add member application
authorSteve Sutton <steve@gaslightmedia.com>
Tue, 4 Jun 2013 15:08:30 +0000 (15:08 +0000)
committerSteve Sutton <steve@gaslightmedia.com>
Tue, 4 Jun 2013 15:08:30 +0000 (15:08 +0000)
337 files changed:
Toolkit/Maps/geoCoder.js [new file with mode: 0644]
Toolkit/Maps/marker.php [new file with mode: 0755]
Toolkit/Maps/marker2.php [new file with mode: 0644]
Toolkit/Members.php [new file with mode: 0644]
Toolkit/Members/AddPhoto.php [new file with mode: 0644]
Toolkit/Members/AddYourBusiness.php [new file with mode: 0755]
Toolkit/Members/Admin/AddPhoto.php [new file with mode: 0644]
Toolkit/Members/Admin/AdvancedSearch.php [new file with mode: 0644]
Toolkit/Members/Admin/AdvancedSearchController.php [new file with mode: 0644]
Toolkit/Members/Admin/AdvancedSearchDataGrid.php [new file with mode: 0644]
Toolkit/Members/Admin/AmenitiesController.php [new file with mode: 0644]
Toolkit/Members/Admin/AuthorizeNewMemberForm.php [new file with mode: 0755]
Toolkit/Members/Admin/AuthorizeUpdates.php [new file with mode: 0755]
Toolkit/Members/Admin/Auxiliary.php [new file with mode: 0644]
Toolkit/Members/Admin/BasicSearch.php [new file with mode: 0644]
Toolkit/Members/Admin/BillingController.php [new file with mode: 0644]
Toolkit/Members/Admin/CategoriesController.php [new file with mode: 0644]
Toolkit/Members/Admin/CitiesController.php [new file with mode: 0644]
Toolkit/Members/Admin/CountiesController.php [new file with mode: 0644]
Toolkit/Members/Admin/EditAmenity.php [new file with mode: 0644]
Toolkit/Members/Admin/EditCategory.php [new file with mode: 0644]
Toolkit/Members/Admin/EditCity.php [new file with mode: 0644]
Toolkit/Members/Admin/EditCounty.php [new file with mode: 0644]
Toolkit/Members/Admin/EditHtmlEmail.php [new file with mode: 0644]
Toolkit/Members/Admin/EditPackages.php [new file with mode: 0644]
Toolkit/Members/Admin/EditPhoto.php [new file with mode: 0644]
Toolkit/Members/Admin/EditRegion.php [new file with mode: 0644]
Toolkit/Members/Admin/ExportController.php [new file with mode: 0644]
Toolkit/Members/Admin/ExportFileForm.php [new file with mode: 0644]
Toolkit/Members/Admin/ExportMembers.php [new file with mode: 0644]
Toolkit/Members/Admin/IndexController.php [new file with mode: 0644]
Toolkit/Members/Admin/InvoicingController.php [new file with mode: 0644]
Toolkit/Members/Admin/ListAmenities.php [new file with mode: 0644]
Toolkit/Members/Admin/ListCategories.php [new file with mode: 0644]
Toolkit/Members/Admin/ListCities.php [new file with mode: 0644]
Toolkit/Members/Admin/ListCounties.php [new file with mode: 0644]
Toolkit/Members/Admin/ListHtmlEmails.php [new file with mode: 0644]
Toolkit/Members/Admin/ListMembers.php [new file with mode: 0644]
Toolkit/Members/Admin/ListNewRequests.php [new file with mode: 0755]
Toolkit/Members/Admin/ListPendingMembers.php [new file with mode: 0755]
Toolkit/Members/Admin/ListRegions.php [new file with mode: 0644]
Toolkit/Members/Admin/MailOut.php [new file with mode: 0644]
Toolkit/Members/Admin/MailOutForm.php [new file with mode: 0644]
Toolkit/Members/Admin/MemberReportSearch.php [new file with mode: 0644]
Toolkit/Members/Admin/MembersController.php [new file with mode: 0644]
Toolkit/Members/Admin/Navigation.php [new file with mode: 0644]
Toolkit/Members/Admin/NewsletterController.php [new file with mode: 0644]
Toolkit/Members/Admin/Newsletters.php [new file with mode: 0644]
Toolkit/Members/Admin/PaymentController.php [new file with mode: 0644]
Toolkit/Members/Admin/PreviewHtmlEmail.php [new file with mode: 0644]
Toolkit/Members/Admin/RegionsController.php [new file with mode: 0644]
Toolkit/Members/Admin/ReportsController.php [new file with mode: 0644]
Toolkit/Members/Admin/Search.php [new file with mode: 0644]
Toolkit/Members/Admin/SettingsController.php [new file with mode: 0644]
Toolkit/Members/Auth.php [new file with mode: 0644]
Toolkit/Members/AuthContainer.php [new file with mode: 0644]
Toolkit/Members/Auxiliary.php [new file with mode: 0644]
Toolkit/Members/Billing/AdminNavigation.php [new file with mode: 0644]
Toolkit/Members/Billing/Auxiliary.php [new file with mode: 0644]
Toolkit/Members/Billing/Billing.php [new file with mode: 0644]
Toolkit/Members/Billing/Database/application.sql [new file with mode: 0644]
Toolkit/Members/Billing/Database/tables/billing.sql [new file with mode: 0644]
Toolkit/Members/Billing/Database/tables/member.sql [new file with mode: 0644]
Toolkit/Members/Billing/Database/tables/member_account.sql [new file with mode: 0644]
Toolkit/Members/Billing/Database/tables/payment_types.sql [new file with mode: 0644]
Toolkit/Members/Billing/EditBillingForm.php [new file with mode: 0644]
Toolkit/Members/Billing/EditMemberAccount.php [new file with mode: 0644]
Toolkit/Members/Billing/EditMemberPayment.php [new file with mode: 0644]
Toolkit/Members/Billing/EditPaymentType.php [new file with mode: 0644]
Toolkit/Members/Billing/EmailInvoices.php [new file with mode: 0644]
Toolkit/Members/Billing/Factory.php [new file with mode: 0644]
Toolkit/Members/Billing/IInvoice.php [new file with mode: 0644]
Toolkit/Members/Billing/InvoiceAbstract.php [new file with mode: 0644]
Toolkit/Members/Billing/InvoiceDate.php [new file with mode: 0644]
Toolkit/Members/Billing/InvoiceFilterForm.php [new file with mode: 0644]
Toolkit/Members/Billing/InvoicePdf.php [new file with mode: 0644]
Toolkit/Members/Billing/Invoices.php [new file with mode: 0644]
Toolkit/Members/Billing/ListPaymentTypes.php [new file with mode: 0644]
Toolkit/Members/Billing/MailingLabelPdf.php [new file with mode: 0644]
Toolkit/Members/Billing/MemberAccount.php [new file with mode: 0644]
Toolkit/Members/Billing/MemberLists.php [new file with mode: 0644]
Toolkit/Members/Billing/PaymentForm.php [new file with mode: 0644]
Toolkit/Members/Billing/PaymentTypes.php [new file with mode: 0644]
Toolkit/Members/Billing/PrintInvoices.php [new file with mode: 0644]
Toolkit/Members/Billing/QifExport.php [new file with mode: 0644]
Toolkit/Members/Billing/RecordNavigation.php [new file with mode: 0644]
Toolkit/Members/Billing/Report.php [new file with mode: 0644]
Toolkit/Members/Billing/ReportSearch.php [new file with mode: 0644]
Toolkit/Members/Billing/Statement.php [new file with mode: 0644]
Toolkit/Members/Billing/billing.css [new file with mode: 0644]
Toolkit/Members/Billing/checkInvestmentType.php [new file with mode: 0644]
Toolkit/Members/Billing/config.ini [new file with mode: 0644]
Toolkit/Members/Billing/deleteBilling.php [new file with mode: 0644]
Toolkit/Members/Billing/js/edit-billing.js [new file with mode: 0644]
Toolkit/Members/Billing/pdfInvoice.php [new file with mode: 0644]
Toolkit/Members/Billing/recreateInvoices.php [new file with mode: 0644]
Toolkit/Members/Billing/templates/editBilling.html [new file with mode: 0644]
Toolkit/Members/Billing/templates/editPaymentTypes.html [new file with mode: 0644]
Toolkit/Members/Billing/templates/invoiceFilterForm.html [new file with mode: 0644]
Toolkit/Members/Billing/templates/memberList.html [new file with mode: 0644]
Toolkit/Members/Billing/templates/memberStatements.html [new file with mode: 0644]
Toolkit/Members/Billing/templates/paymentForm.html [new file with mode: 0644]
Toolkit/Members/Billing/templates/reportSearch.html [new file with mode: 0644]
Toolkit/Members/Billing/templates/sendEmailInvoice.html [new file with mode: 0644]
Toolkit/Members/Billing/testMember.php [new file with mode: 0644]
Toolkit/Members/BreadCrumbs.php [new file with mode: 0644]
Toolkit/Members/CategoriesIterator.php [new file with mode: 0644]
Toolkit/Members/Category.php [new file with mode: 0644]
Toolkit/Members/CategoryTree.php [new file with mode: 0644]
Toolkit/Members/City.php [new file with mode: 0644]
Toolkit/Members/Contact.php [new file with mode: 0644]
Toolkit/Members/ContactsDataGrid.php [new file with mode: 0644]
Toolkit/Members/Coupons/EditCouponForm.php [new file with mode: 0644]
Toolkit/Members/Coupons/Mailer.php [new file with mode: 0644]
Toolkit/Members/Database/application.sql [new file with mode: 0644]
Toolkit/Members/Database/procedures/explode_members_name_POST_8.3.sql [new file with mode: 0644]
Toolkit/Members/Database/procedures/explode_members_name_PRE_8.3.sql [new file with mode: 0644]
Toolkit/Members/Database/procedures/last_record_update_timestamp.sql [new file with mode: 0644]
Toolkit/Members/Database/removeApplication.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/amenity.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/banners2membercategories.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/category.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/category_amenities.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/ccard_type.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/city.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/county.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/exploded_members_name.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/exposure.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_accommodations.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_amenity.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_categories2toolbox_pages.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_categories2toolbox_pages_draft.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_category.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_ccard_type.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_contacts.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_files.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_golf.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_last_updates.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_leads.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_newsletters.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_packages.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_photos.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_regions2toolbox_pages.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_regions2toolbox_pages_draft.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_restaurants.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_session.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/member_updates.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/region.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/state.sql [new file with mode: 0644]
Toolkit/Members/Database/tables/streamsend.sql [new file with mode: 0644]
Toolkit/Members/Database/utilities/unnest.sql [new file with mode: 0644]
Toolkit/Members/Database/utilities/update_exploded_members_name_table_POST_8.3.sql [new file with mode: 0644]
Toolkit/Members/Database/utilities/update_exploded_members_name_table_PRE_8.3.sql [new file with mode: 0644]
Toolkit/Members/Display.php [new file with mode: 0644]
Toolkit/Members/EditContactForm.php [new file with mode: 0644]
Toolkit/Members/EditMemberAmenities.php [new file with mode: 0644]
Toolkit/Members/EditMemberContacts.php [new file with mode: 0644]
Toolkit/Members/EditMemberFile.php [new file with mode: 0644]
Toolkit/Members/EditMemberInfo.php [new file with mode: 0644]
Toolkit/Members/EditMemberOnlyAmenities.php [new file with mode: 0644]
Toolkit/Members/EditMemberOnlyContacts.php [new file with mode: 0644]
Toolkit/Members/EditMemberOnlyFile.php [new file with mode: 0644]
Toolkit/Members/EditMemberOnlyInfo.php [new file with mode: 0644]
Toolkit/Members/EditPackages.php [new file with mode: 0644]
Toolkit/Members/EditPhoto.php [new file with mode: 0644]
Toolkit/Members/Events/CommonEditEvent.php [new file with mode: 0644]
Toolkit/Members/Events/EditEvent.php [new file with mode: 0755]
Toolkit/Members/Events/templates/emailOwner.tpl [new file with mode: 0755]
Toolkit/Members/Exception.php [new file with mode: 0644]
Toolkit/Members/Exposure.php [new file with mode: 0755]
Toolkit/Members/ExposureDetailReports.php [new file with mode: 0755]
Toolkit/Members/ExposureReports.php [new file with mode: 0755]
Toolkit/Members/FileDownload.php [new file with mode: 0644]
Toolkit/Members/Import/ActionDisplay.php [new file with mode: 0644]
Toolkit/Members/Import/ActionUpload.php [new file with mode: 0644]
Toolkit/Members/Import/AnalyzePage.php [new file with mode: 0644]
Toolkit/Members/Import/ConversionPage.php [new file with mode: 0644]
Toolkit/Members/Import/DBPage.php [new file with mode: 0644]
Toolkit/Members/Import/FieldsPage.php [new file with mode: 0644]
Toolkit/Members/Import/FilePage.php [new file with mode: 0644]
Toolkit/Members/Import/ImportPage.php [new file with mode: 0644]
Toolkit/Members/Import/OpPage.php [new file with mode: 0644]
Toolkit/Members/Import/Page.php [new file with mode: 0644]
Toolkit/Members/Import/ServerPage.php [new file with mode: 0644]
Toolkit/Members/Import/index.php [new file with mode: 0644]
Toolkit/Members/Import/templates/template.html [new file with mode: 0644]
Toolkit/Members/Leads/ExportFileForm.php [new file with mode: 0644]
Toolkit/Members/Leads/ExportLeads.php [new file with mode: 0644]
Toolkit/Members/Leads/libjs/visitorLeads.js [new file with mode: 0644]
Toolkit/Members/Map.php [new file with mode: 0644]
Toolkit/Members/Member.php [new file with mode: 0644]
Toolkit/Members/MemberImport/Category.php [new file with mode: 0644]
Toolkit/Members/MemberImport/City.php [new file with mode: 0644]
Toolkit/Members/MemberImport/FileForm.php [new file with mode: 0644]
Toolkit/Members/MemberImport/Import.php [new file with mode: 0644]
Toolkit/Members/MemberImport/ImportForm.php [new file with mode: 0644]
Toolkit/Members/MemberImport/Member.php [new file with mode: 0644]
Toolkit/Members/MemberImport/State.php [new file with mode: 0644]
Toolkit/Members/MemberImport/index.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/BreadCrumbs.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/CommonEventsController.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/Controller.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/CouponsController.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/EditProfileController.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/EventsController.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/IndexController.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/LeadsController.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/Navigation/Factory.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/Navigation/Side.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/ReportsController.php [new file with mode: 0644]
Toolkit/Members/MembersOnly/index.php [new file with mode: 0644]
Toolkit/Members/PackageList.php [new file with mode: 0644]
Toolkit/Members/Packages.php [new file with mode: 0644]
Toolkit/Members/Packages/Package.php [new file with mode: 0644]
Toolkit/Members/Photos.php [new file with mode: 0644]
Toolkit/Members/Photos/Photo.php [new file with mode: 0644]
Toolkit/Members/ProfilePage.php [new file with mode: 0644]
Toolkit/Members/ProfileWriter.php [new file with mode: 0644]
Toolkit/Members/RecordNavigation.php [new file with mode: 0644]
Toolkit/Members/Rules/DuplicateMember.php [new file with mode: 0644]
Toolkit/Members/Rules/MemberFile.php [new file with mode: 0644]
Toolkit/Members/Rules/MemberLogin.php [new file with mode: 0644]
Toolkit/Members/SearchList.php [new file with mode: 0644]
Toolkit/Members/SearchQueryGenerator.php [new file with mode: 0644]
Toolkit/Members/StreamSend.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/AuthContainer.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/Forgot.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/Sessions.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/TripAuth.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/googleMapData.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/helpme.html [new file with mode: 0644]
Toolkit/Members/TripPlanner/login.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/memberList.php [new file with mode: 0755]
Toolkit/Members/TripPlanner/tripPlannerMap.php [new file with mode: 0644]
Toolkit/Members/TripPlanner/wish-list.php [new file with mode: 0755]
Toolkit/Members/TripPlannerList.php [new file with mode: 0644]
Toolkit/Members/UserSearchForm.php [new file with mode: 0644]
Toolkit/Members/UserSearchForm.php.save [new file with mode: 0644]
Toolkit/Members/addressHelp.html [new file with mode: 0644]
Toolkit/Members/assets/.keepme [new file with mode: 0644]
Toolkit/Members/assets/btn_close.gif [new file with mode: 0755]
Toolkit/Members/assets/btn_planneractions.gif [new file with mode: 0755]
Toolkit/Members/assets/btn_submit.gif [new file with mode: 0755]
Toolkit/Members/assets/saveplanner.gif [new file with mode: 0755]
Toolkit/Members/config.ini [new file with mode: 0644]
Toolkit/Members/css/member-admin.css [new file with mode: 0755]
Toolkit/Members/css/member.css [new file with mode: 0755]
Toolkit/Members/export-images-is0.php [new file with mode: 0755]
Toolkit/Members/libjs/advancedsearch.js [new file with mode: 0644]
Toolkit/Members/libjs/authorizeChanges.js [new file with mode: 0644]
Toolkit/Members/libjs/business-detail.js [new file with mode: 0755]
Toolkit/Members/libjs/business-search.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-amenity.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-category.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-city.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-county.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-html-email.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-member-amenities.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-member-contacts.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-member-files.js [new file with mode: 0644]
Toolkit/Members/libjs/edit-member-packages.js [new file with mode: 0755]
Toolkit/Members/libjs/edit-member-photos.js [new file with mode: 0755]
Toolkit/Members/libjs/edit-member.js [new file with mode: 0755]
Toolkit/Members/libjs/edit-region.js [new file with mode: 0644]
Toolkit/Members/libjs/google-map.js [new file with mode: 0644]
Toolkit/Members/libjs/list-categories.js [new file with mode: 0644]
Toolkit/Members/libjs/member-list.js [new file with mode: 0644]
Toolkit/Members/libjs/member-pending-list.js [new file with mode: 0644]
Toolkit/Members/libjs/new-member-sign-up.js [new file with mode: 0755]
Toolkit/Members/libjs/travel-list.js [new file with mode: 0644]
Toolkit/Members/libjs/trip-planner-map.js [new file with mode: 0644]
Toolkit/Members/memberClickThru.php [new file with mode: 0644]
Toolkit/Members/memberDBGoogleAreaMap.php [new file with mode: 0644]
Toolkit/Members/memberDBGoogleMap.php [new file with mode: 0644]
Toolkit/Members/memberFileDownload.php [new file with mode: 0644]
Toolkit/Members/memberdb.css [new file with mode: 0644]
Toolkit/Members/sortPhotos.php [new file with mode: 0644]
Toolkit/Members/templates/addPackage.tpl [new file with mode: 0644]
Toolkit/Members/templates/addPhoto.tpl [new file with mode: 0644]
Toolkit/Members/templates/addYourBusinessAdminEmail.tpl [new file with mode: 0755]
Toolkit/Members/templates/addYourBusinessMemberEmail.tpl [new file with mode: 0644]
Toolkit/Members/templates/admin.tpl [new file with mode: 0644]
Toolkit/Members/templates/authorizeChanges.tpl [new file with mode: 0644]
Toolkit/Members/templates/currentTables/Element.tpl [new file with mode: 0644]
Toolkit/Members/templates/currentTables/Form.tpl [new file with mode: 0644]
Toolkit/Members/templates/currentTables/Group.tpl [new file with mode: 0644]
Toolkit/Members/templates/currentTables/GroupElement.tpl [new file with mode: 0644]
Toolkit/Members/templates/currentTables/Header.tpl [new file with mode: 0644]
Toolkit/Members/templates/currentTables/RequiredNote.tpl [new file with mode: 0644]
Toolkit/Members/templates/editAmenities.tpl [new file with mode: 0644]
Toolkit/Members/templates/editAmenity.tpl [new file with mode: 0644]
Toolkit/Members/templates/editBilling.tpl [new file with mode: 0644]
Toolkit/Members/templates/editCategory.tpl [new file with mode: 0644]
Toolkit/Members/templates/editCity.tpl [new file with mode: 0644]
Toolkit/Members/templates/editContact.html [new file with mode: 0644]
Toolkit/Members/templates/editContacts.tpl [new file with mode: 0644]
Toolkit/Members/templates/editCounty.tpl [new file with mode: 0644]
Toolkit/Members/templates/editCouponEmail.tpl [new file with mode: 0755]
Toolkit/Members/templates/editFile.tpl [new file with mode: 0644]
Toolkit/Members/templates/editHtmlEmail.tpl [new file with mode: 0644]
Toolkit/Members/templates/editMember.tpl [new file with mode: 0644]
Toolkit/Members/templates/editPackage.tpl [new file with mode: 0644]
Toolkit/Members/templates/editPackages.tpl [new file with mode: 0644]
Toolkit/Members/templates/editPhoto.tpl [new file with mode: 0644]
Toolkit/Members/templates/editPhotoGallery.tpl [new file with mode: 0644]
Toolkit/Members/templates/editRegion.tpl [new file with mode: 0644]
Toolkit/Members/templates/emailOwner.tpl [new file with mode: 0644]
Toolkit/Members/templates/exposureDetail.tpl [new file with mode: 0755]
Toolkit/Members/templates/exposureList.tpl [new file with mode: 0755]
Toolkit/Members/templates/htmlEmailBody.tpl [new file with mode: 0644]
Toolkit/Members/templates/listAmenities.tpl [new file with mode: 0644]
Toolkit/Members/templates/listCategories.tpl [new file with mode: 0644]
Toolkit/Members/templates/listCities.tpl [new file with mode: 0644]
Toolkit/Members/templates/listContacts.html [new file with mode: 0644]
Toolkit/Members/templates/listCounties.tpl [new file with mode: 0644]
Toolkit/Members/templates/listHtmlEmails.tpl [new file with mode: 0644]
Toolkit/Members/templates/listMembers.tpl [new file with mode: 0644]
Toolkit/Members/templates/listNewMembers.tpl [new file with mode: 0644]
Toolkit/Members/templates/listPendingMembers.tpl [new file with mode: 0644]
Toolkit/Members/templates/listRegions.tpl [new file with mode: 0644]
Toolkit/Members/templates/memberContactsList.tpl [new file with mode: 0644]
Toolkit/Members/templates/memberDetail.tpl [new file with mode: 0644]
Toolkit/Members/templates/memberNewsletter.tpl [new file with mode: 0755]
Toolkit/Members/templates/memberSearchForm.tpl [new file with mode: 0644]
Toolkit/Members/templates/membersList.tpl [new file with mode: 0644]
Toolkit/Members/templates/newMemberApproval.tpl [new file with mode: 0755]
Toolkit/Members/templates/newMemberDenial.tpl [new file with mode: 0755]
Toolkit/Members/templates/previewHtmlEmail.tpl [new file with mode: 0644]
Toolkit/Members/templates/previewNewsletterWrapper.html [new file with mode: 0644]
Toolkit/Members/templates/settings.html [new file with mode: 0644]
Toolkit/Members/templates/tripPlannerList.tpl [new file with mode: 0644]
Toolkit/Members/templates/tripPlannerNoList.tpl [new file with mode: 0644]
Toolkit/Members/templates/userSearchForm.html [new file with mode: 0644]
Toolkit/Membersonly.php [new file with mode: 0644]
Toolkit/Tree.php [new file with mode: 0644]
admin/members.php [new file with mode: 0755]

diff --git a/Toolkit/Maps/geoCoder.js b/Toolkit/Maps/geoCoder.js
new file mode 100644 (file)
index 0000000..302b839
--- /dev/null
@@ -0,0 +1,164 @@
+// Option would be to make this configurable so it can be used
+// with one field (loc) like event
+// or multiple fields like member (street, city, state, zip)
+var GLM_GeoMap = {
+    defaultLat: 45.3748385,
+    defaultLon: -84.9592251,
+    geocoder: null,
+    map: null,
+    setDefaultLat: function(lat) {
+      GLM_GeoMap.defaultLat = lat;
+    },
+    setDefaultLon: function(lon) {
+        GLM_GeoMap.defaultLon = lon;
+    },
+    initialize: function() {
+        GLM_GeoMap.createMap();
+        var lat = $("#lat").val();
+        var lon = $("#lon").val();
+        if ($("#loc").length > 0) {
+            var location = $("#loc").val();
+        } else {
+            var location = null;
+        }
+        if ($("#address").length > 0) {
+            var street = $("#address").val();
+        }
+        if ($("#city").length > 0) {
+            var city = $("#city").val();
+        }
+        if ($("#state").length > 0) {
+            var state = $("#state").val();
+        }
+        if ($("#zip").length > 0) {
+            var zip = $("#zip").val();
+        }
+
+        if (lat && lon) {
+            GLM_GeoMap.createWithLatLon();
+        } else if (location) {
+            GLM_GeoMap.createWithLocation(location);
+        } else if (street || city || state || zip) {
+            GLM_GeoMap.createWithAddress(street, city, state, zip);
+        } else {
+            GLM_GeoMap.createWithClientLocation();
+        }
+    },
+    initializeWithNewLocation: function(location) {
+        GLM_GeoMap.createMap();
+        GLM_GeoMap.createWithLocation(location);
+    },
+    createMap: function() {
+        var myOptions = {
+            zoom: 15,
+            mapTypeId: google.maps.MapTypeId.ROADMAP
+        };
+        GLM_GeoMap.map = new google.maps.Map(
+            document.getElementById("map_canvas"),
+            myOptions
+        );
+    },
+    addMarkerToMap: function(LatLng) {
+        var marker = new google.maps.Marker({
+            map: GLM_GeoMap.map,
+            position: LatLng,
+            draggable: true
+        });
+        var location = marker.getPosition();
+        GLM_GeoMap.updateLatLonDiv(location);
+        google.maps.event.addListener(marker, 'dragend', function(){
+            var location = marker.getPosition();
+            GLM_GeoMap.updateLatLonDiv(location);
+        });
+        GLM_GeoMap.map.setCenter(LatLng);
+        GLM_GeoMap.map.setZoom(15);
+    },
+    updateLatLonDiv: function(point) {
+        $("#lat").val(point.lat());
+        $("#lon").val(point.lng());
+    },
+    createWithClientLocation: function() {
+        // Try HTML5 geolocation
+        if (navigator.geolocation) {
+            navigator.geolocation.getCurrentPosition(function(position) {
+                var pos = new google.maps.LatLng(
+                    position.coords.latitude,
+                    position.coords.longitude
+                );
+                GLM_GeoMap.addMarkerToMap(pos);
+            }, function() {
+                GLM_GeoMap.handleNoGeolocation(true);
+            });
+        }
+    },
+    createWithLatLon: function() {
+        GLM_GeoMap.addMarkerToMap(new google.maps.LatLng(
+            $("#lat").val(),
+            $("#lon").val()
+        ));
+    },
+    createWithDefaultLatLon: function() {
+
+        GLM_GeoMap.addMarkerToMap(new google.maps.LatLng(
+            GLM_GeoMap.defaultLat,
+            GLM_GeoMap.defaultLon
+        ));
+    },
+    createWithLocation: function(address) {
+        GLM_GeoMap.geocoder = new google.maps.Geocoder();
+        GLM_GeoMap.geocoder.geocode(
+            {'address': address},
+            function(results, status) {
+                if (status == google.maps.GeocoderStatus.OK) {
+                    GLM_GeoMap.map.setCenter(results[0].geometry.location);
+                    GLM_GeoMap.addMarkerToMap(results[0].geometry.location);
+                } else {
+                    GLM_GeoMap.createWithClientLocation();
+                }
+            }
+        );
+    },
+    createWithAddress: function(street, city, state, zip) {
+        var location = "";
+        if (street) {
+            location += street + ",";
+        }
+        if (city) {
+            location += city + ",";
+        }
+        if (state) {
+            location += state + ",";
+        }
+        if (zip) {
+            location += zip + ",";
+        }
+        GLM_GeoMap.geocoder = new google.maps.Geocoder();
+        GLM_GeoMap.geocoder.geocode(
+            {'address': location},
+            function(results, status) {
+                if (status == google.maps.GeocoderStatus.OK) {
+                    GLM_GeoMap.map.setCenter(results[0].geometry.location);
+                    GLM_GeoMap.addMarkerToMap(results[0].geometry.location);
+                } else {
+                    GLM_GeoMap.createWithClientLocation();
+                }
+            }
+        );
+    },
+    handleNoGeolocation: function(errorFlag) {
+        if (errorFlag) {
+            var content = 'Error: The Geolocation service failed.';
+        } else {
+            var content = 'Error: Your browser doesn\'t support geolocation.';
+        }
+
+        var options = {
+            map: GLM_GeoMap.map,
+            position: new google.maps.LatLng(60, 105),
+            content: content
+        };
+
+        var infowindow = new google.maps.InfoWindow(options);
+        GLM_GeoMap.map.setCenter(options.position);
+    }
+}
\ No newline at end of file
diff --git a/Toolkit/Maps/marker.php b/Toolkit/Maps/marker.php
new file mode 100755 (executable)
index 0000000..0a5e5f5
--- /dev/null
@@ -0,0 +1,100 @@
+<?php
+require_once '../../setup.phtml';
+// filter any input
+$color = filter_input(INPUT_GET, 'color', FILTER_SANITIZE_STRING);
+$text  = filter_input(INPUT_GET, 'text', FILTER_SANITIZE_STRING);
+// check to see if this png already exists (cache)
+if (!strstr($color, ".") && !is_dir("./iconCache/".$color)) {
+    $oldUmask = umask(0);
+    mkdir("./iconCache/".$color, 0777, true);
+    umask($oldUmask);
+}
+$fileName = "./iconCache/".$color."/map-".$text.".png";
+if (is_file($fileName)) {
+    header("Content-type: image/png");
+    $fn = fopen($fileName, "r");
+    fpassthru($fn);
+    fclose($fn);
+    exit;
+}
+if (!$color) {
+    $color = "ff776b";  //default google map color
+}
+$color = str_replace("#", "", $color);
+
+$font = GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/Arial_Bold.ttf';
+
+//unfortunately we still must do some offsetting
+switch (ord(substr($text,0,1))) {
+    case 49: //1
+        $offset = -2;
+        break;
+    case 55: //7
+        $offset = -1;
+        break;
+    case 65: //A
+        $offset = 1;
+        break;
+    case 74: //J
+        $offset = -1;
+        break;
+    case 84: //T
+        $offset = 1;
+        break;
+    case 99: //c
+        $offset = -1;
+        break;
+    case 106: //j
+        $offset = 1;
+        break;
+    default:
+       $offset = -2;
+       break;
+}
+if ((int)$text > 99) {
+   $offset = 2;
+} else if ((int)$text > 9) {
+   $offset = 0;
+} else {
+   $offset = -3;
+}
+//$offset = 0; //reset offset
+if (strlen($text) == 1) {
+    $fontsize = 12.5;
+} else if (strlen($text) == 2) {
+    $fontsize = 11;
+} else if (strlen($text) == 3) {
+    $fontsize = 10;
+} else {
+    $fontsize = 10.5;
+    $offset = 0; //reset offset
+    $text = null;//chr(149);
+}
+
+$bbox = imagettfbbox($fontsize, 0, $font, $text);
+$width = $bbox[2] - $bbox[0] + 1;
+$height = $bbox[1] - $bbox[7] + 1;
+
+$image_name = "../../assets/blue.png";
+$im = imagecreatefrompng($image_name);
+imageAlphaBlending($im, true);
+imageSaveAlpha($im, true);
+$black = imagecolorallocate($im, 0, 0, 0);
+
+if ($text) {
+    imagettftext(
+        $im,            // image resource
+        $fontsize,      // font size
+        0,              // angle
+        8 - $offset,    // x
+        15 + $height/2, // y
+        $black,         // color
+        $font,          // font file
+        $text         // text
+    );
+}
+
+header("Content-type: image/png");
+imagepng($im);
+imagepng($im, $fileName);
+imagedestroy($im);
diff --git a/Toolkit/Maps/marker2.php b/Toolkit/Maps/marker2.php
new file mode 100644 (file)
index 0000000..7b58058
--- /dev/null
@@ -0,0 +1,38 @@
+<?php
+require_once '../../setup.phtml';
+$color = filter_input(INPUT_GET, 'color', FILTER_SANITIZE_STRING);
+if (!strstr($color, ".") && !is_dir("./iconCache/".$color)) {
+    $oldUmask = umask(0);
+    mkdir("./iconCache/".$color, 0777, true);
+    umask($oldUmask);
+}
+$fileName = "./iconCache/{$color}/map.png";
+if (is_file($fileName)) {
+    header("Content-type: image/png");
+    $fn = fopen($fileName, "r");
+    fpassthru($fn);
+    fclose($fn);
+    exit;
+}
+$image_name = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%20|{$color}|000000&ext=.png";
+
+//var_dump($image_name);exit;
+$ch = curl_init();
+curl_setopt ($ch, CURLOPT_URL, $image_name);
+curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
+
+// Getting binary data
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
+
+$image_string = curl_exec($ch);
+//var_dump($image_string);exit;
+//curl_close($ch);
+
+$im = imagecreatefromstring ($image_string);
+//imagecolortransparent($im, '000000');
+imagesavealpha($im, true);
+header("Content-type: image/png");
+imagepng($im);
+imagepng($im, $fileName);
+imagedestroy($im);
\ No newline at end of file
diff --git a/Toolkit/Members.php b/Toolkit/Members.php
new file mode 100644 (file)
index 0000000..540b28c
--- /dev/null
@@ -0,0 +1,430 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Driver for admin side processing of member data
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: Members.php,v 1.38 2010/07/16 20:51:05 jamie Exp $
+ * @link     http://demo.gaslightmedia.com
+ */
+
+/**
+ * Base class for the memberdb
+ *
+ * @category  Toolkit
+ * @package   Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members
+{
+       //      {{{     __construct()
+
+       /**
+        * Constructor
+        *
+        * @access      public
+        */
+       public function __construct()
+       {
+        HTTP_Session2::useCookies(false);
+        HTTP_Session2::start('MemberDB');
+        if (HTTP_Session2::get('newSearch')) {
+            HTTP_Session2::set('newSearch', false);
+            HTTP_Session2::set(
+                               'searchResults',
+                               urldecode($_SERVER['HTTP_REFERER'])
+                       );
+        }
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Determine which form to show to the user
+        *
+        * When editing a member the (a)ction in the URL controls
+        * which form is displayed to the user. Member Id's from
+        * the database should be passed along as the ID in the $_GET array.
+        *
+        * @return void
+        * @access public
+        */
+       public function toHtml()
+       {
+               $pdo = Toolkit_Database::getInstance();
+        //  application configuration
+        $conf = new Config;
+        $root =& $conf->parseConfig(
+                       BASE . 'Toolkit/Members/config.ini',
+                       'IniFile'
+               );
+
+               $nav = new Toolkit_Members_RecordNavigation($root);
+               $nav->setupAdminNavStructure();
+
+        $tplOpts =  Toolkit_Members::getFlexyOptions();
+        $tEngine = new HTML_Template_Flexy($tplOpts);
+
+               switch ($_GET['tab']) {
+        case 'invoices' :
+                       $GLOBALS['styleSheets'][]
+                               = BASE_URL . 'Toolkit/Members/Billing/billing.css';
+            if ($_REQUEST['returnPdf']) {
+                $statement = new Toolkit_Members_Billing_Invoices();
+                $statement->pdfToBrowser(
+                    $pdo,
+                    $_REQUEST['invoice_id']
+                );
+                exit;
+            }
+            if ($_REQUEST['editBilling'] == '1') {
+                $billingForm = new Toolkit_Members_Billing_EditBillingForm(
+                    $pdo,
+                    'edit-billing-form',
+                    'post',
+                    BASE_URL . "admin/members.php?id={$_REQUEST['id']}"
+                    . "&rt=Members&ac=editMember&tab=invoices&editBilling=1"
+                );
+                $billingForm->configureForm();
+                $out .= $billingForm->toHtml();
+            } else if ($_REQUEST['full']) {
+                $nav = new Toolkit_Members_RecordNavigation($root);
+                $nav->setupAdminNavStructure();
+                $out  = '<div id="nav-detail">'.$nav->getPageNav().'</div>';
+                $statement = new Toolkit_Members_Billing_Statement();
+                $out .= $statement->createMemberStatements(
+                    $pdo,
+                    $_REQUEST['id'],
+                    true
+                );
+            } else {
+                $mc = new Toolkit_Members_Billing_EditMemberPayment(
+                    $pdo,
+                    'edit_billing',
+                    'post',
+                    null,
+                    null,
+                    null,
+                    true
+                );
+                $mc->configureForm();
+                $out = '';
+                if ($_REQUEST['formSubmitGood']) {
+                    $out = '<div id="form-success-top">
+                        The information below has been successfully submitted.
+                    </div>';
+                }
+                $out .= $mc->toHtml();
+            }
+            break;
+
+        case 'billingInfo' :
+            $mc = new Toolkit_Members_Billing_EditMemberAccount(
+                $pdo,
+                'edit_billing',
+                'post',
+                null,
+                null,
+                null,
+                true
+            );
+            $sql = "
+              SELECT id
+                FROM member_account
+               WHERE member_id = :member_id
+            ORDER BY id";
+            try {
+                $stmt = $pdo->prepare($sql);
+                $stmt->bindParam(
+                    ':member_id',
+                    $_GET['id'],
+                    PDO::PARAM_INT
+                );
+                $stmt->execute();
+                $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
+                if (is_numeric($data[0]['id'])) {
+                    $mc->setPrimaryAccountId($data[0]['id']);
+                }
+                if (is_numeric($data[1]['id'])) {
+                    $mc->setSecondaryAccountId($data[1]['id']);
+                }
+            } catch (PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+            $mc->configureForm();
+            $out = '';
+            if ($_REQUEST['formSubmitGood']) {
+                $out = '<div id="form-success-top">
+                    The information below has been successfully submitted.
+                </div>';
+            }
+            $out .= $mc->toHtml();
+            break;
+               case 'contacts' :
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-contacts.js';
+
+                       if ($_GET['d'] == 't' && ctype_digit($_GET['cid'])) {
+                               Toolkit_Members_Contact::delete($pdo, $_GET['cid']);
+                               $tgt = BASE_URL . "admin/members.php?rt=Members&ac=editMember&tab=contacts&id={$_GET['id']}";
+                               header("Location: $tgt");
+                       }
+
+                       $nav = new Toolkit_Members_RecordNavigation($root);
+               $nav->setupAdminNavStructure();
+                       $out  = '<div id="nav-detail">'.$nav->getPageNav().'</div>';
+                       $out .= '<div id="member-info">';
+
+                       $tEngine = new HTML_Template_Flexy(self::getFlexyOptions());
+                       $editContactForm = new Toolkit_Members_EditContactForm(
+                               'edit_contacts',
+                               'post',
+                               BASE_URL . "admin/members.php?rt=Members&ac=editMember&id={$_GET['id']}&tab=contacts"
+                       );
+                       $editContactForm->configureForm($pdo);
+                       $out .= $editContactForm->toHtml(
+                               $pdo,
+                               new HTML_QuickForm_Renderer_Object(true),
+                               $tEngine
+                       );
+
+                       $rEngine = new Structures_DataGrid_Renderer_Flexy();
+                       $rEngine->setContainer($tEngine);
+                       $contactsList = new Toolkit_Members_ContactsDataGrid($pdo);
+                       $contactsList->setQuery();
+                       $contactsList->setDefaultSort(array('fname' => 'ASC', 'lname' => 'ASC'));
+                       $out .= $contactsList->toHtml($rEngine);
+                       $out .= '</div>';
+                       break;
+
+               case 'files' :
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-files.js';
+
+                       $mf = new Toolkit_Members_EditMemberFile($pdo, 'edit_files');
+            $mf->setConfig($root);
+            $mf->configureForm();
+                       $out = $mf->toHtml();
+                       break;
+
+               case 'amenities' :
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-amenities.js';
+
+                       $ma = new Toolkit_Members_EditMemberAmenities(
+                               $pdo,
+                'edit_amenities',
+                'post',
+                null,
+                null,
+                null,
+                true
+                       );
+            $ma->setConfig($root);
+            $ma->configureForm();
+                       $out = $ma->toHtml();
+                       break;
+
+               case 'packages' :
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-packages.js';
+
+            $mp = new Toolkit_Members_Admin_EditPackages($pdo, $tEngine);
+            $mp->setupPage();
+            $out = $mp->getPage($nav);
+                       break;
+
+               case 'photos' :
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-photos.js';
+
+            //  Object to use when rendering the page template
+            $page = new stdClass();
+            //  Page navigation
+            $page->nav = $nav->getPageNav();
+
+            //  Linked List of member photos
+            $linkedList = new Toolkit_Members_Photos(null, $_GET['id']);
+            $linkedList->createMemberList(
+                               $pdo,
+                               $root
+                       );
+            //  Member Object to get calculate attributes about a member
+            $member = new Toolkit_Members_Member(
+                               $pdo,
+                               $root
+                       );
+            //  Server side caching
+            $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+            //  Image server for processing uploaded images
+            $is = new Toolkit_Image_Server();
+
+            if ($member->canAddPhotos($linkedList, $root)) {
+                $aForm = new Toolkit_Members_Admin_AddPhoto(
+                                       $pdo,
+                    'new_member_photo',
+                    'post',
+                    BASE_URL . "admin/members.php?rt=Members&ac=editMember&tab=photos&id={$_GET['id']}",
+                    '',
+                    null,
+                    true
+                               );
+                $aForm->configureForm($root);
+                $page->uploadForm = $aForm->toHtml(
+                    $tEngine,
+                    $cache,
+                    $root,
+                    $is,
+                    $linkedList
+                );
+            }
+
+            if ($member->hasUploadedPhotos($linkedList)) {
+                $editForms = array();
+                $linkedList->rewind();
+
+                foreach ($linkedList as $i) {
+                    if (!$i->getPending()) {
+                        $id = $i->getId();
+                        $eForm = new Toolkit_Members_Admin_EditPhoto(
+                                                       $pdo,
+                            $linkedList,
+                            "edit_member_photo_$id",
+                            'post',
+                            BASE_URL . "admin/members.php?rt=Members&ac=editMember&tab=photos&id={$_GET['id']}",
+                            '',
+                            array('id' => $id),
+                            true
+                                               );
+                        $eForm->configureForm($root);
+                        $page->editForms[$id] = $eForm->toHtml(
+                            $tEngine,
+                            $cache,
+                            $is,
+                            $root
+                        );
+                    }
+                }
+            }
+
+            //  get reference to [photos] section of config file
+            $config =& $root->getItem('section', 'photos');
+            $template =& $config->getItem('directive', 'editGalleryTemplate');
+
+            $tEngine->compile($template->getContent());
+            $out = $tEngine->bufferedOutputObject($page);
+                       break;
+
+               case 'info' :
+               default :
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member.js';
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'gallery/thickbox-3.1.1.js';
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.js';
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'libjs/cluetip/lib/jquery.hoverIntent.js';
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'libjs/cluetip/lib/jquery.bgiframe.min.js';
+                       $GLOBALS['styleSheets'][]
+                               = GLM_APP_BASE_URL . 'gallery/thickbox.css';
+                       $GLOBALS['styleSheets'][]
+                               = GLM_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.css';
+
+                       $mr = new Toolkit_Members_EditMemberInfo(
+                               $pdo,
+                'edit_member',
+                'post',
+                null,
+                null,
+                null,
+                true
+                       );
+
+            $mr->setStates(
+                               Toolkit_Common::getStates($pdo)
+                       );
+            $mr->setCities(
+                               Toolkit_Common::getCities($pdo)
+                       );
+            $mr->setConfig($root);
+            $mr->configureForm();
+                       $out = $mr->toHtml();
+                       break;
+               }
+
+               return $out;
+       }
+
+       //      }}}
+
+       //      {{{     getCacheOptions()
+
+       /**
+        * Get the cache options defined for the memberdb app
+        *
+        * @return array Cache_Lite options defined for the memberdb app
+        * @access public
+        * @static
+        */
+       public static function getCacheOptions()
+       {
+        $options = $GLOBALS['cacheOptions'];
+        $options['lifeTime'] = (DEVELOPMENT) ? 0: 28800;
+               return $options;
+       }
+
+       //      }}}
+       //      {{{     getFlexyOptions()
+
+       /**
+        * Get the flexy options defined for the memberdb app
+        *
+        * @return array Flexy template options defined for the memberdb app
+        * @access public
+        * @static
+        */
+       public static function getFlexyOptions()
+       {
+               $options                = $GLOBALS['flexyOptions'];
+               $options['templateDir'] = BASE . 'Toolkit/Members/templates/';
+               $options['compileDir']  = BASE . 'Toolkit/Members/templates/compiled/';
+        $options['globals']     = true;
+               return $options;
+       }
+
+       //      }}}
+
+       //      {{{     show()
+
+    /**
+     * Show the page
+     *
+     * @return void
+     * @access public
+     */
+       public function show()
+       {
+               echo $this->toHtml();
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/AddPhoto.php b/Toolkit/Members/AddPhoto.php
new file mode 100644 (file)
index 0000000..c399b67
--- /dev/null
@@ -0,0 +1,203 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles the photos tab in the member record
+ * 
+ * Controls setting up the add photo form if applicable, and rendering
+ * each uploaded photo edit form to edit/delete the photo.
+ * 
+ * PHP version 5
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AddPhoto.php,v 1.3 2009/10/27 14:43:41 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit/Image/Server.php
+ */
+
+
+/**
+ * The image server processing class
+ */
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Form to handle creating a new photo in the members only area
+ * 
+ * Handles inserting new photo into db as a pending photo and creating a
+ * tuple in the member_updates table which will allow the admin to
+ * approve/deny the new photo request.
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_AddPhoto extends Toolkit_Members_Admin_AddPhoto
+{
+       //      {{{ createPendingPhoto()
+
+       /**
+        * Adds photo to member and makes a pending row in the updates table
+        *
+        * Adds a photo to the member_photos table but sets the pending field
+        * to true and then inserts a row into the updates table to make the field
+        * pending.  If the photo gets rejected we will have to delete from both
+        * the updates table and the member_photos table.
+        *
+        * @param array &$values submitted values from the form.
+        *
+        * @return boolean Result of creating a pending photo
+        * @access protected
+        */
+       protected function createPendingPhoto(&$values)
+       {
+               try {
+                       //      Get the last photo inserted.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE pending   = true
+                   AND member_id = :member_id
+                 ORDER BY id DESC";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(
+                ':member_id',
+                $GLOBALS['memberAuth']->getAuthData('member_id'),
+                PDO::PARAM_INT
+            );
+                       $stmt->execute();
+                       $photo = $stmt->fetch();
+
+                       //      Insert the picture into the updates table for approval.
+                       $label    = '<img class="thumb" alt="'.$values['image'].'"
+                                                       src="'.MEMBER_PHOTOS.$values['image'].'">';
+                       $update   = false;
+                       $dataType = 'boolean';
+                       $field    = 'pending';
+
+                       $sql =  "
+                               INSERT INTO " . Toolkit_Membersonly::PENDING_TABLE . "
+                               (member_id, field, update , db_table,
+                                data_type, label, foreign_key)
+                VALUES (:member_id, :field, :update, :db_table,
+                                               :data_type, :label, :foreign_key)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(
+                ':member_id',
+                $GLOBALS['memberAuth']->getAuthData('member_id'),
+                PDO::PARAM_INT
+            );
+                       $stmt->bindParam(':field', $field, PDO::PARAM_STR);
+                       $stmt->bindParam(':update', $update, PDO::PARAM_BOOL);
+                       $stmt->bindParam(':db_table', $this->tableName, PDO::PARAM_STR);
+                       $stmt->bindParam(':data_type', $dataType, PDO::PARAM_STR);
+                       $stmt->bindParam(':label', $label, PDO::PARAM_STR);
+                       $stmt->bindParam(':foreign_key', $photo['id'], PDO::PARAM_STR);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+        //     }}}
+       //      {{{ processData()
+
+       /**
+        * Handles setting up the from processing and which function to get it done
+        *
+        * @param array $values Submitted values from the form.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function processData($values)
+       {
+               try {
+            $this->dbh->beginTransaction();
+            $sql = Toolkit_Common::createSQLInsert(
+                $this->tableName,
+                array_keys($values)
+            );
+
+            $res = Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+
+
+            if ($values['pending']) {
+                $this->createPendingPhoto($values);
+            }
+            $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+
+        header('Location:' . $this->getAttribute('action'));
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+     *
+     * @param HTML_Template_Flexy    $tEngine Templating Engine
+     * @param Cache_Lite             $cache   Caching Engine
+     * @param Config_Container       $c       Application configuration
+     * @param Toolkit_Image_Server   $is      Image Server
+     * @param Toolkit_Members_Photos $ll      Linked List of member photos
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(
+        HTML_Template_Flexy $tEngine,
+        Cache_Lite $cache,
+        Config_Container $c,
+        Toolkit_Image_Server $is,
+        Toolkit_Members_Photos $ll
+    ) {
+               if ($this->validate()) {
+            $config = $c->getItem('section', 'conf');
+            $strictPending = $config->getItem('directive', 'strictPending');
+
+            $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+            $cache->remove("Member-$id", 'Profile');
+
+            //  Inject some data into the submitted values
+            $this->_submitValues['image'] = $is->imageUpload('file');
+            $this->_submitValues['pos'] = $ll->getListSize() + 1;
+            $this->_submitValues['member_id'] = $id;
+            $this->_submitValues['pending'] = (int) $strictPending->getContent();
+
+            unset($this->_submitValues['MAX_FILE_SIZE'],
+                  $this->_submitValues['submit']);
+
+            $this->process(array(&$this, 'processData'), false);
+               }
+
+               $this->setupRenderers($tEngine);
+
+               return $tEngine->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/AddYourBusiness.php b/Toolkit/Members/AddYourBusiness.php
new file mode 100755 (executable)
index 0000000..3f5b5a1
--- /dev/null
@@ -0,0 +1,1606 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * AddYourBusiness.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2008 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AddYourBusiness.php,v 1.40 2010/07/14 23:31:14 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+require_once BASE . 'Toolkit/Members/Rules/DuplicateMember.php';
+require_once BASE . 'Toolkit/Members/Rules/MemberLogin.php';
+
+/**
+ * Creates, Renders, Processes form for request to be added to Business DB
+ *
+ * This Form just sends the primary advisee an HTML email of the data
+ * that was filled in and requires them to add the users to the Business DB
+ * themselves.
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2008 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_AddYourBusiness
+    extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+    /**
+     * PDO
+     * @var pdo
+     * @access private 
+     */
+       private $_dbh;
+    
+    /**
+     * Application configuration
+     * @var Config_Container 
+     */
+       private $_config;
+
+       /**
+        * What do you want the success msg to be if the form validates successfully
+        *
+        * @var         string
+        * @access      protected
+        */
+       protected $successMsg = '
+               <div id="form-success-top">
+                       Your business Information has been successfully submitted.
+                       A representative will be contacting you shortly to follow up.
+               </div>';
+
+       /**
+        * Primary email address to send notification a record has been updated
+        *
+        * Set this value to false and it will turn off the email
+        * update notifications.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $primaryAdvisee;
+
+       /**
+        * Email address of people that might also want to be advised of updates
+        *
+        * A list of all email address that might also want to be advised
+        * updates have been made on a business record. You can add as many
+        * as you would like and they will be CC in the email.
+        *
+        * If you use associative key values then they will be appended
+        * to the email string. i.e.
+        * Jamie Kahgee <jamie.kahgee+secondaryAdvisorTest1@gmail.com>
+        * Other wise the address will just be added.
+        *
+        * N.B. You cannot make this array bigger than 5 people or you will need to
+        * rewrite the function to handle the server spam issue.
+        *
+        * @var array
+        * @access private
+        */
+        protected $secondaryAdvisees = array();
+
+       /**
+        * The default rules to register for validating
+        *
+        * @var array
+        * @access protected
+        */
+       protected $registeredRules = array(
+               'zip',
+               'phone',
+               array(
+                       'checkEmail',
+                       'callback',
+                       'email',
+                       'Validate'
+               ),
+               array(
+                       'checkURI',
+                       'callback',
+                       'uri',
+                       'Validate'
+               )
+       );
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Constructor
+        *
+        * @param PDO              $pdo         PHP Data Object to use for DB calls
+        * @param Config_Container $config      Application Configuration
+        * @param string           $formName    Form's name.
+        * @param string           $method      (optional) Form's method defaults to 'POST'
+        * @param string           $action      (optional) Form's action.
+        * @param string           $target      (optional) Form's target defaults to '_self'
+        * @param mixed            $attributes  (optional) Extra attributes for <form> tag.
+        * @param bool             $trackSubmit (optional) Whether to track if the form was
+        *                                                                      submitted by adding a special hidden
+        *                                                                      field.
+        *
+        * @access public
+        * @see    Toolkit_FormBuilder, HTML_QuickForm
+        */
+       public function __construct(
+        PDO $pdo,
+               Config_Container $config,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               $this->_dbh    = $pdo;
+               $this->_config = $config;
+
+               if ($this->primaryAdvisee !== false && empty($this->primaryAdvisee)) {
+                       //      Set to false to turn off email function.
+                       $this->primaryAdvisee = FROM_MEMBER_NEWS_EMAIL;
+               }
+
+               $var = basename(__FILE__, '.php');
+
+               $callbackUrl = ($_SERVER['HTTPS'] == 'on')
+                       ? BASE_SECURE_URL
+                       : BASE_URL;
+
+               $this->captchaOptions = array(
+                       'width' => 100,
+                       'height' => 50,
+                       'callback' => "{$callbackUrl}Toolkit/qfcaptcha.php?var=$var",
+                       'sessionVar' => $var,
+                       'imageOptions' => array(
+                               'font_size' => 16,
+                               'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/',
+                               'font_file' => 'times.ttf',
+                               'background_color' => '#cccccc',
+                               'obfuscation' => false,
+                               'angle' => true,
+                       ),
+               );
+       }
+
+       //      }}}
+
+       //      {{{     checkCvv()
+
+       /**
+     * Check if the credit card CVV is properly formatted
+        *
+        * @param array $values credit card num and cvv number from the form
+        *
+     * @return boolean whether the cvv is properly formatted
+        * @access public
+        */
+       public function checkCvv($values)
+       {
+               return Validate_Finance_CreditCard::cvv($values[0], $values[1]);
+       }
+
+       //      }}}
+       //      {{{     checkDateInput()
+
+       /**
+     * Checks the validation of a m-d-Y date
+        *
+        * This function will only be called if the autoValidateDateElements
+        * property is set to true
+        *
+        * @param array $value Date element from form.
+        *
+        * @return boolean
+        * @access public
+        * @see    Toolkit_FormBuilder::autoValidateDateElements
+        */
+       public function checkDateInput($value)
+       {
+        $res1 = is_numeric($value['m']);
+        $res2 = is_numeric($value['Y']);
+
+        if (!($res1 && $res2)) {
+            return false;
+        }
+
+        $date = implode('-', $value);
+
+        return Validate::date($date, array('format' => '%j-%Y'));
+       }
+
+       //      }}}
+       //      {{{     checkNumber()
+
+       /**
+        * Check if the credit card number is properly formatted
+        *
+        * Credit card numbers have a specific formatting based on the credit card
+        * types.
+        * i.e. (visa, discover, etc...) This call verifies if the # was properly
+        * formatted against the card type selected
+        *
+        * @param array $values credit card type and number from the form
+        *
+        * @return boolean if cc number is properly formatted based on the card type
+        * @access public
+        */
+       public function checkNumber($values)
+       {
+               if (empty($values[1])) {
+                       $values[1] = null;
+               }
+
+               return Validate_Finance_CreditCard::number($values[0], $values[1]);
+       }
+
+       //      }}}
+       //      {{{ configureConstants()
+
+       /**
+        * Sets the constants for the form
+        *
+        * @return void
+        * @access public
+        */
+       public function configureConstants()
+       {
+               $approvalNeeded = $this->_config
+                                                          ->getItem('section', 'add your business')
+                                                          ->getItem('directive', 'approvalNeeded')
+                                                          ->getContent();
+               $hasAuthNetAcc  = $this->_config
+                                                          ->getItem('section', 'authorize net')
+                                                          ->getItem('directive', 'useAuthNet')
+                                                          ->getContent();
+               $newMember = ($approvalNeeded && !$hasAuthNetAcc) ? 1 : 0;
+
+               $c = array(
+                       'new_member' => $newMember,
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+               $e = array();
+        $singularType  = $this->_config
+                                                         ->getItem('section', 'listing type')
+                                                         ->getItem('directive', 'singular')
+                                                         ->getContent();
+        $pluralType    = $this->_config
+                                                         ->getItem('section', 'listing type')
+                                                         ->getItem('directive', 'plural')
+                                                         ->getContent();
+               $useCtrlCities = $this->_config
+                                                         ->getItem('section', 'conf')
+                                                         ->getItem('directive', 'controlledCities')
+                                                         ->getContent();
+               $hasAuthNetAcc = $this->_config
+                                                         ->getItem('section', 'authorize net')
+                                                         ->getItem('directive', 'useAuthNet')
+                                                         ->getContent();
+
+               $ccTypes = array(
+                       '' => '-- Select --',
+                       'amex' => 'American Express',
+                       'discover' => 'Discover Card',
+                       'mastercard' => 'Master Card',
+                       'visa' => 'Visa'
+               );
+
+               $states = Toolkit_Common::getStates($this->_dbh);
+               $this->setCategories();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               //      Member Information
+               $e[] = array(
+                       'type' => 'hidden',
+                       'req'  => false,
+                       'name' => 'new_member'
+               );
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'businessInfoHdr',
+                       'display' => "$singularType Information",
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'member_name',
+                       'display' => "$singularType Name",
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'primary_contact_fname',
+                       'display' => 'Primary Contact First Name'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'primary_contact_lname',
+                       'display' => 'Primary Contact Last Name'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'process_email',
+                       'display' => 'Primary Contact Email'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'process_email_rmv',
+                       'display' => 'Confirm Email'
+               );
+        $e[] = array(
+            'type'    => 'select3',
+            'req'     => true,
+            'name'    => 'category_id',
+            'display' => "$singularType Category",
+            'opts'    => $this->categories,
+        );
+               $e[] = array(
+                       'type' => 'header',
+                       'req' => false,
+                       'name' => 'physicalAddressHdr',
+                       'display' => 'Physical Address',
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => true,
+                       'name' => 'street',
+                       'display' => 'Street Address'
+               );
+        if ($useCtrlCities) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => true,
+                'name'    => 'city_id',
+                'display' => 'City',
+                'opts'    => $this->getCities(),
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => true,
+                'name'    => 'city',
+                'display' => 'City',
+            );
+        }
+               $e[] = array(
+                       'type' => 'select',
+                       'req' => true,
+                       'name' => 'state_id',
+                       'display' => 'State / Provice',
+                       'opts' => array('' => '-- Select --') + $states
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => true,
+                       'name' => 'zip',
+                       'display' => 'Zip / Postal Code',
+               );
+               $e[] = array(
+                       'type' => 'header',
+                       'req' => false,
+                       'name' => 'mailingAddressHdr',
+                       'display' => 'Mailing Address - <em>If different from physical address</em>',
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => false,
+                       'name' => 'mailing_address',
+                       'display' => 'Street Address'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'mailing_city',
+                       'display' => 'City',
+               );
+               $e[] = array(
+                       'type' => 'select',
+                       'req' => false,
+                       'name' => 'mailing_state_id',
+                       'display' => 'State / Provice',
+                       'opts' => array('' => '-- Select --') + $states
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => false,
+                       'name' => 'mailing_zip',
+                       'display' => 'Zip / Postal Code'
+               );
+               $e[] = array(
+                       'type' => 'header',
+                       'req' => false,
+                       'name' => 'contactInfoHdr',
+                       'display' => 'Public Contact Information'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'phone',
+                       'display' => 'Phone'
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => false,
+                       'name' => 'toll_free',
+                       'display' => 'Phone 2'
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => false,
+                       'name' => 'fax',
+                       'display' => 'Fax'
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => false,
+                       'name' => 'member_contact_email',
+                       'display' => 'Email on Website'
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => false,
+                       'name' => 'url',
+                       'display' => 'Website Address'
+               );
+               $e[] = array(
+                       'type' => 'textarea',
+                       'req' => false,
+                       'name' => 'description',
+                       'display' => 'Description of Business - <em id="charcount">1,000 characters max</em>'
+               );
+               $e[] = array(
+                       'type' => 'header',
+                       'req' => false,
+                       'name' => 'accountInfoHdr',
+                       'display' => 'Account Information'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'member_login',
+                       'display' => 'Username'
+               );
+               $e[] = array(
+                       'type'    => 'password',
+                       'req'     => true,
+                       'name'    => 'member_passwd',
+                       'display' => 'Password'
+               );
+               $e[] = array(
+                       'type'    => 'password',
+                       'req'     => true,
+                       'name'    => 'member_passwd_rmv',
+                       'display' => 'Confirm Password'
+               );
+               if ($hasAuthNetAcc) {
+                       $e[] = array(
+                               'type' => 'header',
+                               'req' => false,
+                               'name' => 'creditCardInfoHdr',
+                               'display' => 'CreditCard Information'
+                       );
+                       if (DEVELOPMENT) {
+                               $e[] = array(
+                                       'type' => 'static',
+                                       'req' => false,
+                                       'name' => 'development_notice',
+                                       'opts' => 'Test Mode: Credit Card transactions will not be processed'
+                               );
+                       }
+                       $e[] = array(
+                               'type' => 'select',
+                               'req' => true,
+                               'name' => 'cc_type',
+                               'display' => 'Type',
+                               'opts' => $ccTypes
+                       );
+                       $e[] = array(
+                               'type' => 'text',
+                               'req' => true,
+                               'name' => 'cc_num',
+                               'display' => 'Credit Card Number',
+                       );
+                       $e[] = array(
+                               'type' => 'date',
+                               'req' => true,
+                               'name' => 'cc_exp',
+                               'display' => 'Expiration Date',
+                               'opts' => array(
+                                       'format' => 'm / Y',
+                                       'minYear' => date('Y'),
+                                       'maxYear' => date('Y') + 10,
+                                       'addEmptyOption' => true,
+                                       'emptyOptionText' => array(
+                                               'm' => 'mm',
+                                               'Y' => 'yyyy'
+                                       )
+                               )
+                       );
+                       $e[] = array(
+                               'type' => 'text',
+                               'req' => true,
+                               'name' => 'cc_cvv',
+                               'display' => 'CVV',
+                       );
+               }
+               if ($this->useCaptcha) {
+                       $e[] = array(
+                               'type' => 'header',
+                               'req' => false,
+                               'name' => 'captchaHdr',
+                               'display' => 'Captcha'
+                       );
+                       $e[] = array(
+                               'type'    => 'CAPTCHA_Image',
+                               'req'     => false,
+                               'name'    => 'captcha_question',
+                               'display' => 'Verification code',
+                               'opts'    => $this->captchaOptions
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => true,
+                               'name'    => 'captcha_rmv',
+                               'display' => 'Enter verification code'
+                       );
+               }
+               $e[] = array(
+                       'type'     => 'submit',
+                       'req'      => false,
+                       'name'     => 'submit_rmv',
+                       'display'  => 'Submit'
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+       /**
+        * Setup the filters to apply to the elements before we are
+        * handed the values submitted
+        *
+        * @return void
+        * @access public
+        */
+       public function configureFilters()
+       {
+               $f = array();
+               $f[] = array(
+                       'element' => '__ALL__',
+                       'filter'  => 'trim'
+               );
+        $f[] = array(
+            'element' => 'url',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'phone',
+            'filter' => array('Toolkit_Common', 'filterPhone')
+        );
+        $f[] = array(
+            'element' => 'toll_free',
+            'filter' => array('Toolkit_Common', 'filterPhone')
+        );
+        $f[] = array(
+            'element' => 'fax',
+            'filter' => array('Toolkit_Common', 'filterPhone')
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper method to setup the entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+               $this->configureElements();
+               $this->configureFilters();
+               $this->configureRules();
+               $this->configureConstants();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+               $r = array();
+
+               $useCtrlCities
+                       = $this->_config
+                                  ->getItem('section', 'conf')
+                                  ->getItem('directive', 'controlledCities')
+                                  ->getContent();
+               $allowDuplicateMemberNames
+                       = $this->_config
+                                  ->getItem('section', 'conf')
+                                  ->getItem('directive', 'duplicateMembers')
+                                  ->getContent();
+
+
+               $r[] = array(
+                       'element'    => 'category_id',
+                       'message'    => 'ERROR: Invalid Category!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+        //     If we're using controlled cities, then we only accept numeric
+        //     ids for cities.
+        if ($useCtrlCities) {
+                       $r[] = array(
+                               'element'    => 'city_id',
+                               'message'    => 'ERROR: Invalid City!',
+                               'type'       => 'numeric',
+                               'format'     => null,
+                               'validation' => $this->validationType,
+                               'reset'      => false,
+                               'force'      => false
+                       );
+                       $r[] = array(
+                               'element'    => 'mailing_city_id',
+                               'message'    => 'ERROR: Invalid City!',
+                               'type'       => 'numeric',
+                               'format'     => null,
+                               'validation' => $this->validationType,
+                               'reset'      => false,
+                               'force'      => false
+                       );
+        }
+               $r[] = array(
+                       'element'    => 'member_contact_email',
+                       'message'    => 'ERROR: Invalid email format!',
+                       'type'       => 'checkEmail',
+                       'format'     => array('use_rfc822' => true),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'process_email',
+                       'message'    => 'ERROR: Invalid email format!',
+                       'type'       => 'checkEmail',
+                       'format'     => array('use_rfc822' => true),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => array(
+                               'process_email',
+                               'process_email_rmv'
+                       ),
+                       'message'    => 'ERROR: Your email addresses do not match!',
+                       'type'       => 'compare',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'   => array(
+                               'member_passwd',
+                               'member_passwd_rmv'
+                       ),
+                       'message'    => 'ERROR: Your passwords do not match!',
+                       'type'       => 'compare',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'url',
+                       'message'    => 'ERROR: Invalid URL format (http, https only)',
+                       'type'       => 'checkURI',
+                       'format'     => array(
+                               'allowed_schemes' => array('http', 'https'),
+                               'strict' => true
+                       ),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'state_id',
+                       'message'    => 'ERROR: Invalid State!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'mailing_state_id',
+                       'message'    => 'ERROR: Invalid State!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'zip',
+                       'message'    => 'ERROR: Invalid Zip Code!',
+                       'type'       => 'zip',
+                       'format'     => array('requireDBCheck' => false),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'mailing_zip',
+                       'message'    => 'ERROR: Invalid Zip Code!',
+                       'type'       => 'zip',
+                       'format'     => array('requireDBCheck' => false),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'phone',
+                       'message'    => 'ERROR: Invalid Phone Number! (xxx) xxx-xxxx',
+                       'type'       => 'phone',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'fax',
+                       'message'    => 'ERROR: Invalid Phone Number! (xxx) xxx-xxxx',
+                       'type'       => 'phone',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'toll_free',
+                       'message'    => 'ERROR: Invalid Phone Number! (xxx) xxx-xxxx',
+                       'type'       => 'phone',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+        if ($allowDuplicateMemberNames) {
+                       $r[] = array(
+                               'element' => 'member_name',
+                               'message' => 'ERROR: This name already exists!',
+                               'type' => 'DuplicateMember',
+                               'format' => $this->_dbh,
+                               'validation' => $this->validationType,
+                               'reset' => false,
+                               'force' => false
+                       );
+        }
+               $r[] = array(
+                       'element'    => 'member_login',
+                       'message'    => 'ERROR: This username is taken already!',
+                       'type'       => 'MemberLogin',
+                       'format'     => $this->_dbh,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $hasAuthNetAcc = $this->_config
+                                                         ->getItem('section', 'authorize net')
+                                                         ->getItem('directive', 'useAuthNet')
+                                                         ->getContent();
+               if ($hasAuthNetAcc) {
+                   $r[] = array(
+                'element'    => array('cc_num', 'cc_type'),
+                'message'    => 'ERROR: Number does not match card type!',
+                'type'       => 'callback',
+                'format'     => array(&$this, 'checkNumber'),
+                'validation' => $this->validationType,
+                'reset'      => false,
+                'force'      => false
+            );
+                   $r[] = array(
+                'element'    => array('cc_cvv', 'cc_type'),
+                'message'    => 'ERROR: CVV does not match card type!',
+                'type'       => 'callback',
+                'format'     => array(&$this, 'checkCvv'),
+                'validation' => $this->validationType,
+                'reset'      => false,
+                'force'      => false
+            );
+               }
+               if ($this->useCaptcha) {
+            $r[] = array(
+                'element'    => 'captcha_rmv',
+                'message'    => 'ERROR: What you entered didn\'t match!',
+                'type'       => 'CAPTCHA',
+                'format'     => $this->captchaQuestion,
+                'validation' => $this->validationType,
+                'reset'      => false,
+                'force'      => false
+            );
+               }
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{ createCategories()
+
+       /**
+        * Creates an array from the array of category tree objects
+        *
+     * @param array   $tree  linear category tree array
+     * @param integer $depth what level we are on
+     *
+        * @return array The array list of categories that
+        *                               that can be loaded into a select element
+        * @access protected
+        */
+       protected function createCategories($tree, $depth = 0)
+       {
+               $this->records[] = $tree->category;
+               if ($depth == 0) {
+                       $this->categories[$tree->catid] = "<span>{$tree->category}</span>";
+               } else {
+                       $this->categories[$tree->catid] = $tree->category;
+               }
+               if (empty($tree->children)) {
+                       return;
+               } else {
+                       ++$depth;
+                       foreach ($tree->children as $miniTrees) {
+                               $this->createCategories($miniTrees, $depth);
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{ getCategories()
+
+       /**
+        * Creates array structure of the category tree for use in a select element.
+        *
+        * This method will also instantiate a class property called tree for your
+        * class. This object will hold the tree structure of the categories list
+        * from the Database.
+        *
+        * @return array The array list of categories that can be loaded
+        *                               into a select element
+        *
+        * @access protected
+        */
+       protected function getCategories()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM category
+                                WHERE parent_id = 0
+                                ORDER BY name";
+                       foreach ($this->_dbh->query($sql) as $row) {
+                               $this->tree[] = new Toolkit_Members_CategoryTree(
+                                       $row['category_id'],
+                                       $row['name'],
+                                       $this->_dbh
+                               );
+                       }
+                       if (!empty($this->tree)) {
+                               foreach ($this->tree as $t) {
+                                       $this->createCategories($t);
+                               }
+                       }
+
+                       if (empty($this->categories)) {
+                               $this->categories = array('' => '-- No Categories Created Yet --');
+                       } else {
+                               $this->categories
+                                       = array('' => '-- Select Category --') + $this->categories;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ getCities()
+
+       /**
+        * Configure the cities for member stored in the database into an array
+        *
+     * @return array the cities
+        * @access protected
+        */
+       protected function getCities()
+       {
+               $cities = array();
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM city
+                                ORDER BY city_name";
+                       foreach ($this->_dbh->query($sql) as $row) {
+                               $cities[$row['city_id']] = $row['city_name'];
+                       }
+                       if (!empty($cities)) {
+                               $cities = array('' => '-- Select --') + $cities;
+                       } else {
+                               $cities = array('' => '-- No Cities Created Yet -- ');
+                       }
+                       return $cities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberCategories()
+
+       /**
+        * Get the array of member categories used for the select list
+        *
+        * @return array $pages pages used to populate a select list element
+        * @access protected
+        */
+       protected function getMemberCategories()
+       {
+               $categories = Toolkit_Common::getHierarchicalTreeStructure(
+            $this->_dbh,
+            'category',
+            'category_id',
+            'parent_id'
+        );
+               //  Get only the active categories from
+               //  the nav structure for our select list.
+               $sql = "
+                       SELECT category_id, name
+                         FROM category
+                        WHERE category_id = :id";
+
+               $stmt = $this->_dbh->prepare($sql);
+
+               foreach ($categories as $k => $v) {
+                       unset($row, $category);
+                       $stmt->bindParam(':id', $k, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       //  If we actually retrieved a row, add it to the select list
+                       //  after we clean it up.
+                       if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $pages[$k] = array(
+                                       'level' => $v - 1,
+                                       'name' => $row['name']
+                               );
+                       }
+               }
+
+               return $pages;
+       }
+
+       //      }}}
+       //      {{{     insertData()
+
+    /**
+     * Inserts contact data into the contact db
+     *
+     * @param array $values submitted values
+        *
+     * @return object    result of db insert query
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $hasAuthNetAcc = $this->_config
+            ->getItem('section', 'authorize net')
+            ->getItem('directive', 'useAuthNet')
+            ->getContent();
+               try {
+                       $this->setFormData();
+                       $values['description']
+                               = nl2br(str_replace("\r", "\n", $values['description']));
+
+                       $this->setLatLngCoords($values);
+
+                       $this->_dbh->beginTransaction();
+                       $memberCategory = $values['category_id'];
+                       $authValues     = $values;
+                       unset(
+                               $values['category_id'],
+                               $values['cc_type'],
+                               $values['cc_num'],
+                               $values['cc_exp'],
+                               $values['cc_cvv']
+                       );
+            if ($hasAuthNetAcc) {
+                $values['active'] = true;
+            }
+                       $sql = Toolkit_Common::createSQLInsert('member', array_keys($values));
+                       $stmt = Toolkit_Common::prepareQuery(
+                               $this->_dbh,
+                               'member',
+                               $sql,
+                               $values
+                       );
+                       $stmt->execute();
+
+                       $sql = "
+                SELECT member_id
+                  FROM member
+                 ORDER BY member_id DESC LIMIT 1";
+
+                       $row = $this->_dbh->query($sql)->fetch();
+
+                       $sql = "
+                INSERT INTO member_category (member_id, category_id)
+                VALUES (:mid, :cid)";
+                       $stmt = $this->_dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $row['member_id']);
+                       $stmt->bindParam(':cid', $memberCategory, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       //      If they are paying via auth.net and their account
+                       //      doesn't go through, then don't actually insert the member.
+
+                       if ($hasAuthNetAcc) {
+                               $res = $this->processAuthNet($authValues);
+                               if (is_array($res) && !empty($res)) {
+                                       if ($res[0] == 1) {
+                                               //      CC was Accepted.
+                                               $this->_dbh->commit();
+                                               return true;
+                                       } elseif ($res[0] == 2) {
+                                               //      CC was Declined.
+                                               $this->_dbh->rollback();
+                                               return 2;
+                                       } else {
+                                               //      There was a CC processing error.
+                                               $this->_dbh->rollback();
+                                               return $res[0];
+                                       }
+                               } else {
+                                       //      There was a CC processing error.
+                                       $this->_dbh->rollback();
+                                       return false;
+                               }
+                       } else {
+                               //      Not paying by CC so just commit the insert.
+                               return $this->_dbh->commit();
+                       }
+               } catch (PDOException $e) {
+                       $this->_dbh->rollback();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     processAuthNet()
+
+       /**
+        * Send payment to auth.net
+        *
+        * Test Cards
+        * Card Number      Card Type
+        * ===============  ===============
+        * 370000000000002  American Express
+        * 6011000000000012 Discover Card
+        * 5424000000000015 MasterCard
+        * 4000000000000000 Visa
+        *
+        * @param array $values Submitted values from the form
+        *
+        * @return array Auth.net response
+        * @access protected
+        */
+       protected function processAuthNet($values)
+       {
+               $authNetLoginId = $this->_config
+                                                          ->getItem('section', 'add your business')
+                                                          ->getItem('directive', 'authNetLoginId')
+                                                          ->getContent();
+               $authNetTranKey = $this->_config
+                                                          ->getItem('section', 'add your business')
+                                                          ->getItem('directive', 'authNetTranKey')
+                                                          ->getContent();
+               $authNetUrl     = "https://secure.authorize.net/gateway/transact.dll";
+
+               $authNetValues = array(
+                       'x_login'          => $authNetLoginId,
+                       'x_version'        => '3.1',
+                       'x_delim_char'     => '|',
+                       'x_delim_data'     => 'TRUE',
+                       'x_type'           => 'AUTH_CAPTURE',
+                       'x_method'         => 'CC',
+                       "x_test_request"   => DEVELOPMENT ? "TRUE" : "FALSE",
+                       'x_tran_key'       => $authNetTranKey,
+                       'x_relay_response' => 'FALSE',
+                       'x_card_num'       => $values['cc_num'],
+                       'x_exp_date'       => implode('', $values['cc_exp']),
+                       'x_amount'         => $values[$values['member_type']],
+            'x_first_name'     => $values['cc_fname'],
+            'x_last_name'      => $values['cc_lname'],
+               );
+
+               $fields = '';
+               foreach ($authNetValues as $i => $j) {
+                       $fields .= "$i=" . urlencode($j) . '&';
+               }
+
+               $ch = curl_init($authNetUrl);
+               //      set to 0 to elimindate header info from response
+               curl_setopt($ch, CURLOPT_HEADER, 0);
+               //      Returns response data instead of TRUE(1)
+               curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+               //      Use HTTP POST to send form data
+                       curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($fields, "& "));
+               //      Uncomment this line if you get no gateway response. ###
+               //      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
+               //      Execute post and get results
+               $resp = curl_exec($ch);
+               curl_close($ch);
+
+               $res = explode('|', $resp);
+               return $res;
+       }
+
+       //      }}}
+       //      {{{     processData()
+
+    /**
+     * Handles how to process the form when submitted
+     *
+     * @param array $values Form submitted values
+        *
+     * @return array     Result of Insert / Update function
+     * @access protected
+     */
+       public function processData($values)
+       {
+               //      Form data used for the insert/update sql queries and
+               //      the form email.
+               $e = array();
+               $this->setFormData($e);
+
+               //      Get rid of any defined un-needed elements.
+               //      un-needed elements after the form is submitted are defined
+               //      by the ending _rmv name.
+               foreach ($values as $k => &$v) {
+                       if (preg_match('/^.+_rmv$/', $k)) {
+                               unset($values[$k]);
+                       }
+               }
+
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->_dbh,
+                       'member'
+        );
+
+               return $this->insertData($values);
+       }
+
+       //      }}}
+
+       //      {{{     sendAdminEmail()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param boolean $test Parameter description (if any) ...
+     *
+     * @return boolean Return description (if any) ...
+     * @access public
+     */
+       public function sendAdminEmail($test = false)
+       {
+               if ($this->primaryAdvisee === false) {
+                       return true;
+               } else {
+                       $template = new HTML_Template_Flexy(Toolkit_Members::getFlexyOptions());
+                       $page     = new stdClass();
+
+                       $page->base_url    = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL :
+                                                                                                                          BASE_URL;
+                       $page->approval_needed = $this->approvalNeeded;
+                       $page->member_name     = $this->formData['member_name']['element'];
+                       $page->client_name     = SITENAME;
+                       $page->email_from      = OWNER_EMAIL;
+
+                       $template->compile('addYourBusinessAdminEmail.tpl');
+                       //      Merge the compiled template with the $page object.
+                       $htmlMsg = $template->bufferedOutputObject($page);
+
+                       $msg = '';
+
+                       $crlf     = "\n";
+                       $mimeMail = new Mail_mime($crlf);
+                       $mimeMail->setFrom(SITENAME . " <{$page->email_from}>");
+                       $mimeMail->setSubject('Add Your Business Request From ' . SITENAME);
+                       if (!empty($this->secondaryAdvisees)) {
+                               //      Spam will choke if we CC: more than 5 addresses.
+                               //      so if the user puts more than 5 in, we'll only
+                               //      accept the first 5.  This is stated in the property
+                               //      description for secondaryAdvisees
+                               if (count($this->secondaryAdvisees) > 5) {
+                                       $this->secondaryAdvisees = array_slice($this->secondaryAdvisees, 0, 5);
+                               }
+                               foreach ($this->secondaryAdvisees as $k => $v) {
+                                       if (is_string($k) && !is_numeric($k)) {
+                                               $email = "$k <$v>";
+                                       } else {
+                                               $email = $v;
+                                       }
+                                       $mimeMail->addCC($email);
+                               }
+                       }
+                       $mimeMail->setHTMLBody($htmlMsg);
+                       $mimeMail->setTXTBody($msg);
+
+                       //      If we're testing the interface then don't actually send out the mail
+                       $interface = $test ? 'mock' : 'mail';
+                       $mail      = Mail::factory($interface);
+                       $body      = $mimeMail->get();
+                       $headers   = $mimeMail->headers($hdrs);
+
+                       $res = $mail->send($this->primaryAdvisee, $headers, $body);
+
+                       return PEAR::isError($res) ? Toolkit_Common::handleError($res) : $res;
+               }
+       }
+
+       //      }}}
+       //      {{{     sendMemberEmail()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param boolean $test Parameter description (if any) ...
+     *
+     * @return unknown Return description (if any) ...
+     * @access public
+     */
+       public function sendMemberEmail($test = false)
+       {
+               $template = new HTML_Template_Flexy(Toolkit_Members::getFlexyOptions());
+               $page     = new stdClass();
+
+               $page->base_url        = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL :
+                                                                                                                          BASE_URL;
+               $page->member_category = MEMBERS_CATEGORY;
+               $page->approval_needed = $this->approvalNeeded;
+               $page->first_name      = $this->formData['primary_contact_fname']['element'];
+               $page->member_name     = $this->formData['member_name']['element'];
+               $page->username        = $this->formData['member_login']['element'];
+               $page->password        = $this->formData['member_passwd']['element'];
+               $page->client_name     = SITENAME;
+
+               $template->compile('addYourBusinessMemberEmail.tpl');
+               //      Merge the compiled template with the $page object.
+               $htmlMsg = $template->bufferedOutputObject($page);
+
+               $msg = '';
+
+               $crlf     = "\n";
+               $mimeMail = new Mail_mime($crlf);
+               $mimeMail->setFrom(SITENAME . ' <'.OWNER_EMAIL.'>');
+               $mimeMail->setSubject('Add Your Business Request From ' . SITENAME);
+               $mimeMail->setHTMLBody($htmlMsg);
+               $mimeMail->setTXTBody($msg);
+
+               //      If we're testing the interface then don't actually send out the mail
+               $interface = $test ? 'mock' : 'mail';
+               $mail      = Mail::factory($interface);
+               $body      = $mimeMail->get();
+               $headers   = $mimeMail->headers($hdrs);
+
+               $res = $mail->send($this->formData['process_email']['element'], $headers, $body);
+
+               return PEAR::isError($res) ? Toolkit_Common::handleError($res) : $res;
+       }
+
+       //      }}}
+       //      {{{ setCategories()
+
+       /**
+        * Creates array structure of the category tree for use in a select element.
+        *
+        * This method will also instantiate a class property called tree for your
+        * class. This object will hold the tree structure of the categories list
+        * from the Database.
+        *
+        * @return array The array list of categories that can be loaded
+        *                               into a select element
+        *
+        * @access protected
+        */
+       protected function setCategories()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM category
+                                WHERE parent_id = 0
+                                ORDER BY name";
+                       foreach ($this->_dbh->query($sql) as $row) {
+                               $this->tree[] = new Toolkit_Members_CategoryTree(
+                                       $row['category_id'],
+                                       $row['name'],
+                                       $this->_dbh
+                               );
+                       }
+                       if (!empty($this->tree)) {
+                               foreach ($this->tree as $t) {
+                                       $this->createCategories($t);
+                               }
+                       }
+
+                       if (empty($this->categories)) {
+                               $this->categories = array('' => '-- No Categories Created Yet --');
+                       } else {
+                               $this->categories
+                                       = array('' => '-- Select --') + $this->categories;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setLatLngCoords()
+
+    /**
+     * Description for setLatLngCoords
+     * 
+     * @param array &values
+     * @return mixed From Toolkit_Common
+     * @access protected 
+     */
+       protected function setLatLngCoords(&$values)
+       {
+               $geocoder = new GeocodeYahoo();
+
+               $sql = "
+                       SELECT c.city_name, s.state_abb
+                         FROM city c, state s
+                        WHERE c.city_id  = :cityId
+                          AND s.state_id = :stateId";
+
+               try {
+                       $stmt = $this->_dbh->prepare($sql);
+                       $stmt->bindParam(':cityId', $values['city_id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':stateId', $values['state_id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('city_name', $cityName);
+                       $stmt->bindColumn('state_abb', $stateName);
+                       $stmt->fetch(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+               $address = array(
+                       'city' => $cityName,
+                       'state' => $stateName,
+                       'zip' => $values['zip'],
+               );
+               if (!empty($values['street'])) {
+                       $address['street'] = $values['street'];
+               }
+
+               $response = $geocoder->geocodeAddress($address);
+               $responseArray = unserialize($response);
+               $values['lat'] = $responseArray['ResultSet']['Result']['Latitude'];
+               $values['lon'] = $responseArray['ResultSet']['Result']['Longitude'];
+       }
+
+       //      }}}
+       //      {{{     setupRenderers()
+
+    /**
+        * Setup how the form should render
+        *
+        * We also need to attach a couple specific rendering templates to
+        * a few special elements.
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer = $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="req">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate(
+                       '<tr align="center"><td colspan="2">{element}</td></tr>',
+                       'submit_rmv'
+               );
+               $renderer->setElementTemplate(
+                       '<tr>
+                               <td colspan="2">'.$required.'{label}'.$error.'{element}</td>
+                       </tr>',
+                       'description'
+               );
+               if (DEVELOPMENT) {
+               $renderer->setElementTemplate(
+                       '<tr>
+                               <td colspan="2"><em id="cc-dev-mode-notice">{element}</em></td>
+                       </tr>',
+                       'development_notice'
+               );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+        * destroying and resetting the captcha value dis-allows someone from
+        * re-sending a form on a previous captcha.
+        *
+        * @return string The Form to be rendered or success msg.
+        * @access public
+        */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       if ($this->useCaptcha) {
+                               $this->captchaQuestion->destroy();
+                       }
+
+                       $res = $this->process(
+                               array(&$this, 'processData'),
+                               $this->mergeFiles
+                       );
+
+//return '<h1>validated</h1>' . parent::toHtml();
+                       if ($res === true) {
+                $this->cleanForm();
+                               $this->sendAdminEmail();
+                               $this->sendMemberEmail();
+                               $this->freeze();
+                               $output = $this->successMsg;
+                               $hasAuthNetAcc = $this->_config
+                    ->getItem('section', 'authorize net')
+                    ->getItem('directive', 'useAuthNet')
+                    ->getContent();
+                               if ($hasAuthNetAcc) {
+                                       $rem = array(
+                                               'cc_cvv',
+                                               'cc_type',
+                                               'cc_fname',
+                                               'cc_lname',
+                                               'member_login',
+                                               'member_passwd',
+                                               'captcha_question',
+                                       );
+                                       foreach ($rem as $i) {
+                                               if ($this->elementExists($i)) {
+                                                       $this->removeElement($i);
+                                               }
+                                       }
+
+                                       if ($this->elementExists('cc_num')) {
+                                               //      Obscure th CC Num so its not displayed.
+                                               $e = $this->getElement('cc_num');
+                                               $ccNum = $e->getValue();
+                                               $newCCNum = preg_replace(
+                            '/\d/',
+                            '*',
+                            $ccNum,
+                            strlen($ccNum) - 4
+                        );
+                                               $e->setValue($newCCNum);
+                                       }
+                               }
+                $output = $this->successMsg;
+                       } elseif ($res == 2) {
+                               $this->_errors['cc_num'] = 'ERROR: Your credit card has been declined!';
+                               if ($this->useCaptcha) {
+                                       $this->captchaQuestion->destroy();
+                                       $this->captchaAnswer->setValue('');
+                               }
+                               $output  = $this->errorMsg;
+                               $output .= parent::toHtml();
+                       } else {
+                               $this->_errors['cc_num'] = 'ERROR: There was an error processing your credit card!';
+                               if ($this->useCaptcha) {
+                                       $this->captchaQuestion->destroy();
+                                       $this->captchaAnswer->setValue('');
+                               }
+                               $output  = $this->errorMsg;
+                               $output .= parent::toHtml();
+                       }
+               } elseif ($this->isSubmitted()) {
+                       if ($this->useCaptcha) {
+                               $this->captchaQuestion->destroy();
+                               $this->captchaAnswer->setValue('');
+                       }
+                       $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/textlimit.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/new-member-sign-up.js';
+                       $output = $this->errorMsg;
+                       $output .= parent::toHtml();
+               } else {
+                       if ($this->useCaptcha) {
+                               $this->captchaQuestion->destroy();
+                               $this->captchaAnswer->setValue('');
+                       }
+                       $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/textlimit.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/new-member-sign-up.js';
+                       $output = parent::toHtml();
+               }
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/AddPhoto.php b/Toolkit/Members/Admin/AddPhoto.php
new file mode 100644 (file)
index 0000000..7d8be8a
--- /dev/null
@@ -0,0 +1,359 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles the photos tab in the member record
+ *
+ * Controls setting up the add photo form if applicable, and rendering
+ * each uploaded photo edit form to edit/delete the photo.
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AddPhoto.php,v 1.5 2010/07/16 20:53:08 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit/Image/Server.php
+ */
+
+
+/**
+ * The image server processing class
+ */
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Form to handle creating a new photo in the members only area
+ *
+ * Handles inserting new photo into db as a pending photo and creating a
+ * tuple in the member_updates table which will allow the admin to
+ * approve/deny the new photo request.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_AddPhoto extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_photos';
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'addPhoto.tpl';
+
+       /**
+        * Some special forms dont utlize this stylesheet
+        * Allow classes to override this setting so it doesn't
+        * get included
+        *
+        * @var boolean
+        * @access protected
+        */
+       protected $includeContactStyleSheet = false;
+
+    /**
+     * Success message when a photo gets successfully uploaded
+     * @var string
+     * @access protected
+     */
+    protected $successMsg = '
+        <div id="form-success-top">
+            You successfully uploaded your photo.
+        </div>';
+
+    /**
+     * Description for protected
+     * @var array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+        * @param PDO    $pdo         PHP Data Object to use for DB calls
+        * @param string $formName    Form's name.
+        * @param string $method      (optional) Form's method defaults to 'POST'
+        * @param string $action      (optional) Form's action.
+        * @param string $target      (optional) Form's target defaults to '_self'
+        * @param mixed  $attributes  (optional) Extra attributes for <form> tag.
+        * @param bool   $trackSubmit (optional) Whether to track if the form was
+        *                                                                               submitted by adding a special hidden
+        *                                                                               field.
+        *
+        * @access public
+        * @see    Toolkit_Members_Admin_EditPhotos
+        */
+       public function __construct(
+        $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+     * @param Config_Container $c application configuration
+     *
+        * @return void
+        * @access public
+        */
+       public function configureElements(Config_Container $c)
+       {
+               $e = array();
+
+        $config = $c->getItem('section', 'photos');
+        $maxLength = $config->getItem('directive', 'maxCaptionLength');
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+                       'type' => 'file',
+                       'req'  => true,
+                       'name' => 'file',
+            'display' => 'Upload a Photo',
+                       'opts' => array('class' => 'submit')
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req'  => false,
+                       'name' => 'caption',
+            'display' => 'Caption',
+                       'opts' => array(
+                               'class' => 'text',
+                               'maxlength' => $maxLength->getContent(),
+                       ),
+            'noCharLimit' => true
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'submit',
+                       'display' => 'Upload new photo',
+                       'opts'    => array('class' => 'submit')
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+        * helper function to set up entire form definition
+        *
+     * @param Config_Container $c application configuration
+        *
+        * @return void
+        * @access public
+     */
+    public function configureForm(Config_Container $c)
+    {
+        $this->configureElements($c);
+               $this->configureRules($c);
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Configure rules for form
+        *
+     * @param Config_Container $c application configuration
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules(Config_Container $c)
+       {
+        $config = $c->getItem('section', 'photos');
+        $maxLength = $config->getItem('directive', 'maxCaptionLength');
+
+               $mimeTypes = array(
+                       'image/jpe',
+                       'image/jpeg',
+                       'image/jpg',
+                       'image/jfif',
+                       'image/pjpeg',
+                       'image/pjp',
+                       'image/gif',
+                       'image/png',
+               );
+
+               $r = array();
+
+               $r[] = array(
+                       'element'    => 'file',
+                       'message'    => 'ERROR: You must select a file!',
+                       'type'       => 'uploadedfile',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'caption',
+
+                       'message'    => "ERROR: {$maxLength->getContent()} characters max!",
+                       'type'       => 'maxlength',
+                       'format'     => $maxLength->getContent(),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'file',
+                       'message'    => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                       'type'       => 'mimetype',
+                       'format'     => $mimeTypes,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+       /**
+        * Handles setting up the from processing and which function to get it done
+        *
+        * @param array $values Submitted values from the form.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function processData($values)
+       {
+               try {
+            $sql = Toolkit_Common::createSQLInsert(
+                $this->tableName,
+                array_keys($values)
+            );
+
+            $res = Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+        header('Location:' . $this->getAttribute('action'));
+       }
+
+       //      }}}
+
+       //      {{{ setupRenderers()
+
+    /**
+     * Set up the rendering engine we are going to use to display this form
+     *
+     * @param HTML_Template_Flexy &$tEngine Templating Engine
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers(HTML_Template_Flexy &$tEngine)
+       {
+               $renderer = new HTML_QuickForm_Renderer_ObjectFlexy($tEngine);
+
+               $this->accept($renderer);
+               $this->view       = new stdClass();
+               $this->view->form = $renderer->toObject();
+               $tEngine->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+     *
+     * @param HTML_Template_Flexy    $tEngine Templating Engine
+     * @param Cache_Lite             $cache   Caching Engine
+     * @param Config_Container       $c       Application configuration
+     * @param Toolkit_Image_Server   $is      Image Server
+     * @param Toolkit_Members_Photos $ll      Linked List of member photos
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(
+        HTML_Template_Flexy $tEngine,
+        Cache_Lite $cache,
+        Config_Container $c,
+        Toolkit_Image_Server $is,
+        Toolkit_Members_Photos $ll
+    ) {
+               if ($this->validate()) {
+            $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+            //  Put the processed photo's new name into the submitted values
+            $this->_submitValues['image'] = $is->imageUpload('file');
+            $this->_submitValues['pos'] = $ll->getListSize() + 1;
+            $this->_submitValues['member_id'] = $_GET['id'];
+            $this->_submitValues['pending'] = 0;
+
+            unset($this->_submitValues['MAX_FILE_SIZE'],
+                  $this->_submitValues['submit']);
+
+                       $this->process(array(&$this, 'processData'), false);
+               }
+
+               $this->setupRenderers($tEngine);
+
+               return $tEngine->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/AdvancedSearch.php b/Toolkit/Members/Admin/AdvancedSearch.php
new file mode 100644 (file)
index 0000000..903bc53
--- /dev/null
@@ -0,0 +1,990 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Admin search functionality for memberdb
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AdvancedSearch.php,v 1.14 2010/08/15 19:35:15 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form to search the members database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_AdvancedSearch
+    extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Description of $_members
+     *
+     * @var unknown
+     * @access private
+     */
+       private $_members;
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for the form
+        *
+        * @param PDO $dbh Database handler
+        *
+        * @access public
+     * @return void
+        */
+       public function configureDefaults(PDO $dbh)
+       {
+               //      earliest create date is the same thing as
+               //      earliest modified date.
+
+               //$earliestDate = $this->_getEarliestCreateDate($dbh);
+               //if they want to default dates to the earliest date
+               //available in the DB, then uncomment this variable
+               //and the default values below.
+
+               $d = array(
+                       'rt' => $_GET['rt'],
+                       'rt' => $_GET['rt'],
+                       'active' => '-1',
+                       /*
+                       'create_date_beg' => $earliestDate,
+                       'create_date_end' => array(
+                               'm' => date('m'),
+                               'd' => date('d'),
+                               'Y' => date('Y')
+                       ),
+                       'last_modified_date_beg' => $earliestDate,
+                       'last_modified_date_end' => array(
+                               'm' => date('m'),
+                               'd' => date('d'),
+                               'Y' => date('Y')
+                       )
+                       */
+               );
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+        * @param PDO                      $dbh Databse handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements(PDO $dbh, Config_Container $c)
+       {
+        $e = array();
+
+               $singularType = $c->getItem('section', 'listing type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+               $pluralType = $c->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+               $useCtrlCities = $c->getItem('section', 'conf')
+                       ->getItem('directive', 'controlledCities')
+                       ->getContent();
+               $dateStartYear = $c->getItem('section', 'conf')
+                       ->getItem('directive', 'dateStartYear')
+                       ->getContent();
+
+               //      All Grouped Elements are created here.
+               $isActive = array();
+               $isActive[] = array(
+                       'type'    => 'radio',
+                       'req'     => false,
+                       'name'    => 'active',
+                       'opts' => 'Yes',
+                       'att' => '1'
+               );
+               $isActive[] = array(
+                       'type'    => 'radio',
+                       'req'     => false,
+                       'name'    => 'active',
+                       'opts' => 'No',
+                       'att' => '0'
+               );
+               $isActive[] = array(
+                       'type'    => 'radio',
+                       'req'     => false,
+                       'name'    => 'active',
+                       'opts' => "Don't Care",
+                       'att' => '-1'
+               );
+               $createDate = array();
+               $createDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'create_date_beg',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+               $createDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'create_date_end',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+               $lastModifiedDate = array();
+               $lastModifiedDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'last_modified_date_beg',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+               $lastModifiedDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'last_modified_date_end',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+               $memberSinceDate = array();
+               $memberSinceDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'join_date_beg',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+               $memberSinceDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'join_date_end',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'rt'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'ac'
+        );
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'attributesInfoHdr',
+            'display' => "Record Attributes",
+        );
+               $e[] = array(
+            'type' => 'group',
+            'req' => false,
+            'name' => 'active',
+                       'group' => $isActive,
+                       'seperator' => '<br>',
+            'label' => 'Is Active',
+                       'appendName' => false
+        );
+               $e[] = array(
+                       'type'    => 'group',
+                       'req'     => false,
+                       'name'    => 'create_date',
+                       'group' => $createDate,
+                       'seperator' => '<br>',
+                       'label' => "Created Between",
+                       'appendName' => false
+               );
+//             $e[] = array(
+//                     'type'    => 'group',
+//                     'req'     => false,
+//                     'name'    => 'member_since',
+//                     'group' => $memberSinceDate,
+//                     'seperator' => '<br>',
+//                     'label' => "Member Since Between",
+//                     'appendName' => false
+//             );
+//             $e[] = array(
+//                     'type'    => 'group',
+//                     'req'     => false,
+//                     'name'    => 'last_modified',
+//                     'group' => $lastModifiedDate,
+//                     'seperator' => '<br>',
+//                     'label' => "Last Modified Between",
+//                     'appendName' => false
+//             );
+               $e[] = array(
+            'type' => 'selectglm',
+            'req' => false,
+            'name' => 'category',
+            'display' => 'Has Category',
+            'opts' => $this->_getCategories($dbh),
+                       'att' => array(
+                               'multiple' => 'multiple',
+                               'size' => 6
+                       )
+        );
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'recordInfoHdr',
+            'display' => "Record Information",
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'member_name',
+            'display' => "$singularType Name"
+        );
+//             $e[] = array(
+//            'type' => 'text',
+//            'req' => false,
+//            'name' => 'member_contact_email',
+//            'display' => "$singularType Email"
+//        );
+        if ($useCtrlCities) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'city_id',
+                'display' => 'City',
+                'opts'    => array('' => '-- Select --')
+                                                       + Toolkit_Common::getCities($this->dbh),
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => false,
+                'name'    => 'city',
+                'display' => 'City',
+                'opts'    => array('class' => 'text')
+            );
+        }
+               $e[] = array(
+                       'type'    => 'select',
+                       'req'     => false,
+                       'name'    => 'state_id',
+                       'display' => 'State / Province',
+                       'opts'    => array('' => '-- Select --')
+                                               + Toolkit_Common::getStates($this->dbh)
+               );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'county',
+            'display' => 'County',
+            'opts'    => array('' => '-- Select --')
+                        + $this->getCounties($this->dbh),
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'region',
+            'display' => 'Region',
+            'opts'    => array('' => '-- Select --')
+                        + $this->getRegions($this->dbh),
+        );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'zip',
+                       'display' => 'Zip / Postal Code',
+                       'opts'    => array('class' => 'text')
+               );
+//             $e[] = array(
+//            'type' => 'header',
+//            'req' => false,
+//            'name' => 'PrimaryContactInfoHdr',
+//            'display' => "Record Contact Information"
+//        );
+//             $e[] = array(
+//            'type' => 'text',
+//            'req' => false,
+//            'name' => 'contact_fname',
+//            'display' => 'First Name'
+//        );
+//             $e[] = array(
+//            'type' => 'text',
+//            'req' => false,
+//            'name' => 'contact_lname',
+//            'display' => 'Last Name'
+//        );
+//             $e[] = array(
+//            'type' => 'text',
+//            'req' => false,
+//            'name' => 'process_email',
+//            'display' => 'Email'
+//        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Search'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+        * @param PDO                      $dbh Databse handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(PDO $dbh, Config_Container $c)
+    {
+        $this->configureElements($dbh, $c);
+        $this->configureDefaults($dbh);
+        $this->configureRules();
+        $this->configureFilters();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+               $r[] = array(
+            'element' => 'member_contact_email',
+            'message' => 'ERROR: Invalid Email Address!',
+            'type' => 'email',
+        );
+        /*
+               $r[] = array(
+            'element' => 'category',
+            'message' => 'ERROR: Invalid Category!',
+            'type' => 'numeric',
+        );
+        */
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     getSearchResults()
+
+       /**
+        * Get the results of the search
+        *
+        * @return mixed false if not searched else array of matching members
+        * @access public
+        */
+       public function getSearchResults()
+       {
+               if (!$this->isSubmitted()) {
+                       return false;
+               } else {
+                       return $this->_members;
+               }
+       }
+
+       //      }}}
+       //      {{{     _getCategories()
+
+    /**
+     * get all the categories available in alpha order
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array alpha order of categories available in the DB
+     * @access private
+     */
+       private function _getCategories(PDO $dbh)
+       {
+               $categories = Toolkit_Common::getHierarchicalTreeStructure(
+                       $dbh,
+            'category',
+            'category_id',
+            'parent_id',
+                       'name'
+        );
+               //  Get only the active categories from
+               //  the nav structure for our select list.
+               $sql = "
+                       SELECT category_id, name
+                         FROM category
+                        WHERE category_id = :id";
+
+               $stmt = $dbh->prepare($sql);
+
+               foreach ($categories as $k => $v) {
+                       unset($row, $category);
+                       $stmt->bindParam(':id', $k, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       //  If we actually retrieved a row, add it to the select list
+                       //  after we clean it up.
+                       if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $pages[$k] = array(
+                                       'level' => $v - 1,
+                                       'name' => $row['name']
+                               );
+                       }
+               }
+
+               return $pages;
+       }
+
+       //      }}}
+    // //      {{{ getCounties()
+
+       /**
+        * Configure the regions for member stored in the database into an array
+        *
+     * @return array the counties
+        * @access protected
+        */
+       protected function getCounties()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM county
+                                ORDER BY county_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $counties[$row['county_id']] = $row['county_name'];
+                       }
+                       if (!empty($counties)) {
+                               $counties = array('' => '-- Select County --') + $counties;
+                       } else {
+                               $counties = array('' => '-- No Counties Created Yet -- ');
+                       }
+                       return $counties;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+    // {{{ getRegions()
+
+       /**
+        * Configure the regions for member stored in the database into an array
+        *
+     * @return array the regions
+        * @access protected
+        */
+       protected function getRegions()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM region
+                                ORDER BY region_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $regions[$row['region_id']] = $row['region_name'];
+                       }
+                       if (!empty($regions)) {
+                               $regions = array('' => '-- Select Region --') + $regions;
+                       } else {
+                               $regions = array('' => '-- No Regions Created Yet -- ');
+                       }
+                       return $regions;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     _getEarliestCreateDate()
+
+    /**
+     * Description for _getEarliestCreateData()
+     *
+     * @param PDO $dbh PDO
+     *
+     * @return array
+     * @access private
+     */
+       private function _getEarliestCreateDate(PDO $dbh)
+       {
+               try {
+                       $sql = "
+                               SELECT date_part('month', min(create_date)) AS month,
+                                          date_part('day', min(create_date)) AS day,
+                                          date_part('year', min(create_date)) AS year
+                                 FROM member";
+
+                       $minDate = $dbh->query($sql, PDO::FETCH_ASSOC)->fetch();
+                       $date = array(
+                               'm' => $minDate['month'],
+                               'd' => $minDate['day'],
+                               'Y' => $minDate['year']
+                       );
+
+                       return $date;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _getSQLQuery()
+
+       /**
+        * generate the SQL query for the search
+        *
+        * @param PDO              $dbh    Database handler
+     * @param Config_Container $c      Configuration object
+     * @param array            $values Form submit values
+        *
+        * @return string SQL query string
+        * @access private
+        */
+       private function _getSQLQuery(PDO $dbh, Config_Container $c, array $values)
+       {
+               $useCtrlCities = $c->getItem('section', 'conf')
+                       ->getItem('directive', 'controlledCities')
+                       ->getContent();
+
+               $sql = "
+                       SELECT DISTINCT m.member_id
+                         FROM member m LEFT JOIN member_contacts mc USING(member_id),
+                                  member_last_updates mlu,
+                                  exploded_members_name emn";
+
+               $params = array(
+                       'm.member_id = emn.mid',
+                       "m.new_member <> '1'"
+               );
+
+               if ($values['active'] == 1) {
+                       $params[] = 'm.active = ' . $dbh->quote(1);
+               } elseif ($values['active'] == 0) {
+                       $params[] = 'm.active IS NULL';
+               } else {
+                       //      do nothing
+               }
+
+        if ($_REQUEST['page'] == 'newsletterSearch') {
+            $params[] = "(m.process_email is NOT NULL OR m.process_email <> '')";
+        }
+
+               if (isset($values['create_date_beg'])
+                       && is_array($values['create_date_beg'])
+                       && ctype_digit($values['create_date_beg']['m'])
+                       && ctype_digit($values['create_date_beg']['d'])
+                       && ctype_digit($values['create_date_beg']['Y'])
+               ) {
+                       $params[] = 'm.create_date >= ' .
+                               $dbh->quote(implode('-', $values['create_date_beg']));
+               }
+
+               if (isset($values['create_date_end'])
+                       && is_array($values['create_date_end'])
+                       && ctype_digit($values['create_date_end']['m'])
+                       && ctype_digit($values['create_date_end']['d'])
+                       && ctype_digit($values['create_date_end']['Y'])
+               ) {
+                       $params[] = 'm.create_date <= ' .
+                               $dbh->quote(implode('-', $values['create_date_end']));
+               }
+
+               if (isset($values['join_date_beg'])
+                       && is_array($values['join_date_beg'])
+                       && ctype_digit($values['join_date_beg']['m'])
+                       && ctype_digit($values['join_date_beg']['d'])
+                       && ctype_digit($values['join_date_beg']['Y'])
+               ) {
+                       $params[] = 'm.join_date >= ' .
+                               $dbh->quote(implode('-', $values['join_date_beg']));
+               }
+
+               if (isset($values['join_date_end'])
+                       && is_array($values['join_date_end'])
+                       && ctype_digit($values['join_date_end']['m'])
+                       && ctype_digit($values['join_date_end']['d'])
+                       && ctype_digit($values['join_date_end']['Y'])
+               ) {
+                       $params[] = 'm.join_date <= ' .
+                               $dbh->quote(implode('-', $values['join_date_end']));
+               }
+
+               if (isset($values['last_modified_date_beg'])
+                       && is_array($values['last_modified_date_beg'])
+                       && ctype_digit($values['last_modified_date_beg']['m'])
+                       && ctype_digit($values['last_modified_date_beg']['d'])
+                       && ctype_digit($values['last_modified_date_beg']['Y'])
+               ) {
+                       $lastModifiedTimestampBeg
+                               = implode('-', $values['last_modified_date_beg']) . ' 00:00:00';
+                       $params[]
+                               = 'mlu.timestamp >= ' . $dbh->quote($lastModifiedTimestampBeg);
+                       $params[] = 'm.member_id = mlu.member_id';
+               }
+
+               if (isset($values['last_modified_date_end'])
+                       && is_array($values['last_modified_date_end'])
+                       && ctype_digit($values['last_modified_date_end']['m'])
+                       && ctype_digit($values['last_modified_date_end']['d'])
+                       && ctype_digit($values['last_modified_date_end']['Y'])
+               ) {
+                       $lastModifiedTimestampEnd
+                               = implode('-', $values['last_modified_date_end']) . ' 23:59:59';
+                       $params[]
+                               = 'mlu.timestamp <= ' . $dbh->quote($lastModifiedTimestampEnd);
+                       $params[] = 'm.member_id = mlu.member_id';
+               }
+
+               //      Include all/any subcategories beneath selected cats
+               if (isset($values['category']) && is_array($values['category'])) {
+                       $categoryKeys = array();
+                       foreach ($values['category'] as $k => $v) {
+                               if ($category = filter_var($v, FILTER_VALIDATE_INT)) {
+                                       $tree = Toolkit_Common::getHierarchicalTreeStructure(
+                                               $this->dbh,
+                                               'category',
+                                               'category_id',
+                                               'parent_id',
+                                               'pos',
+                                               $category,
+                                               0,
+                                               false
+                                       );
+                                       $categoryKeys = array_merge($categoryKeys, array_keys($tree));
+                               }
+                       }
+
+                       $params[] = "
+                                 m.member_id in (
+                                                SELECT member_id
+                                                  FROM member_category
+                                 WHERE category_id in (" . implode(', ', $categoryKeys) . "))";
+               }
+
+               //      Fuzzy search on member name
+               if (isset($values['member_name']) && !empty($values['member_name'])) {
+                       $lowerName = strtolower($values['member_name']);
+                       $noSpaceMemberName = preg_replace('/[^[:alnum:]]/', '', urldecode($lowerName));
+                       $spaceMemberName = urldecode($lowerName);
+                       $sanitizedNoSpaceMemberName = $this->dbh->quote($noSpaceMemberName);
+                       $sanitizedSpaceMemberName = $this->dbh->quote($spaceMemberName);
+                       //      fuzzy name search
+                       $params[] = "
+                               (   regexp_replace(lower(m.member_name), '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceMemberName
+                                OR metaphone(lower(m.member_name), 4) = metaphone($sanitizedSpaceMemberName, 4)
+                               )
+                        OR (
+                                    m.member_id = emn.mid
+                                        AND m.new_member <> '1'
+                                AND (
+                                                $sanitizedNoSpaceMemberName ~* regexp_replace(lower(emn.part), '[^[:alnum:]]', '', 'g')
+                                         OR (metaphone($sanitizedSpaceMemberName, 4) = metaphone(lower(emn.part), 4))
+                                        )
+                                AND char_length(emn.part) > 1
+                               )";
+               }
+
+               if (   isset($values['member_contact_email'])
+                       && !empty($values['member_contact_email'])
+               ) {
+                       $lowerMemberEmail = strtolower($values['member_contact_email']);
+                       $memberEmail = preg_replace('/[^[:alnum:]]/', '', urldecode($lowerMemberEmail));
+                       $params[] = "regexp_replace(lower(m.member_contact_email), '[^[:alnum:]]', '', 'g') ~* " .
+                               $this->dbh->quote($memberEmail);
+               }
+
+        if ($useCtrlCities) {
+            if (ctype_digit($values['city_id'])) {
+                $params[] = "m.city_id = " . $this->dbh->quote($values['city_id']);
+            }
+        } else {
+            if (isset($values['city']) && !empty($values['city'])) {
+                               $lowerCity = strtolower($values['city']);
+                               $city = preg_replace('/[^[:alnum:]]/', '', urldecode($lowerCity));
+                $params[] = "regexp_replace(lower(m.city), '[^[:alnum:]]', '', 'g') ~* " .
+                                       $this->dbh->quote($city);
+            }
+        }
+        if ($region = filter_var($_REQUEST['region'], FILTER_VALIDATE_INT)) {
+            $params[] = "m.region = {$region}";
+        }
+        if ($county = filter_var($_REQUEST['county'], FILTER_VALIDATE_INT)) {
+            $params[] = "m.county = {$county}";
+        }
+
+               if (isset($values['state_id']) && ctype_digit($values['state_id'])) {
+                       $params[] = "m.state_id = " . $this->dbh->quote($values['state_id']);
+               }
+               if (isset($values['zip']) && !empty($values['zip'])) {
+                       $params[] = 'm.zip = ' . $this->dbh->quote($values['zip']);
+               }
+
+               //      Fuzzy search on primary contact first name
+               if (   isset($values['contact_fname'])
+                       && !empty($values['contact_fname'])
+               ) {
+                       $lowerPrimaryContactFname = strtolower($values['contact_fname']);
+                       $noSpaceContactFName = preg_replace('/[^[:alnum:]]/', '', urldecode($lowerPrimaryContactFname));
+                       $spaceContactFName = urldecode($lowerPrimaryContactFname);
+                       $sanitizedNoSpaceContactFName = $this->dbh->quote($noSpaceContactFName);
+                       $sanitizedSpaceContactFName = $this->dbh->quote($spaceContactFName);
+                       $params[] = "
+                               (
+                                       (
+                                               regexp_replace(lower(m.primary_contact_fname), '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceContactFName
+                                               OR
+                                               metaphone(lower(m.primary_contact_fname), 4) = metaphone($sanitizedSpaceContactFName, 4)
+                                       )
+                                       OR
+                                       (
+                                               (
+                                                       regexp_replace(lower(mc.fname), '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceContactFName
+                                                       OR
+                                                       metaphone(lower(mc.fname), 4) = metaphone($sanitizedSpaceContactFName, 4)
+                                               )
+                                               AND mc.member_id = m.member_id
+                                       )
+                               )";
+               }
+
+               //      Fuzzy search on primary contact last name
+               if (   isset($values['contact_lname'])
+                       && !empty($values['contact_lname'])
+               ) {
+                       $lowerPrimaryContactLname = strtolower($values['contact_lname']);
+                       $noSpaceContactLName = preg_replace('/[^[:alnum:]]/', '', urldecode($lowerPrimaryContactLname));
+                       $spaceContactLName = urldecode($lowerPrimaryContactLname);
+                       $sanitizedNoSpaceContactFName = $this->dbh->quote($noSpaceContactLName);
+                       $sanitizedSpaceContactFName = $this->dbh->quote($spaceContactLName);
+                       $params[] = "
+                               (
+                                       (
+                                               regexp_replace(lower(m.primary_contact_lname), '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceContactFName
+                                               OR
+                                               metaphone(lower(m.primary_contact_lname), 4) = metaphone($sanitizedSpaceContactFName, 4)
+                                       )
+                                       OR
+                                       (
+                                               (
+                                                       regexp_replace(lower(mc.lname), '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceContactFName
+                                                       OR
+                                                       metaphone(lower(mc.lname), 4) = metaphone($sanitizedSpaceContactFName, 4)
+                                               )
+                                               AND mc.member_id = m.member_id
+                                       )
+                               )";
+               }
+
+               if (   isset($values['process_email'])
+                       && !empty($values['process_email'])
+               ) {
+                       $lowerPrimaryContactEmail = strtolower($values['process_email']);
+                       $primaryContactEmail = preg_replace('/[^[:alnum:]]/', '', urldecode($lowerPrimaryContactEmail));
+                       $params[] = "regexp_replace(lower(m.process_email), '[^[:alnum:]]', '', 'g') ~* " .
+                               $this->dbh->quote($primaryContactEmail);
+               }
+
+        //  Limit to members whose first letter starts with the letter
+        //  a user clicked in the narrow alphabetically list.
+               if (isset($_GET['alpha']) && $_GET['alpha'] == '0-9') {
+                       $params[] = "substr(m.member_name, 1, 1) ~ '[0-9]'";
+               } elseif (isset($_GET['alpha']) && ctype_alpha($_GET['alpha'])) {
+                       $letter = $_GET['alpha'][0];
+            $params[] = "upper(substr(member_name, 1, 1)) = upper(" .
+                               $this->dbh->quote($letter) . ')';
+        }
+
+               $params = implode(' AND ', $params);
+
+               return "$sql WHERE $params";
+       }
+
+       //      }}}
+       //      {{{     _processData()
+
+       /**
+        * generate the array of member ids that were created from the search
+        *
+        * @param PDO              $dbh    Database handler
+     * @param Config_Container $c      Configuration object
+     * @param array            $values Form submit values
+        *
+        * @return void
+        * @access private
+     *
+        */
+       private function _processData(PDO $dbh, Config_Container $c, array $values)
+       {
+               $sql = $this->_getSQLQuery($dbh, $c, $values);
+
+               try {
+                       $this->_members = array();
+                       foreach ($dbh->query($sql, PDO::FETCH_ASSOC) as $row) {
+                               $this->_members[] = $row['member_id'];
+                       }
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $tpl = '<tr align="center"><td colspan="2">{element}</td></tr>';
+               $renderer->setElementTemplate($tpl, 'submit');
+       }
+
+    //  @codeCoverageIgnoreEnd
+       //      }}}
+
+       //      {{{     toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+        * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+        *
+        * @access protected
+        * @return string $output The Form to be rendered or success msg.
+        */
+       public function toHtml(PDO $dbh, Config_Container $c)
+       {
+               $jqueryuiPath = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle';
+               $GLOBALS['styleSheets'][] = "$jqueryuiPath/themes/base/jquery.ui.all.css";
+               $GLOBALS['bottomScripts'][] = "$jqueryuiPath/ui/minified/jquery.ui.core.min.js";
+               $GLOBALS['bottomScripts'][] = "$jqueryuiPath/ui/minified/jquery.ui.widget.min.js";
+               $GLOBALS['bottomScripts'][] = "$jqueryuiPath/ui/minified/jquery.ui.datepicker.min.js";
+               $GLOBALS['bottomScripts'][] = BASE_URL . 'Toolkit/Members/libjs/advancedsearch.js';
+
+               $this->setupRenderers();
+
+               if ($this->validate()) {
+                       $this->_processData($dbh, $c, $this->getSubmitValues());
+               }
+
+               return parent::toHTML();
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/AdvancedSearchController.php b/Toolkit/Members/Admin/AdvancedSearchController.php
new file mode 100644 (file)
index 0000000..26dd183
--- /dev/null
@@ -0,0 +1,96 @@
+<?php
+/**
+ * AdvancedSearchController.php
+ * 
+ * PHP versions 4 and 5
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Newsletters.php,v 1.9 2009/09/16 19:00:58 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Admin_AdvancedSearchController
+ * 
+ * Description for Toolkit_Members_Admin_AdvancedSearchController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      http://demo.gaslightmedia.com
+ */
+
+class Toolkit_Members_Admin_AdvancedSearchController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    /**
+     * Main action for controller. Runs admin template, list out all regions
+     * 
+     * @return mixed
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $GLOBALS['styleSheets'][] = BASE_URL . 'css/contactform.css';
+
+               HTTP_Session2::set('newSearch', true);
+               $searchForm = new Toolkit_Members_Admin_AdvancedSearch(
+            'advanced-record-search',
+                       'get',
+                       BASE_URL . 'admin/members.php',
+                       '',
+                       null,
+                       true
+               );
+
+        $searchForm->configureForm($this->registry->dbh, $this->registry->config);
+
+               $this->registry->controllerObject->content 
+            = $searchForm->toHtml($this->registry->dbh, $this->registry->config);
+               if ($results = $searchForm->getSearchResults()) {
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/member-list.js';
+
+                       $membersList = new Toolkit_Members_Admin_AdvancedSearchDataGrid(
+                               $this->registry->dbh,
+                               50
+                       );
+                       if ($_GET['d'] == 't' && ctype_digit($_GET['id'])) {
+                               $membersList->removeMember(
+                                       $_GET['id'],
+                                       new Toolkit_Image_Server()
+                               );
+                       }
+                       $membersList->setQuery($results);
+                       $membersList->setDefaultSort(array('sort_field' => 'ASC'));
+
+                       //  rendering engine to use
+                       $rEngine = new Structures_DataGrid_Renderer_Flexy();
+                       $rEngine->setContainer($this->registry->tEngine);
+
+                       $this->registry->controllerObject->content .=
+                               $membersList->toHtml($rEngine, 'listMembers.tpl');
+               }
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/AdvancedSearchDataGrid.php b/Toolkit/Members/Admin/AdvancedSearchDataGrid.php
new file mode 100644 (file)
index 0000000..2eb86af
--- /dev/null
@@ -0,0 +1,70 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * AdvancedSearchDataGrid.php
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @release  CVS: $Id: AdvancedSearchDataGrid.php,v 1.1 2010/01/11 15:08:46 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Admin_AdvancedSearchDataGrid
+ * 
+ * Description of Toolkit_Members_Admin_AdvancedSearchDataGrid
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+
+class Toolkit_Members_Admin_AdvancedSearchDataGrid
+       extends Toolkit_Members_Admin_ListMembers
+{
+    //  {{{ setControlObject()
+
+    /**
+     * don't call parents method
+     *
+     * @return void
+     * @access protected
+     */
+    protected function setControlObject() 
+    {
+    }
+
+    //  }}}
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param array $ids IDs array
+     * 
+     * @return void
+     * @access public
+     */
+    public function setQuery(array $ids)
+    {
+               $memberIds = implode(', ', $ids);
+               $sql = "
+                       SELECT *, LOWER(member_name) AS sort_field
+              FROM member m
+                         WHERE member_id IN ($memberIds)";
+
+        Toolkit_FlexyDataGridBuilder::setQuery($sql);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/AmenitiesController.php b/Toolkit/Members/Admin/AmenitiesController.php
new file mode 100644 (file)
index 0000000..51b2d74
--- /dev/null
@@ -0,0 +1,105 @@
+<?php
+/**
+ * AmenitiesController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_AmenitiesController
+ * 
+ * Description of Toolkit_Members_Admin_AmenitiesController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_AmenitiesController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    /**
+     * Description of indexAction()
+     * 
+     * @return string
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $amenityList = new Toolkit_Members_Admin_ListAmenities($this->registry->dbh);
+               $this->registry->controllerObject->content = $amenityList->renderAmenities();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     editAmenityAction()
+    /**
+     * Description of editAmnityAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function editAmenityAction()
+       {
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/edit-amenity.js';
+
+               $form = new Toolkit_Members_Admin_EditAmenity(
+            $this->registry->dbh,
+            'edit_amenity'
+        );
+        $form->configureForm();
+               $this->registry->controllerObject->content = $form->toHtml();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     listAmenitiesAction()
+    /**
+     * Description of listAmenitiesAction
+     * 
+     * @return string
+     * @access public
+     */
+       public function listAmenitiesAction()
+       {
+               return $this->indexAction();
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/AuthorizeNewMemberForm.php b/Toolkit/Members/Admin/AuthorizeNewMemberForm.php
new file mode 100755 (executable)
index 0000000..71e9999
--- /dev/null
@@ -0,0 +1,792 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Authorizes or denies new member admission into the DB
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AuthorizeNewMemberForm.php,v 1.19 2010/07/14 23:27:59 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Creates, Renders, Processes form for request to be added to Business DB
+ *
+ * This Form just sends the primary advisee an HTML email of the data
+ * that was filled in and requires them to add the users to the Business DB
+ * themselves.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_AuthorizeNewMemberForm extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * The name of the DB table that holds the member records
+        *
+        * @var array
+        * @access protected
+        */
+       public $tableName = 'member';
+
+       /**
+        * What do you want the success msg to be if the form validates successfully
+        *
+        * @var         string
+        * @access      protected
+        */
+       protected $successMsg = '<div id="form-success-top"></div>';
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The default rules to register for validating
+        *
+        * @var array
+        * @access protected
+        */
+       protected $registeredRules = array('zip', 'phone', 'memberlogo');
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access protected
+        */
+       protected $template;
+
+       //      }}}
+
+       //      {{{ __construct()
+
+       /**
+        * Constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+        * @param string $formName    Form's name.
+        * @param string $method      (optional) Form's method defaults to 'POST'
+        * @param string $action      (optional) Form's action.
+        * @param string $target      (optional) Form's target defaults to '_self'
+        * @param mixed  $attributes  (optional) Extra attributes for <form> tag.
+        * @param bool   $trackSubmit (optional) Whether to track if the form was
+        *                                                                               submitted by adding a special hidden
+        *                                                                               field.
+        *
+        * @access public
+        * @see    Toolkit_FormBuilder, HTML_QuickForm
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+               $this->template = dirname(__FILE__) . '/../templates/currentTables/';
+
+               $this->dbh = $pdo;
+
+               $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{     approveMember()
+
+
+    /**
+     * Set a members "new" flag to false
+     *
+     * @return boolean result of sql query
+     * @access protected
+     */
+       protected function approveMember()
+       {
+               try {
+                       $sql = "
+                UPDATE {$this->tableName}
+                   SET new_member = false
+                 WHERE member_id  = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       return $stmt->execute(array($_GET['id']));
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ configureConstants()
+
+       /**
+        * Sets the constants for the form
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureConstants()
+       {
+               $c = array(
+                       'new_member' => 0,
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for the form
+        *
+        * @return array $defaults Returns the array of defaults
+        *                                                 so children who call this function
+        *                                                 can obtain a copy of these values.
+        * @access protected
+        */
+       protected function configureDefaults()
+       {
+               $defaults = array();
+
+               try {
+                       if (ctype_digit($_GET['id'])) {
+                               $sql = "
+                    SELECT m.*
+                      FROM {$this->tableName} m
+                     WHERE m.member_id  = :mid
+                       AND m.new_member = true";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':mid', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                    foreach ($row as $i => $j) {
+                        $defaults[$i] = $j;
+                    }
+                }
+
+                $sql = "
+                       SELECT *
+                         FROM member_category
+                        WHERE member_id = :mid";
+
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(':mid', $_GET['id'], PDO::PARAM_INT);
+                $stmt->execute();
+                $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                $defaults['category_id'] = $row['category_id'];
+                               $defaults['description'] = strip_tags($defaults['description']);
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+               $this->setupDefaults($defaults);
+               return $defaults;
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureElements()
+       {
+        //  get reference to the [listing type] section of config file
+        $config =& $this->config->getItem('section', 'listing type');
+        //  get listing type
+        $singularDirective =& $config->getItem('directive', 'singular');
+        $singularType = $singularDirective->getContent();
+
+        //  get reference to [conf] section of config file
+        $config =& $this->config->getItem('section', 'conf');
+        //  get controlled cities
+        $ctrlCtyDirective =& $config->getItem('directive', 'controlledCities');
+
+        $states = Toolkit_Common::getStates($this->dbh);
+        $this->setCategories();
+
+               $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $submitBtns[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'approve',
+                       'display' => 'Approve',
+                       'opts'    => array('id' => 'approve')
+               );
+               $submitBtns[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'deny',
+                       'display' => 'Deny',
+                       'opts'    => array('id' => 'deny')
+               );
+
+               //      Member Information
+               $e[] = array(
+                       'type' => 'hidden',
+                       'req'  => false,
+                       'name' => 'new_member'
+               );
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'newMemberHdr',
+                       'display' => "$singularType Information"
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'member_name',
+                       'display' => $singularType . ' Name'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'primary_contact_fname',
+                       'display' => 'Primary Contact First Name'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'primary_contact_lname',
+                       'display' => 'Primary Contact Last Name'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'process_email',
+                       'display' => 'Primary Contact Email'
+               );
+        $e[] = array(
+            'type'    => 'select3',
+            'req'     => false,
+            'name'    => 'category_id',
+            'display' => "$singularType Category",
+            'opts'    => $this->categories,
+        );
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'physicalAddressHdr',
+                       'display' => 'Physical Address'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'street',
+                       'display' => 'Street Address'
+               );
+        if ($ctrlCtyDirective->getContent()) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'city_id',
+                'display' => 'City',
+                'opts'    => $this->getCities(),
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => false,
+                'name'    => 'city',
+                'display' => 'City',
+            );
+        }
+               $e[] = array(
+                       'type' => 'select',
+                       'req' => false,
+                       'name' => 'state_id',
+                       'display' => 'State / Provice',
+                       'opts' => array('' => '-- Select --') + $states
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'zip',
+                       'display' => 'Zip / Postal Code'
+               );
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'mailingAddressHdr',
+                       'display' => 'Mailing Address'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'mailing_address',
+                       'display' => 'Street Address'
+               );
+        if ($ctrlCtyDirective->getContent()) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'mailing_city_id',
+                'display' => 'City',
+                'opts'    => $this->getCities(),
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => false,
+                'name'    => 'mailing_city',
+                'display' => 'City',
+            );
+        }
+               $e[] = array(
+                       'type' => 'select',
+                       'req' => false,
+                       'name' => 'mailing_state_id',
+                       'display' => 'State / Provice',
+                       'opts' => array('' => '-- Select --') + $states
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'mailing_zip',
+                       'display' => 'Zip / Postal Code'
+               );
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'publicContactInfoHdr',
+                       'display' => 'Public Contact Information'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'phone',
+                       'display' => 'Phone'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'toll_free',
+                       'display' => 'Phone 2'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'fax',
+                       'display' => 'Fax'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'member_contact_email',
+                       'display' => 'Email on Website'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'url',
+                       'display' => 'Website Address'
+               );
+               $e[] = array(
+                       'type'    => 'textarea',
+                       'req'     => false,
+                       'name'    => 'description',
+                       'display' => "Description of $singularType",
+            'noCharLimit' => true
+               );
+               $e[] = array(
+                       'type'       => 'group',
+                       'req'        => false,
+                       'name'       => 'decision',
+                       'group'      => $submitBtns,
+                       'seperator'  => '',
+                       'appendName' => false
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+       /**
+        * Setup the filters to apply to the elements before we are
+        * handed the values submitted
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureFilters()
+       {
+               $f   = array();
+               $f[] = array(
+                       'element' => '__ALL__',
+                       'filter'  => 'trim'
+               );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureFilters();
+        $this->configureDefaults();
+        $this->configureConstants();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+        * @return void
+        * @access Protected
+        */
+       protected function configureRules()
+       {
+               $this->setupRules($rules);
+       }
+
+       //      }}}
+       //      {{{ createCategories()
+
+       /**
+        * Creates an array from the array of category tree objects
+        *
+     * @param array   $tree  linear category tree array
+     * @param integer $depth what level we are on
+     *
+        * @return array The array list of categories that
+        *                               that can be loaded into a select element
+        * @access protected
+        */
+       protected function createCategories($tree, $depth = 0)
+       {
+               $this->records[] = $tree->category;
+               if ($depth == 0) {
+                       $this->categories[$tree->catid] = "<span>{$tree->category}</span>";
+               } else {
+                       $this->categories[$tree->catid] = $tree->category;
+               }
+               if (empty($tree->children)) {
+                       return;
+               } else {
+                       ++$depth;
+                       foreach ($tree->children as $miniTrees) {
+                               $this->createCategories($miniTrees, $depth);
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{     denyMember()
+
+
+    /**
+     * Removes member from DB
+     *
+     * @return boolean Result of sql query
+     * @access protected
+     */
+       protected function denyMember()
+       {
+               try {
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE member_id  = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       return $stmt->execute(array($_GET['id']));
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     emailMember()
+
+
+    /**
+     * Emails member who requested to join
+     *
+     * If approved, sends email telling member how to login.
+     *
+     * If denied, sends email explaining they were denied and how to
+     * correct the problem if that was a mistake
+     *
+     * @param boolean $status If the member was approved/denied
+     * @param boolean $test   If this is a test
+     *
+     * @return mixed PEAR Error on mail failure, otherwise true
+     * @access public
+     */
+       public function emailMember($status, $test = false)
+       {
+        //  get reference to the [listing type] section of config file
+        $config =& $this->config->getItem('section', 'listing type');
+        //  get listing type
+        $singularDirective =& $config->getItem('directive', 'singular');
+        $singularType = $singularDirective->getContent();
+
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $data = $this->configureDefaults();
+               $page->base_url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL :
+                                                                                                               BASE_URL;
+               $page->client_name     = SITENAME;
+               $page->member_login    = $data['member_login'];
+               $page->member_passwd   = $data['member_passwd'];
+               $page->first_name      = $data['primary_contact_fname'];
+               $page->member_category = MEMBERS_CATEGORY;
+
+               $tpl = $status ? 'newMemberApproval.tpl' : 'newMemberDenial.tpl';
+               $template->compile($tpl);
+               //      Merge the compiled template with the $page object.
+               $htmlMsg = $template->bufferedOutputObject($page);
+
+               $crlf     = "\n";
+               $mimeMail = new Mail_mime($crlf);
+               $mimeMail->setFrom(SITENAME . ' <' . OWNER_EMAIL . '>');
+               $mimeMail->setSubject("New $singularType Request");
+               $mimeMail->setHTMLBody($htmlMsg);
+               $mimeMail->setTXTBody($msg);
+
+               $interface = $test ? 'mock' : 'mail';
+               $mail      =& Mail::factory($interface);
+               $body      = $mimeMail->get();
+               $headers   = $mimeMail->headers($hdrs);
+
+               try {
+                       $sql = "
+                               SELECT process_email
+                                 FROM {$this->tableName}
+                                WHERE member_id = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute(array($_GET['id']));
+                       $stmt->bindColumn('process_email', $email);
+                       $stmt->fetch();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+               $res = $mail->send($email, $headers, $body);
+
+               return PEAR::isError($res) ? Toolkit_Common::handleError($res) : $res;
+       }
+
+       //      }}}
+
+       //      {{{ getCities()
+
+       /**
+        * Configure the cities for member stored in the database into an array
+        *
+     * @return array the cities
+        * @access protected
+        */
+       protected function getCities()
+       {
+               $cities = array();
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM city
+                                ORDER BY city_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $cities[$row['city_id']] = $row['city_name'];
+                       }
+                       if (!empty($cities)) {
+                               $cities = array('' => '-- Select --') + $cities;
+                       } else {
+                               $cities = array('' => '-- No Cities Created Yet -- ');
+                       }
+                       return $cities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     processData()
+
+    /**
+     * Handles how to process the form when submitted
+     *
+     * @param array $values Form submitted values
+        *
+     * @return array Result of Insert / Update function
+     * @access protected
+     */
+       public function processData($values)
+       {
+               if (array_key_exists('deny', $values)) {
+                       $this->emailMember(false);
+                       return $this->denyMember();
+               } elseif (array_key_exists('approve', $values)) {
+                       $this->emailMember(true);
+                       return $this->approveMember();
+               }
+       }
+
+       //      }}}
+
+    //  {{{ setConfig()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function setConfig(Config_Container $c)
+    {
+        $this->config = $c;
+    }
+
+    //  }}}
+       //      {{{ setCategories()
+
+       /**
+        * Creates array structure of the category tree for use in a select element.
+        *
+        * This method will also instantiate a class property called tree for your
+        * class. This object will hold the tree structure of the categories list
+        * from the Database.
+        *
+        * @return array The array list of categories that can be loaded
+        *                               into a select element
+        *
+        * @access protected
+        */
+       protected function setCategories()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM category
+                                WHERE parent_id = 0
+                                ORDER BY name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $this->tree[] = new Toolkit_Members_CategoryTree($row['category_id'], $row['name'], $this->dbh);
+                       }
+                       if (!empty($this->tree)) {
+                               foreach ($this->tree as $t) {
+                                       $this->createCategories($t);
+                               }
+                       }
+
+                       if (empty($this->categories)) {
+                               $this->categories = array('' => '-- No Categories Created Yet --');
+                       } else {
+                               $this->categories
+                                       = array('' => '-- Select --') + $this->categories;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setupRenderers()
+
+    /**
+        * Setup how the form should render
+        *
+        * We also need to attach a couple specific rendering templates to
+        * a few special elements.
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="req">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate('<tr align="center"><td colspan="2">{element}</td></tr>', 'decision');
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+        * @access protected
+        * @return string $output The Form to be rendered or success msg.
+        */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               $this->freeze();
+               if ($this->validate()) {
+                       $this->cleanForm();
+                       if ($this->process(array(&$this, 'processData'))) {
+                               header('Location: ' . BASE_URL . 'admin/members.php?rt=Members&ac=newMemberRequests');
+                       }
+               } else if ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHTML();
+               } else {
+                       $output = parent::toHTML();
+               }
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/AuthorizeUpdates.php b/Toolkit/Members/Admin/AuthorizeUpdates.php
new file mode 100755 (executable)
index 0000000..637d522
--- /dev/null
@@ -0,0 +1,1770 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: AuthorizeUpdates.php,v 1.17 2010/07/14 23:27:59 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handle processing all the update requests from members
+ *
+ * @category  MembersDB
+ * @package      Toolkit_Members
+ * @author       Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_AuthorizeUpdates extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+    /**
+     * The member we are going to process updates for
+     *
+     * @var integer
+     * @access private
+     */
+    private $_mid;
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_updates';
+
+       /**
+        * Array of data that holds the meta data info on the table
+        *
+        * Contains information on the type of fields in the database.
+        * That way when we run our automated SQL queries with our PDO
+        * we can properly bind data to our SQL queries.  This will
+        * allow for one more layer of protection against any sql
+        * injection attempts.
+        *
+        * @var string
+        * @access public
+        * @see Toolkit_Common::processData()
+        */
+       public $tableMetaData;
+
+       /**
+        * The name of the template used to render the business info form.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'authorizeChanges.tpl';
+
+       /**
+        * Form access from inside the template
+        *
+        * @var object
+        * @access protected
+        */
+       protected $view;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field
+        *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+
+               $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{     commitUpdates
+
+    /**
+     * Commit the updates requested by the member
+     *
+     * @param string $table   The table to commit any updates for
+     * @param array  $fields  The fields to update
+     * @param array  $updates The updates
+        *
+     * @return boolean true on success, false on error
+     * @access protected
+     */
+       protected function commitUpdates($table, array $fields, array $updates)
+       {
+               foreach ($fields as $k => &$v) {
+                       $orig          = $v;
+                       list ($id, $v) = explode('_', $v, 2);
+                       if (array_key_exists("{$orig}_update", $updates)) {
+                               $updates["{$v}_update"] = $updates["{$orig}_update"];
+                               unset($updates["{$orig}_update"]);
+                       }
+               }
+               try {
+                       $this->dbh->beginTransaction();
+                       //      This will be the query we will use at the end to update the
+                       //      members record.
+                       $sql        = $this->getUpdateQuery($table, $fields);
+
+                       //      hack to fix states trying to update w/ the
+                       //      text ie (North Carolina - go heels!) vs. field id.
+                       unset(
+                $updates['state_id_update'],
+                $updates['city_id_update'],
+                $updates['mailing_state_id_update']
+            );
+                       $updateStmt = $this->dbh->prepare($sql);
+                       $updateStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+
+                       //      This will be the query we will use to remove the updates
+                       //      from the update table.  By removing the field from the updates
+                       //      table it takes that field out of a "pending" state, by removing all
+                       //      of the fields for a member out of the updates table it removes
+                       //      that member from being in a "pending" state.
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                                WHERE field        = :field
+                                  AND member_id    = :member_id";
+
+                       $deleteStmt = $this->dbh->prepare($sql);
+                       $deleteStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+
+                       //      This will be the query we will use to get the updated fields
+                       //      information.
+                       $sql =  "
+                               SELECT *
+                                 FROM {$this->tableName}
+                                WHERE id in (
+                                               SELECT max(id)
+                                                 FROM {$this->tableName}
+                                                WHERE member_id     = :member_id
+                                                  AND field   = :field)";
+
+                       $fetchStmt = $this->dbh->prepare($sql);
+                       $fetchStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       foreach ($fields as $k => &$f) {
+                               unset($v);
+                               //      Get the newest row for this field for this member.
+                               $fetchStmt->bindParam(':field', $f, PDO::PARAM_STR);
+                               $fetchStmt->execute();
+                               $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                               //      Get the update to apply.
+                               if (array_key_exists("{$f}_update", $updates)) {
+                                       $v = $updates["{$f}_update"];
+                               } else {
+                                       $v = $row['update'];
+                               }
+
+                               //      Get the dataType for the PDO Statement.
+                               $metaData = $row['data_type'];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               //      for empty values that are not actually a zero (0), we
+                               //      want to insert null's.
+                               //      This will help hold the unique values for member_logins,
+                               //      as empty values '', are not considered unique
+                               if (empty($v) && $v !== 0) {
+                                       $v        = null;
+                                       $dataType = PDO::PARAM_NULL;
+                               }
+                               //      Bind the update for later execution.
+                               $updateStmt->bindParam(":$f", $v, $dataType);
+
+                               //      Remove this field from the updates
+                               $deleteStmt->bindParam(':field', $f, PDO::PARAM_STR);
+                               $deleteStmt->execute();
+                       }
+                       $updateStmt->execute();
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for the an existing member
+        *
+        * Populates data for the main member form.  Also grabs
+        * data to populate the modules on the form if needed.
+        *
+        * @return array $defaults Returns the array of defaults
+        *                                                 so children who call this function
+        *                                                 can obtain a copy of these values.
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               $updatedFieldValues  = $this->getUpdatedFieldValues();
+               $originalFieldValues = $this->getOriginalFieldValues();
+
+               if (is_array($updatedFieldValues)) {
+                       $defaults = $updatedFieldValues;
+               }
+
+               if (is_array($originalFieldValues)) {
+                       if (is_array($defaults)) {
+                               $defaults += $originalFieldValues;
+                       } else {
+                               $defaults = $originalFieldValues;
+                       }
+               }
+
+               $this->setupDefaults($defaults);
+               return $defaults;
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * Categories are populated into the protected class property $categories.
+        * These categories are used to populate the select list of categories.
+        * Modules are configured before any elements are setup, that way we will
+        * know if we need to include them in the rendering of the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+               //      Get the newest updates in the update table for this member
+               //      for each field that was updated.
+               try {
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE id IN (
+                                               SELECT max(id)
+                                                 FROM {$this->tableName}
+                                                WHERE member_id     = :member_id
+                                                GROUP BY field, foreign_key)
+                 ORDER BY db_table, foreign_key, id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               //      If we are dealing w/ a credit card, this
+                               //      will extract the name of the card.
+                               //      Otherwise, it will leave the value unchanged.
+                               $pattern      = '/creditCards\[(.+)\]/';
+                               $replacement  = '$1';
+                               $row['field'] = preg_replace($pattern, $replacement, $row['field']);
+                               $updates[]    = $row;
+                               switch ($row['field_type']) {
+                               case 'select' :
+                               case 'checkbox' :
+                                       $elementsToFreeze[$row['id']] = $row['field'];
+                                       break;
+
+                               default :
+                                       break;
+                               }
+                       }
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+
+               $fields = $labels = array();
+               if (is_array($updates)) {
+                       //      We're going to need to alter how some of the fields
+                       //      are displayed on the page.  This is where we set them up.
+                       foreach ($updates as $u) {
+                               unset($type, $opts);
+                               //      Determine which fields should be a text field so
+                               //      the admin can update them w/ thier own text.
+                               switch ($u['data_type']) {
+                               case 'text' :
+                               case 'integer' :
+                                       $textField = true;
+                                       break;
+
+                               default :
+                                       $textField = false;
+                                       break;
+                               }
+                               if ($textField) {
+                                       switch ($u['label']) {
+                                       case 'Description' :
+                                       case 'Special Package Description' :
+                                       case 'Golf Package Description' :
+                                               $type = 'textarea';
+                                               $opts = array(
+                                                       'id' => 'd' . microtime(),
+                                                       'rows' => 8,
+                                                       'cols' => 43,
+                                               );
+                                               break;
+
+                                       default :
+                                               $type = 'text';
+                                               $opts = array('class' => 'text');
+                                               break;
+                                       }
+                               }
+                               //      If we are dealing w/ the fields for the restaurant module
+                               //      we need to alter the labels of the text fields.
+                               //      Otherwise we could potentially have multiple [To] or [From]
+                               //      fields and no way to discern which meal they represent.
+                               if ($u['db_table'] == 'member_restaurants') {
+                                       if ($u['data_type'] == 'text') {
+                                               $u['label'] = ucwords(str_replace('_', ' ', $u['field']));
+                                       }
+                               }
+                               if ($u['db_table'] == 'member' && $u['field'] == 'logo') {
+                                       $u['label'] = '<div class="pendingLogo">
+                                               <img alt="'.$u['update'].'"
+                                               src="'.MEMBER_PHOTOS.$u['update'].'">Main Image</div>';
+                               }
+                               if ($u['db_table'] == 'member_packages' && $u['field'] == 'image') {
+                                       unset($type, $opts);
+                               }
+                               if (!isset($type)) {
+                                       $type = 'static';
+                               }
+                               $labels[$u['id']][$u['field']]['label']    = $u['label'];
+                               $labels[$u['id']][$u['field']]['db_table'] = $u['db_table'];
+
+                               $fields[$u['id']][$u['field']][] = array('type' => 'static', 'req' => false, 'name' => "{$u['id']}_{$u['field']}_orig");
+                               $fields[$u['id']][$u['field']][] = array('type' => $type, 'req' => false, 'name' => "{$u['id']}_{$u['field']}_update", 'opts' => $opts);
+                       }
+                       $elements[] = array('type' => 'header', 'req' => false, 'name' => 'memberInfoHdr',      'display' => 'Updates', 'col1' => true);
+                       foreach ($fields as $rowid => $field) {
+                               foreach ($field as $k => $arr) {
+                                       if ($table != $labels[$rowid][$k]['db_table']) {
+                                               $elements[] = array('type' => 'header', 'req' => false, 'name' => 'table',      'display' => ucwords(str_replace('_', ' ', $labels[$rowid][$k]['db_table'])));
+                                               $table      = $labels[$rowid][$k]['db_table'];
+                                       }
+                                       $elements[] = array('type' => 'group',  'req' => false, 'name' => "{$rowid}_{$k}", 'group' => $field[$k],       'label' => $labels[$rowid][$k]['label'], 'seperator' => '&nbsp;', 'appendName' => false);
+                               }
+                       }
+               }
+
+               $this->setupElements($elements);
+
+               if (!empty($elementsToFreeze)) {
+                       foreach ($elementsToFreeze as $k => $v) {
+                               $eName = "{$k}_{$v}";
+                               if ($this->elementExists($eName)) {
+                                       $e =& $this->getElement($eName);
+                                       if (PEAR::isError($e)) {
+                                               return Toolkit_Common::handleError($e);
+                                       } else {
+                                               $e->freeze();
+                                       }
+                               }
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+       /**
+        * Setup the filters to apply to the elements before we are
+        * handed the values submitted
+        *
+        * @return void
+        * @access public
+        */
+       public function configureFilters()
+       {
+               $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+
+               $this->setupFilters($filters);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return mixed PEAR error if no member id is set, otherwise true
+     * @access public
+     */
+    public function configureForm()
+    {
+        if (!is_numeric($this->_mid)) {
+            return PEAR::raiseError('Invalid member id');
+        }
+
+        $this->configureElements();
+        $this->configureFilters();
+        //$this->configureRules();
+        $this->configureDefaults();
+
+        return true;
+    }
+
+    //  }}}
+       //      {{{ configureModules()
+
+       /**
+        * Turns on a modules if the member has the appropriate category
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureModules()
+       {
+               if (is_array($this->memberCategories)) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE category_id = :cid";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               foreach ($this->memberCategories as $cid => $v) {
+                                       $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                       $stmt->execute();
+                                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                                       if ($row['accommodations'] == 't') {
+                                               $this->accommodations = true;
+                                       }
+                                       if ($row['restaurant'] == 't') {
+                                               $this->restaurant = true;
+                                       }
+                                       if ($row['golf'] == 't') {
+                                               $this->golf = true;
+                                       }
+                               }
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+               //      Define the rules for each element in the group.
+               $num_rule = array('ERROR: Must contain a valid positive or negative decimal number!', 'numeric');
+               //      Collect together the rules for each element.
+               $lat_rules = array('lat' => array($num_rule));
+               $lon_rules = array('lon' => array($num_rule));
+
+               $rules[] = array('element' => 'reservation_id', 'message' => 'ERROR: Must be an integer!',      'type' => 'numeric', 'format' => null, 'validation' => $this->validationType, 'reset' => false, 'force' => false);
+               $rules[] = array('element' => 'num_rooms',              'message' => 'ERROR: Must be an integer!',      'type' => 'numeric', 'format' => null, 'validation' => $this->validationType, 'reset' => false, 'force' => false);
+               $rules[] = array('element' => 'latitude',               'message' => 'ERROR:',  'type' => 'group', 'format' => $lat_rules, 'validation' => $this->validationType, 'reset' => false,     'force' => false);
+               $rules[] = array('element' => 'longitude',              'message' => 'ERROR:',  'type' => 'group', 'format' => $lon_rules, 'validation' => $this->validationType, 'reset' => false,     'force' => false);
+               $rules[] = array('element' => 'member_name',    'message' => 'ERROR: Name Already used!',       'type' => 'callback', 'format' => array($this, 'checkMemberName'), 'validation' => $this->validationType, 'reset' => false,     'force' => false);
+               $rules[] = array('element' => 'member_login',   'message' => 'ERROR: Already used, Please choose another!',     'type' => 'callback', 'format' => array($this, 'checkUName'), 'validation' => $this->validationType, 'reset' => false,  'force' => false);
+               $rules[] = array('element' => 'zip',                    'message' => 'ERROR: Invalid Zip Code!',        'type' => 'zip', 'format' => array('requireDBCheck' => false), 'validation' => $this->validationType, 'reset' => false, 'force' => false);
+               $rules[] = array('element' => 'phone',                  'message' => 'ERROR: Invalid Phone Number!','type' => 'phone', 'format' => null, 'validation' => $this->validationType, 'reset' => false,       'force' => false);
+               $rules[] = array('element' => 'fax',                    'message' => 'ERROR: Invalid Phone Number!','type' => 'phone', 'format' => null, 'validation' => $this->validationType, 'reset' => false,       'force' => false);
+
+               $this->setupRules($rules);
+       }
+
+       //      }}}
+
+       //      {{{     getMultipleFieldUpdates()
+
+       /**
+        * Gets the current values for multiple fields of members
+        *
+        * Multiple fields are ones that a member can have many of.  They idealy
+        * need a foreign key, but it is impossible to set up dynamic foreign keys.
+        * examples of these fields are photo captions or file name, or newly added
+        * files.  Since a member can have multiple of these fields pending at the
+        * same time, we need to figure out the original value for the file names,
+        * captions, etc...  of these fields.
+        *
+        * To get these fields, figure out which ones have updates in the updates
+        * table and get corresponding field from the original table. Then use the
+        * psuedo foreign_key to get the corresponding match in the actual table.
+        *
+        * @return array All the original updates made by the member
+        * @access protected
+        * @see    Toolkit_Members_authorizeupdates::getOriginalFieldValues()
+        */
+       protected function getMultipleFieldUpdates()
+       {
+        $tables = array();
+        //     Then we need to get all the tables which DO NOT have DISTINCT
+        //     fields in the updates table.  That means they DO have a
+        //     psuedo foreign_key pointing back to them.  These are going
+        //     to take a little more work to obtain the original values.
+        $sql = "
+            SELECT DISTINCT db_table
+              FROM {$this->tableName}
+             WHERE foreign_key is NOT NULL";
+        foreach ($this->dbh->query($sql) as $row) {
+            $tables[] = $row['db_table'];
+        }
+
+        if (empty($tables)) {
+            return $tables;
+        }
+
+               //      This query will get all the fields that we need to get
+               //      from the original table.
+               $sql = "
+            SELECT *
+              FROM {$this->tableName}
+             WHERE id in (
+                                       SELECT max(id)
+                                         FROM {$this->tableName}
+                                        WHERE db_table  = :db_table
+                                          AND member_id = :member_id
+                                        GROUP BY field, foreign_key)";
+
+               $getFieldStmt = $this->dbh->prepare($sql);
+               $getFieldStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+
+        $defaults = array();
+               foreach ($tables as $t) {
+                       $getFieldStmt->bindParam(':db_table', $t, PDO::PARAM_STR);
+                       $getFieldStmt->execute();
+
+                       //      This query will get the current value that the member
+                       //      has stored in the DB for the field we want.
+                       $sql = "
+                SELECT %s
+                  FROM $t
+                 WHERE id = %d";
+
+                       while ($row = $getFieldStmt->fetch(PDO::FETCH_ASSOC)) {
+                               if ($row['data_type'] == 'text') {
+                                       $newSql  = sprintf($sql, $row['field'], $row['foreign_key']);
+                                       $current
+                        = $this->dbh->query($newSql)->fetch();
+                                       if (empty($current[$row['field']])) {
+                                               $current[$row['field']] = 'Did not previously exist.';
+                                       } elseif ($t == 'member_packages') {
+                                               if ($row['field'] == 'image') {
+                                                       $current[$row['field']]
+                                = '<div class="oldPackageImage">Old Image
+                                                               <img class="oldPackageImage"
+                                                                       alt="'.$current[$row['field']].'"
+                                                                       src="'.MEMBER_PHOTOS.$current[$row['field']].'">
+                                                               </div>';
+                                               }
+                                       }
+
+                                       if ($t == 'member_packages' && $row['field'] == 'image') {
+                                           $sql = "
+                                              SELECT *
+                                                FROM member_packages
+                                               WHERE id = {$row['foreign_key']}";
+                                           $package = $this->dbh->query($sql)->fetch(PDO::FETCH_ASSOC);
+
+                                           if ($package['pending']) {
+                                               $defaults["{$row['id']}_{$row['field']}_orig"] = '';
+                                           } else {
+                            $defaults["{$row['id']}_{$row['field']}_orig"]
+                                = $current[$row['field']];
+                                           }
+                                       } else {
+                                          $defaults["{$row['id']}_{$row['field']}_orig"]
+                            = $current[$row['field']];
+                                       }
+                               }
+                       }
+               }
+
+               return $defaults;
+       }
+
+       //      }}}
+       //      {{{     getOriginalFieldValues()
+
+       /**
+        * Gets all the original values for the fields that have pending updates
+        *
+        * @return array of updates for all the fields that the member sent
+        * @access protected
+        */
+       protected function getOriginalFieldValues()
+       {
+               try {
+            $staticUpdates  = $this->getSingleFieldUpdates();
+            $dynamicUpdates = $this->getMultipleFieldUpdates();
+
+                       $defaults = array_merge($staticUpdates, $dynamicUpdates);
+
+                       return $defaults;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getSingleFieldUpdates()
+
+       /**
+        * Gets the current values for single fields of members
+        *
+        * Single fields are ones that can only show reference one field from
+        * the updates table to a member. Such as, url, description, num_rooms,
+        * etc...
+        * These field will only come from the member table or any member module
+        * table (golf, restaurant, accommodations).
+        *
+        * To get these fields, figure out which ones have updates in the updates
+        * table and get corresponding field from the original table.
+        *
+        * @return array
+        * @access protected
+        * @see    Toolkit_Members_authorizeupdates::getOriginalFieldValues()
+        */
+       protected function getSingleFieldUpdates()
+       {
+        $tables = array();
+        //  We need to get all the tables which have DISTINCT fields
+        //  in the updates table. That means they do not have a
+        //  psuedo foreign_key pointing back to them.  These will be
+        //  easier to get the original values for.
+        $sql = "
+            SELECT DISTINCT db_table
+              FROM {$this->tableName}
+             WHERE foreign_key is null";
+        foreach ($this->dbh->query($sql) as $row) {
+            $tables[] = $row['db_table'];
+        }
+
+        if (empty($tables)) {
+            return $tables;
+        }
+
+               //      This query will get all the fields that we need to get
+               //      from the original table.
+               $sql = "
+            SELECT *
+              FROM {$this->tableName}
+             WHERE id in (
+                                       SELECT max(id)
+                                         FROM {$this->tableName}
+                                        WHERE db_table  = :db_table
+                                          AND member_id = :member_id
+                                        GROUP BY field)";
+
+               $getFieldStmt = $this->dbh->prepare($sql);
+               $getFieldStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+
+        $defaults = array();
+        //     We need to get all the tables which have DISTINCT fields
+               foreach ($tables as &$t) {
+                       $getFieldStmt->bindParam(':db_table', $t, PDO::PARAM_STR);
+                       $getFieldStmt->execute();
+
+                       //      This query will get the current value that the member
+                       //      has stored in the DB for the field we want.
+                       $sql = "
+                SELECT %s
+                  FROM $t
+                 WHERE member_id = {$this->_mid}";
+
+                       while ($row = $getFieldStmt->fetch()) {
+                               if ($row['data_type'] == 'text') {
+                                       $newSql  = sprintf($sql, $row['field']);
+                                       $current
+                        = $this->dbh->query($newSql)->fetch();
+
+                                       $defaults["{$row['id']}_{$row['field']}_orig"]
+                        = $current[$row['field']];
+                               }
+                               if ($row['field'] == 'state_id') {
+                                       $locationNames = '
+                                                ,(
+                                               select state_name
+                                                 from state
+                                                where state.state_id = member.state_id) as state_id';
+
+                                       $newSql  = sprintf($sql, $row['field'] . $locationNames);
+                                       $current
+                        = $this->dbh->query($newSql)->fetch();
+
+                                       $defaults["{$row['id']}_{$row['field']}_orig"]
+                        = $current[$row['field']];
+                               }
+                       }
+               }
+
+               return $defaults;
+       }
+
+       //      }}}
+       //      {{{     getUpdateQuery()
+
+    /**
+     * Get the update query for a table in the database
+     *
+     * @param string $tname    The table name to update in the database
+     * @param array  $accepted All the accepted updates/changes
+        *
+     * @return string The update query to run against the database
+     * @access protected
+     */
+       protected function getUpdateQuery($tname, array $accepted)
+       {
+               $params = array_values($accepted);
+               $length = count($params);
+               for ($i = 0; $i < $length; ++$i) {
+                       $bindParams .= "{$params[$i]} = :{$params[$i]}";
+                       if ($i < ($length - 1)) {
+                               $bindParams .= ', ';
+                       }
+               }
+               $sql = "
+                       UPDATE $tname
+                          SET $bindParams
+                       WHERE member_id = :member_id";
+               return $sql;
+       }
+
+       //      }}}
+       //      {{{     getUpdatedFieldValues()
+
+       /**
+        * Gets all the values for the newest updates
+        *
+        * @return array The updated values
+        * @access protected
+        */
+       protected function getUpdatedFieldValues()
+       {
+               try {
+                       //      Get all the latest updates, When we are dealing w/ the state_id
+                       //      fields, get the state name vs showing the id number.
+                       //      users won't know what the # is.
+                       $sql = "
+                               SELECT *,
+                                  CASE
+                   WHEN field = 'city_id' THEN (
+                                       SELECT city_name
+                                         FROM city
+                                        WHERE city_id   = CAST(UPDATE AS integer) )
+                   WHEN field = 'mailing_state_id' AND update != '' THEN (
+                                       SELECT state_name
+                                         FROM state
+                                        WHERE state_id   = CAST(UPDATE AS integer) )
+                   WHEN field = 'mailing_state_id' AND update = '' THEN NULL
+                                  WHEN field = 'state_id' THEN (
+                                       SELECT state_name
+                                         FROM state
+                                        WHERE state_id   = CAST(UPDATE AS integer) )
+                                  WHEN field ~* 'creditCards' AND update = '0' THEN 'Removed'
+                                  WHEN field ~* 'creditCards' AND update = '1' THEN 'Added'
+                                  WHEN db_table = 'member_amenity' AND update = '0' THEN 'Removed'
+                                  WHEN db_table = 'member_amenity' AND update = '1' THEN 'Added'
+                                  ELSE UPDATE END AS
+                               UPDATE
+                                 FROM {$this->tableName}
+                                WHERE id IN (
+                                               SELECT MAX(id)
+                                                 FROM {$this->tableName}
+                                                WHERE member_id = :member_id
+                                                GROUP BY field, foreign_key)
+                               ORDER BY db_table, foreign_key, id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               //      If we are dealing w/ a credit card, this
+                               //      will extract the name of the card.
+                               //      Otherwise, it will leave the value unchanged.
+                               $pattern      = '/creditCards\[(.+)\]/';
+                               $replacement  = '$1';
+                               $row['field'] = preg_replace($pattern, $replacement, $row['field']);
+                               if (empty($row['update'])) {
+                                       if ($row['data_type'] == 'boolean') {
+                                               $row['update'] = 'Off';
+                                       }
+                               } elseif ($row['data_type'] == 'boolean') {
+                                       $row['update'] = 'On';
+                               }
+
+                               //      Handle all the member photos requests
+                               if ($row['db_table'] == 'member_photos') {
+                                       //      The boolean field will only be for the pending status
+                                       //      if the data_type is boolean we know we are dealing
+                                       //      with a newly uploaded image
+                                       if ($row['data_type'] == 'boolean') {
+                                               //      No need to show any instructions for
+                                               //      the accept/reject buttons
+                                               $row['update'] = 'Added';
+                                       }
+                               }
+                               if ($row['db_table'] == 'member') {
+                                       if ($row['field'] == 'logo') {
+                                               $row['update'] = 'Updated';
+                                       }
+                               }
+                               if ($row['db_table'] == 'member_files') {
+                                       //      if the data_type is boolean we know we are dealing
+                                       //      with a newly uploaded file
+                                       if ($row['data_type'] == 'boolean') {
+                                               //      No need to show any instructions for
+                                               //      the accept/reject buttons
+                                               $row['update'] = 'Added';
+                                       }
+                               }
+                               if ($row['db_table'] == 'member_packages') {
+                                       if ($row['field'] == 'image') {
+                                               $row['update'] = ' <div class="newPackageImage">
+                                                               New Image
+                                                               <img alt="'.$row['update'].'"
+                                                               class="newPackageImage"
+                                                               src="'.MEMBER_PHOTOS.$row['update'].'">
+                                                               </div>';
+                                       }
+                               }
+                               $defaults["{$row['id']}_{$row['field']}_update"] = $row['update'];
+                       }
+
+                       return $defaults;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     group()
+
+       /**
+        * Gets the group [table name] the field is supposed to be a part of
+        *
+        * @param string $field the name of the field in the db.
+        *
+        * @return string
+        * @access public
+        */
+       public function group($field)
+       {
+               //      The field is going to come in as [id]_[field name]
+               //      so we need to extract the field name from the id.
+               list($id, $field) = explode('_', $field, 2);
+               try {
+                       $sql = "
+                SELECT db_table
+                  FROM {$this->tableName}
+                 WHERE id = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                       return $row['db_table'];
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+       /**
+        * Handles processing the submitted forms data.
+        *
+        * Sets up the table meta data so we can insert into the member table.
+        * removes any unwanted fields from the values array.  these fields
+        * will be denoted by the '_rmv' at the end of thier name in the
+        * configureElements function
+        *
+        * <example>
+        * ... 'name' => 'remove_rmv', ...
+        * </example>
+        *
+        * This function also verifies that the lat/lon values were properly filled
+        * out, if they were left blank then the values will either be looked up
+        * via google maps or through our own zip DB. These values will then be
+        * inserted into the values array AND also injected into the form field
+        * values so they will display when the form comes back around.
+        *
+        * The form then decides if it is handeling a new member or not and calls
+        * the appropriate function to insert or update data.
+        *
+        * @param array $values The array of all submitted form values.
+        *
+        * @return boolean Whether the insert/update succeeded.
+        * @access protected
+        * @see    Toolkit_Members_EditMemberInfo::configureElements()
+        */
+       protected function processData($values)
+       {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       default :
+                               if (preg_match('/^.+_rmv$/', $k)) {
+                                       unset($values[$k]);
+                               }
+                               break;
+                       }
+               }
+
+               $this->updateData($values);
+               $listPage = BASE_URL . "admin/members.php?rt=Members&ac=pendingUpdates";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+    //  {{{ setMember()
+
+    /**
+     * Sets the member id to use for updating
+     *
+     * @param integer $mid Target Member Id
+     *
+     * @return object PEAR Error on invalid member id
+     * @access public
+     */
+    public function setMember($mid)
+    {
+        if (!is_numeric($mid)) {
+            return PEAR::raiseError('Invalid member id');
+        } elseif (!ctype_digit($mid) && !is_int($mid)) {
+            return PEAR::raiseError('Invalid member id string');
+        }
+        $this->_mid = $mid;
+    }
+
+    //  }}}
+       //      {{{ setupRenderers()
+
+    /**
+     * Handles compiling and rendering the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view       = $this;
+               $this->view->form = $renderer->toObject();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml()
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+
+               if ($this->validated) {
+                       $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+               }
+
+               //      ProcessData handles settingup the lat/lon coordinates if they were
+               //      not     entered into the form.  these values ar calculated and then
+               //      inserted into the forms element values. So we need to process the
+               //      data first and then render the form.
+               $this->setupRenderers();
+
+               return $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+       //      {{{ updateAmenities()
+
+       /**
+        * Handle updating any approvals or rejections on the member amenities
+        *
+        * @param array $amenities The amenity update statuses submitted from the form
+        *
+        * @return bool True on success, false on error.
+        * @access protected
+        */
+       protected function updateAmenities($amenities)
+       {
+               if (empty($amenities)) {
+                       return true;
+               }
+               try {
+                       $this->dbh->beginTransaction();
+                       //      Stmt to find the newest request in the updates table.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE id = :id";
+
+                       $fetchStmt = $this->dbh->prepare($sql);
+                       //      Stmt to add amenity to member.
+                       $sql = "
+                INSERT INTO member_amenity(member_id, amenity_id)
+                VALUES (:member_id, :aid)";
+
+                       $insStmt = $this->dbh->prepare($sql);
+                       $insStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       //      Stmt to remove amenity from member.
+                       $sql = "
+                               DELETE FROM member_amenity
+                                WHERE amenity_id = :aid
+                   AND member_id = :member_id";
+
+                       $delStmt = $this->dbh->prepare($sql);
+                       //      Remove from updates table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE member_id          = :member_id
+                   AND db_table     = 'member_amenity'
+                   AND field        = :aid";
+
+                       $remStmt = $this->dbh->prepare($sql);
+                       $remStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       //      Loop through all the amenities and see if the update was
+                       //      accepted or not.  If it was accepted, get the update
+                       //      row from the updates table and find out if the update
+                       //      was to add [update = 1] the card or remove [update = 0].
+                       //      Perform the update, and then remove the requests from the
+                       //      updates table.
+                       foreach ($amenities as $aid => $accepted) {
+                               list($id, $aid) = explode('_', $aid, 2);
+                               if ($accepted == 'yes') {
+                                       $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                                       $fetchStmt->execute();
+                                       $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                                       if ($row['update']) {
+                                               //      Remove the the cards from from the db to make
+                                               //      sure we don't try to insert the same card to
+                                               //      a member twice and conflict w/ the unique
+                                               //      constraint on member_id and ccard_id
+                                               $delStmt->bindParam(':aid', $aid, PDO::PARAM_STR);
+                        $delStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                                               $delStmt->execute();
+                                               //      Insert the card as a row into the db.
+                                               $insStmt->bindParam(':aid', $aid, PDO::PARAM_STR);
+                                               $insStmt->execute();
+                                       } else {
+                                               //      Remove the the cards from from the db.
+                                               $delStmt->bindParam(':aid', $aid, PDO::PARAM_STR);
+                        $delStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                                               $delStmt->execute();
+                                       }
+
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':aid', $aid, PDO::PARAM_STR);
+                                       $remStmt->execute();
+                               } else {
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':aid', $aid, PDO::PARAM_STR);
+                                       $remStmt->execute();
+                               }
+                       }
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ updateCCards()
+
+       /**
+        * Handle updating any approvals or rejections on the member credit cards
+        *
+        * @param array $cards The cards update status submitted from the form
+        *
+        * @return bool True on success, false on error.
+        * @access protected
+        */
+       protected function updateCCards($cards)
+       {
+               if (empty($cards)) {
+                       return true;
+               }
+               foreach ($cards as $k => $v) {
+                       $orig         = $k;
+                       list($id, $k) = explode('_', $k, 2);
+                       $cards[$k]    = $v;
+                       unset($cards[$orig]);
+               }
+               try {
+                       $this->dbh->beginTransaction();
+                       //      Stmt to find the newest request in the updates table.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE id in (
+                                               SELECT max(id)
+                                                 FROM {$this->tableName}
+                                                WHERE member_id     = :member_id
+                   AND field   = :field)";
+
+                       $fetchStmt = $this->dbh->prepare($sql);
+                       $fetchStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       //      Stmt to add card to member.
+                       $sql = "
+                               INSERT INTO member_ccard_type (member_id, ccard_type_id)
+                               SELECT :member_id, ccard_type_id
+                                 FROM ccard_type
+                                WHERE ccard_type_name = :name";
+
+                       $insStmt = $this->dbh->prepare($sql);
+                       $insStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       //      Stmt to remove card from member.
+                       $sql = "
+                               DELETE FROM member_ccard_type
+                                WHERE member_id       = :member_id
+                                  AND ccard_type_id in (
+                                               SELECT ccard_type_id
+                                                 FROM ccard_type
+                                WHERE ccard_type_name = :name)";
+
+                       $delStmt = $this->dbh->prepare($sql);
+                       $delStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       //      Remove from updates table.
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                                WHERE member_id = :member_id
+                                  AND label = :name";
+
+                       $remStmt = $this->dbh->prepare($sql);
+                       $remStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       //      Loop through all the cards and see if the update was
+                       //      accepted or not.  If it was accepted, get the update
+                       //      row from the updates table and find out if the update
+                       //      was to add [update = 1] the card or remove [update = 0].
+                       //      Perform the update, and then remove the requests from the
+                       //      updates table.
+                       foreach ($cards as $card => $accepted) {
+                               if ($accepted == 'yes') {
+                                       $field = "creditCards[$card]";
+                                       $fetchStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                       $fetchStmt->execute();
+                                       $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                                       if ($row['update']) {
+                                               //      Remove the the cards from from the db to make
+                                               //      sure we don't try to insert the same card to
+                                               //      a member twice and conflict w/ the unique
+                                               //      constraint on member_id and ccard_id
+                                               $delStmt->bindParam(':name', $card, PDO::PARAM_STR);
+                                               $delStmt->execute();
+                                               //      Insert the card as a row into the db.
+                                               $insStmt->bindParam(':name', $card, PDO::PARAM_STR);
+                                               $insStmt->execute();
+                                       } else {
+                                               //      Remove the the cards from from the db.
+                                               $delStmt->bindParam(':name', $card, PDO::PARAM_STR);
+                                               $delStmt->execute();
+                                       }
+
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':name', $card, PDO::PARAM_STR);
+                                       $remStmt->execute();
+                               } else {
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':name', $card, PDO::PARAM_STR);
+                                       $remStmt->execute();
+                               }
+                       }
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ updateData()
+
+    /**
+     * Handles updating all approvals and rejections of pending updates
+     *
+     * @param array $values All elements submitted from the form
+        *
+     * @return boolean True on success, false on error
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+               //      Credit Cards are a special case and handled seperately
+               $ccardUpdates   = $values['member_ccard_type'];
+               $amenityUpdates = $values['member_amenity'];
+               $photoUpdates   = $values['member_photos'];
+               $fileUpdates    = $values['member_files'];
+               $packageUpdates = $values['member_packages'];
+               unset ($values['member_ccard_type'],
+                       $values['member_amenity'],
+                       $values['member_files'],
+                       $values['member_photos'],
+                       $values['member_packages']
+               );
+
+               foreach ($values as $k => $v) {
+                       if (!is_array($v)) {
+                               $updates[$k] = $v;
+                               unset($values[$k]);
+                       }
+               }
+               //      The values array should now hold all the submitted updates
+               //      in a grouped format and tell you if the field was approved
+               //      to be updated or not. Fields from each table will be grouped
+               //      together and any text field that "could" be changed by the
+               //      admin to fix typos or errors will be in thier own array.
+               //      These updates will have the same associative array key name
+               //      as thier corresponding field with '_update' appended.
+               //      ie. street => street_update,  url => url_update, etc..
+               //      (values example:)
+               //      Array
+               //      (
+               //              [member] => Array
+               //                      (
+               //                              [street] => yes
+               //                              [url] => no
+               //                              [description] => yes
+               //              )
+               //
+               //              [member_accommodations] => Array
+               //                      (
+               //                      [num_rooms] => yes
+               //                          [year_round] => no
+               //                      )
+               //
+               //          [member_restaurants] => Array
+               //              (
+               //                  [breakfast] => yes
+               //              )
+               //      )
+               //      (updates example:)
+               //      Array
+               //      (
+               //              [street_update] => 139 Dove Cottage Ln
+               //              [url_update] => www.google.com
+               //              [description_update] => test update 8
+               //      )
+
+               try {
+                       //      Remove from updates table.
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                                WHERE member_id = :member_id
+                                  AND field = :field
+                                  AND db_table = :db_table";
+
+                       $remStmt = $this->dbh->prepare($sql);
+                       $remStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       //      For each of the "rejected" updates, loop through
+                       //      and remove them from the arrays as well as from the
+                       //      updates DB table.
+
+                       //      Tables
+                       foreach ($values as $table => &$fields) {
+                               //      Fields
+                               //
+                               //      The field key names will come in as
+                               //      [id_fieldName] => yes
+                               //      [id_fieldName] => no
+                               //      The id # is the primary key row id number of the update
+                               //      in the updates table.
+                               //      The fieldName is the name of column that was updated.
+                               foreach ($fields as $k => &$v) {
+                                       if ($v == 'no') {
+                                               list($id, $field) = explode('_', $k, 2);
+                                               $remStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                               $remStmt->bindParam(':db_table', $table, PDO::PARAM_STR);
+                                               $remStmt->execute();
+                                               unset($fields["{$id}_{$field}"],
+                                                         $updates["{$id}_{$field}_update"]);
+                                       }
+                               }
+                               //      Do some cleanup while we're right here.
+                               //      If all the updates were rejected for a single group,
+                               //      then unset this array, that way we won't waste our time
+                               //      trying to run updates against it later.
+                               if (empty($values[$table])) {
+                                       unset($values[$table]);
+                               }
+                       }
+
+                       foreach ($values as $k => &$v) {
+                               if (!is_array($updates)) {
+                                       $updates = array();
+                               }
+                               $this->commitUpdates($k, array_keys($v), $updates);
+                       }
+                       $this->updatePackages($packageUpdates);
+                       $this->updateCCards($ccardUpdates);
+                       $this->updateAmenities($amenityUpdates);
+                       $this->updatePhotos($photoUpdates);
+                       $this->updateFiles($fileUpdates);
+            // remove cache file for profile page
+            $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+            $cache->remove(
+                "Member-{$this->_mid}",
+                'Profile'
+            );
+            // for the stream send
+            if (   defined('MEMBER_STREAMSEND_API')
+                && MEMBER_STREAMSEND_API) {
+                // send member to streamsend
+                $memberStreamSend = new Toolkit_Members_StreamSend($this->dbh);
+                $memberStreamSend->sendMemberById($this->_mid);
+            }
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+               return true;
+       }
+
+       //      }}}
+       //      {{{ updateFiles()
+
+       /**
+        * Handle updating any approvals or rejections on the member files
+        *
+        * @param array $files an array of file updates and their update status
+        *
+        * @return bool True on success, false on error.
+        * @access protected
+        */
+       protected function updateFiles($files)
+       {
+               if (empty($files)) {
+                       return true;
+               }
+               try {
+                       $this->dbh->beginTransaction();
+                       //      Stmt to find the newest request in the updates table for
+                       //      a specific field.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE id = :id";
+
+                       $fetchStmt = $this->dbh->prepare($sql);
+                       //      Stmt to update the file
+                       $updateSql = "
+                UPDATE member_files
+                   SET %s = :update
+                 WHERE id      = :id";
+                       //      Stmt to remove file from member.
+                       $sql = "
+                DELETE FROM member_files
+                 WHERE id   = :id";
+
+                       $delStmt = $this->dbh->prepare($sql);
+                       //      Stmt to remove any file name updates for a file that
+                       //      are still in the updates table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE field        = 'file_name'
+                   AND foreign_key  = :id";
+
+                       $delFileNameStmt = $this->dbh->prepare($sql);
+                       //      Remove from updates table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE field        = :field
+                   AND foreign_key  = :id";
+
+                       $remStmt = $this->dbh->prepare($sql);
+                       //      Loop through all the files and see if the update was
+                       //      accepted or not.  If it was accepted, get the update
+                       //      row from the updates table and find out if the update
+                       //      was to add [update = 1] the card or remove [update = 0].
+                       //      Perform the update, and then remove the requests from the
+                       //      updates table.
+                       foreach ($files as $field => $accepted) {
+                               list($id, $field) = explode('_', $field, 2);
+                               $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                               $fetchStmt->execute();
+                               $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                               if ($accepted == 'yes') {
+                                       $updtStmt = $this->dbh->prepare(sprintf($updateSql, $field));
+                                       //      we are dealing w/ the file_name
+                                       //      update the files name.
+                                       $updtStmt->bindParam(':update', $row['update'], PDO::PARAM_STR);
+                                       $updtStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $updtStmt->execute();
+
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                       $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $remStmt->execute();
+                               } else {
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                       $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $remStmt->execute();
+
+                                       //      a rejected file (we know its a file because it
+                                       //      has a data_type of boolean) means we have to not only
+                                       //      remove the row from the updates table, but also
+                                       //      from the member_files table.
+                                       if ($row['data_type'] == 'boolean') {
+                                               $delFileNameStmt->bindParam(
+                            ':id',
+                            $row['foreign_key'],
+                            PDO::PARAM_STR
+                        );
+                                               $delFileNameStmt->execute();
+
+                                               //      Remove the the cards from from the db.
+                                               $delStmt->bindParam(
+                            ':id',
+                            $row['foreign_key'],
+                            PDO::PARAM_INT
+                        );
+                                               $delStmt->execute();
+                                       }
+                               }
+                       }
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ updatePackages()
+
+       /**
+        * Handle updating any approvals or rejections on the member packages
+        *
+        * @param array $packages an array of package updates and their update status
+        *
+        * @return bool True on success, false on error.
+        * @access protected
+        */
+       protected function updatePackages($packages)
+       {
+               if (empty($packages)) {
+                       return true;
+               }
+               try {
+                       $this->dbh->beginTransaction();
+                       //      Stmt to find the newest request in the updates table for
+                       //      a specific field.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE id = :id";
+
+                       $fetchStmt = $this->dbh->prepare($sql);
+                       //      Stmt to update the package
+                       $updateSql = "
+                UPDATE member_packages
+                   SET %s = :update
+                 WHERE id      = :id";
+                       //      Stmt to remove any updates for a package that
+                       //      are still in the updates table.
+                       //      Remove from updates table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE foreign_key  = :id
+                   AND field        = :field
+                                  AND db_table = 'member_packages'";
+
+                       $remStmt = $this->dbh->prepare($sql);
+                       //      Loop through all the package field and see if the update was
+                       //      accepted or not.  If it was accepted, get the update
+                       //      row from the updates table and find out if the update
+                       //      was to add [update = 1] the card or remove [update = 0].
+                       //      Perform the update, and then remove the requests from the
+                       //      updates table.
+$values = $this->getSubmitValues();
+$checkToResetPending = array();
+                       foreach ($packages as $field => $accepted) {
+                               list($id, $field) = explode('_', $field, 2);
+                               $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                               $fetchStmt->execute();
+                               $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                               if ($accepted == 'yes') {
+$sql = "
+       select foreign_key
+       from member_updates
+       where id = :id";
+$stmt = $this->dbh->prepare($sql);
+$stmt->bindParam(':id', $id, PDO::PARAM_INT);
+$stmt->execute();
+$row = $stmt->fetch(PDO::FETCH_ASSOC);
+$checkToResetPending[] = $row['foreign_key'];
+                                       $updtStmt = $this->dbh->prepare(sprintf($updateSql, $field));
+                                       $update   = $this->getSubmitValue("{$id}_{$field}_update");
+                                       if (empty($update)) {
+                                               $update = $row['update'];
+                                       }
+                                       $updtStmt->bindParam(':update', $update, PDO::PARAM_STR);
+                                       $updtStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $updtStmt->execute();
+
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                       $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $remStmt->execute();
+                               } else {
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                       $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $remStmt->execute();
+                               }
+                       }
+
+$checkToResetPending = array_unique($checkToResetPending);
+$sql = "
+       SELECT count(*) as total
+         from member_updates
+        where db_table = 'member_packages'
+          and member_id = :mid
+          and foreign_key = :fk";
+$stmt = $this->dbh->prepare($sql);
+$stmt->bindParam(':mid', $_GET['id'], PDO::PARAM_INT);
+if (is_array($checkToResetPending) && !empty($checkToResetPending)) {
+       foreach ($checkToResetPending as $i) {
+               $stmt->bindParam(':fk', $i, PDO::PARAM_INT);
+               $stmt->execute();
+
+               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+               if ($row['total'] == 0) {
+                       $sql = "
+                               update member_packages
+                               set pending = false
+                               where member_id = :mid
+                               and id = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':id', $i, PDO::PARAM_INT);
+                       $stmt->execute();
+               }
+       }
+}
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ updatePhotos()
+
+       /**
+        * Handle updating any approvals or rejections on the member photos
+        *
+        * @param array $photos an array of photo updates and thier update status
+        *
+        * @return bool True on success, false on error.
+        * @access protected
+        */
+       protected function updatePhotos($photos)
+       {
+               if (empty($photos)) {
+                       return true;
+               }
+               try {
+                       $this->dbh->beginTransaction();
+                       //      Stmt to find the newest request in the updates table for
+                       //      a specific field.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE id = :id";
+
+                       $fetchStmt = $this->dbh->prepare($sql);
+                       //      Stmt to update the photo
+                       $updateSql = "
+                UPDATE member_photos
+                   SET %s = :update
+                 WHERE id      = :id";
+                       //      Stmt to remove photo from member.
+                       $sql = "
+                DELETE FROM member_photos
+                 WHERE id = :id";
+
+                       $delStmt = $this->dbh->prepare($sql);
+                       //      Stmt to remove any caption updates for a photo that
+                       //      are still in the updates table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE field = 'caption'
+                   AND foreign_key  = :id";
+
+                       $delPhotoCaptionStmt = $this->dbh->prepare($sql);
+                       //      Remove from updates table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE foreign_key  = :id
+                   AND field        = :field";
+
+                       $remStmt = $this->dbh->prepare($sql);
+                       //      Loop through all the photos and see if the update was
+                       //      accepted or not.  If it was accepted, get the update
+                       //      row from the updates table and find out if the update
+                       //      was to add [update = 1] the card or remove [update = 0].
+                       //      Perform the update, and then remove the requests from the
+                       //      updates table.
+                       foreach ($photos as $field => $accepted) {
+                               list($id, $field) = explode('_', $field, 2);
+                               $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                               $fetchStmt->execute();
+                               $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                               if ($accepted == 'yes') {
+                                       $updtStmt = $this->dbh->prepare(sprintf($updateSql, $field));
+                                       //      we are dealing w/ the caption
+                                       //      update the photos caption.
+                                       $updtStmt->bindParam(':update', $row['update'], PDO::PARAM_STR);
+                                       $updtStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $updtStmt->execute();
+
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                       $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $remStmt->execute();
+                               } else {
+                                       //      Remove field from the member_updates table.
+                                       $remStmt->bindParam(':field', $field, PDO::PARAM_STR);
+                                       $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT);
+                                       $remStmt->execute();
+
+                                       //      a rejected photo (we know its a photo because it
+                                       //      has a data_type of boolean) means we have to not only
+                                       //      remove the row from the updates table, but also
+                                       //      from the member_photos table.
+                                       if ($row['data_type'] == 'boolean') {
+                                               $delPhotoCaptionStmt->bindParam(
+                            ':id',
+                            $row['foreign_key'],
+                            PDO::PARAM_STR
+                        );
+                                               $delPhotoCaptionStmt->execute();
+
+                                               //      Remove the the cards from from the db.
+                                               $delStmt->bindParam(
+                            ':id',
+                            $row['foreign_key'],
+                            PDO::PARAM_INT
+                        );
+                                               $delStmt->execute();
+                                       }
+                               }
+                       }
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ validated()
+
+       /**
+        * Checks if the form is validated
+        *
+        * If the form is validated display the success msg.
+        * If the form is submitted but not validated, display
+        * the error msg.  Other wise display nothing.
+        *
+        * This function is called from within the template.
+        *
+        * @return string The success or error msg for the user.
+        * @access protected
+        */
+       public function validated()
+       {
+               if ($this->validated) {
+                       return $this->successMsg;
+               } elseif ($this->isSubmitted()) {
+                       return $this->errorMsg;
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/Auxiliary.php b/Toolkit/Members/Admin/Auxiliary.php
new file mode 100644 (file)
index 0000000..92636c1
--- /dev/null
@@ -0,0 +1,512 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: Auxiliary.php,v 1.13 2010/01/26 19:39:07 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Base class used for building forms to accompany the members database
+ *
+ * This class handles all common functions that are to be used in
+ * the auxiliary forms used to assist in the members DB.
+ * (categories, amenities, regions, etc...).
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ * @see       Toolkit_Members, member_admin
+ */
+abstract class Toolkit_Members_Admin_Auxiliary extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * Primary table used for database calls
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName;
+
+       /**
+        * Array of primary table meta data
+        *
+        * This array will hold the column data types for the fields
+        * that will be manipulated in the database.
+        *
+        * @var array
+        * @access public
+        * @see Toolkit_Common::getTableMetaData()
+        */
+       public $tableMetaData;
+
+       /**
+        * The name of the template used for the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate;
+
+       /**
+        * The object to use inside the form
+        *
+        * This object which is to be populated by the $this object
+        * is used inside the templates and allows access back into the
+        * calling class to call publicly available functions
+        *
+        * @var string
+        * @access protected
+        */
+       protected $view;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @access public
+        */
+       public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+               $this->registeredRules = array();
+
+               $this->configureElements();
+               $this->configureRules();
+               $this->configureFilters();
+               $this->configureDefaults();
+
+               $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ baseUrl()
+
+       /**
+        * Returns the BASE_URL
+        *
+        * This function is used inside the Flexy Templated forms
+        *
+        * @return string BASE_URL
+        * @access public
+        */
+       public function baseUrl()
+       {
+               return BASE_URL;
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Configure the default values for the form
+        *
+        * Since each form is different, you will need to redefine this
+        * method inside of each subclass and create your own rules
+        * based on your forms elements.
+        *
+     * @return void
+        * @access public
+        */
+       abstract protected function configureDefaults();
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Configures all form elements
+        *
+        * If you are subclassing this base class out, you will need to define
+        * all your forms elements in your new subclass.
+        *
+     * @return void
+        * @access protected
+        */
+       abstract protected function configureElements();
+
+       //      }}}
+       //      {{{ configureFilters()
+
+       /**
+        * Defines all filters used on form elements when submitted
+        *
+        * Most times this function won't need to be overridden.
+        *
+     * @return void
+        * @access public
+        */
+       protected function configureFilters()
+       {
+               $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+
+               $this->setupFilters($filters);
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up the required / not-required rules for forms
+        *
+        * At the bare minimum, the required / not-required rules for form
+        * needs to be defined.  Since these rules are most easily defined
+        * while creating the element definitions themselves the base function
+        * is to call the setupRules function that will instantiate these
+        * rules in the quickform class.
+        *
+     * @return void
+        * @access public
+        */
+       protected function configureRules()
+       {
+               $this->setupRules();
+       }
+
+       //      }}}
+
+       //      {{{ getSetParameters()
+
+       /**
+     * get a string of sql query parameters
+     *
+     * @param array $values parameters to include
+     *
+     * @return string sql query parameters
+        * @access protected
+        */
+       protected function getSetParameters($values)
+       {
+               $params = array_keys($values);
+               $length = count($params);
+               for ($i = 0; $i < $length; ++$i) {
+                       $bindParams .= "{$params[$i]} = :{$params[$i]}";
+            if ($i < ($length - 1)) {
+                $bindParams .= ', ';
+            }
+               }
+               return $bindParams;
+       }
+
+       //      }}}
+       //      {{{ getDataType()
+
+       /**
+     * gets the datatype of the element
+     *
+     * @param string $k name of element
+     *
+     * @return string datatype
+        * @access protected
+        */
+       protected function getDataType($k)
+       {
+               $metaData = $this->tableMetaData[$k];
+               if ($metaData == 'integer') {
+                       return PDO::PARAM_INT;
+               } else if ($metaData == 'boolean') {
+                       return PDO::PARAM_BOOL;
+               } elseif ($metaData == 'double precision') {
+                       return null;
+               } else {
+                       return PDO::PARAM_STR;
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+       /**
+     * insert the data in the DB
+     *
+     * @param array  $values Submitted form values
+     * @param string $sql    Query to execute to make update
+     *
+     * @return void
+        * @access protected
+        */
+       protected function insertData($values, $sql)
+       {
+               try {
+                       $stmt = $this->dbh->prepare($sql);
+                       foreach ($values as $k => $v) {
+                               $dataType = $this->getDataType($k);
+                               $stmt->bindParam(":$k", $values[$k], $dataType);
+                       }
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ isEdit()
+
+       /**
+        * Determines if we are editing an object or not
+        *
+        * If we are ever editing an object, member, category, city, etc...
+        * There will be the objects DB ID passed along in the url under the
+        * id key.  If we can find this then we know we're editing, if not
+        * then we are adding.
+        *
+     * @return void
+        * @access public
+        */
+       public function isEdit()
+       {
+               return isset($_GET['id']);
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return array Return description (if any) ...
+     * @access protected
+     */
+       protected function processData($values)
+       {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       case 'uploaded_file_rmv' :
+                               //      Don't remove this from the values array.
+                               //      we will handle it later.
+                               //      we need to have access to this value
+                               //      in the insert/update functions.
+                               break;
+
+                       case 'MAX_FILE_SIZE' :
+                               unset($values[$k]);
+                               break;
+
+                       default :
+                               if (preg_match('/^.+_rmv$/', $k)) {
+                                       unset($values[$k]);
+                               }
+                               break;
+                       }
+               }
+
+               if (isset($_GET['id'])) {
+                       return $this->updateData($values);
+               } else {
+                       return $this->insertData($values);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ setupElements()
+
+       /**
+        * Add the form elements defined in your class to a QuickForm
+        *
+        * Handles adding singleton elements as well as grouped elements.
+        * If added elements fail to correctly add to the form, the script
+        * should die gracefully, telling the user there was a problem.
+        *
+     * @param array $elements form element definitions
+     *
+        * @throws HTML_QuickForm_Error error raised from QuickForm class.
+     * @return void
+        * @access protected
+        */
+       protected function setupElements($elements)
+       {
+               $this->formElements = $elements;
+               foreach ($elements as $e) {
+                       if ($e['type'] != 'group') {
+                               try {
+                                       $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
+                               } catch (HTML_QuickForm_Error $e) {
+                                       Toolkit_Common::dieGracefully(null, $e);
+                               }
+                               if ($e['type'] == 'advmultiselect') {
+                                       $source->setLabel($e['labels']);
+                               }
+                               if ($e['name'] == 'categories') {
+                                       $res = $source->loadArray($this->categories);
+                                       if (PEAR::isError($res)) {
+                                               Toolkit_Common::dieGracefully(null, $res);
+                                       }
+                               }
+                               if ($e['type'] == 'header') {
+                                       $this->formHeaders[$e['display']] = $e;
+                               }
+                       } elseif (is_array($e['group'])) {
+                               unset($field);
+                               foreach ($e['group'] as $g) {
+                                       $field[] =& HTML_QuickForm::createElement($g['type'], $g['name'], $g['display'], $g['opts'], $g['att'], $g['val']);
+                               }
+                               $source =& $this->addGroup($field, $e['name'], $e['label'], $e['seperator'], $e['appendName']);
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ setupRenderers()
+
+       /**
+     * Sets up the rendering engine for the form
+     *
+     * @return void
+        * @access protected
+        */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+               $this->view->form = $renderer->toObject();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+       //      {{{ toHTML()
+
+       /**
+        * Renders the form for viewing
+        *
+        * This function validates the form if needed, and if it successfully
+        * validates attempts to insert or update the data record.
+        * If it is unsuccessful, it will return an error to the user
+        * informing them of what went wrong.
+        *
+        * @param string $listPage The page the header should redirect
+        *                                                 to on successful insert or update.
+     *
+        * @return string The compiled and filled form template.
+        * @access public
+        */
+       public function toHTML($listPage = 'index.php')
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+               $this->setupRenderers();
+
+               if ($this->validated) {
+                       $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+                       if ($processed) {
+                               header("Location: $listPage");
+                       } else {
+                               $errorMsg = "There was an unexpected error. Please try again later.";
+                       }
+               }
+
+               return $errorMsg . $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+       /**
+     * update the data in the DB
+     *
+     * @param array  $values Submitted form values
+     * @param string $sql    Query to execute to make update
+     *
+     * @return boolean result of query
+        * @access protected
+        */
+       protected function updateData($values, $sql)
+       {
+               try {
+                       $stmt = $this->dbh->prepare($sql);
+                       foreach ($values as $k => &$v) {
+                               $dataType = $this->getDataType($k);
+                               $stmt->bindParam(":$k", $v, $dataType);
+                       }
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ validated()
+
+       /**
+        * Returns form message from validation attempts
+        *
+     * @return string validation message
+        * @access public
+        */
+       public function validated()
+       {
+               if ($this->validated) {
+                       return $this->successMsg;
+               } elseif ($this->isSubmitted()) {
+                       return $this->errorMsg;
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/BasicSearch.php b/Toolkit/Members/Admin/BasicSearch.php
new file mode 100644 (file)
index 0000000..4766459
--- /dev/null
@@ -0,0 +1,343 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Admin search functionality for memberdb
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: BasicSearch.php,v 1.6 2010/05/25 14:01:20 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form to search the members database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_BasicSearch
+    extends Toolkit_FormBuilder implements Toolkit_Form
+{
+       //      {{{ configureConstants()
+
+    /**
+     * Form constant definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+               $c = array(
+                       'page' => 'members',
+                       'module' => 'listMembers',
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+        * @param PDO                      $dbh Databse handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements(PDO $dbh, Config_Container $c)
+       {
+        $e = array();
+
+        //  get reference to [listing type] section of config file
+        $config =& $c->getItem('section', 'listing type');
+        //  get coupon
+        $singularDirective =& $config->getItem('directive', 'singular');
+        $singularType = $singularDirective->getContent();
+        $pluralDirective =& $config->getItem('directive', 'plural');
+        $pluralType = $pluralDirective->getContent();
+
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'page'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'module'
+        );
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'recordInfoHdr',
+            'display' => "Search for $pluralType",
+        );
+               $e[] = array(
+            'type' => 'selectglm',
+            'req' => false,
+            'name' => 'category',
+            'display' => 'Category',
+            'opts' => $this->_getCategories($dbh),
+                       'att' => array(
+                               'multiple' => 'multiple',
+                               'size' => 6
+                       )
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'name',
+            'display' => "$singularType Name"
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'email',
+            'display' => "$singularType Email"
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Search'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+        * @param PDO                      $dbh Databse handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(PDO $dbh, Config_Container $c)
+    {
+        $this->configureElements($dbh, $c);
+        $this->configureRules();
+        $this->configureFilters();
+        $this->configureConstants();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+               $r[] = array(
+            'element' => 'member_contact_email',
+            'message' => 'ERROR: Invalid Email Address!',
+            'type' => 'email',
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     _getCategories()
+
+    /**
+     * get all the categories available in alpha order
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array alpha order of categories available in the DB
+     * @access private
+     */
+       private function _getCategories(PDO $dbh)
+       {
+               $categories = Toolkit_Common::getHierarchicalTreeStructure(
+                       $dbh,
+            'category',
+            'category_id',
+            'parent_id',
+                       'name'
+        );
+               //  Get only the active categories from
+               //  the nav structure for our select list.
+               $sql = "
+                       SELECT category_id, name
+                         FROM category
+                        WHERE category_id = :id";
+
+               $stmt = $dbh->prepare($sql);
+
+               foreach ($categories as $k => $v) {
+                       unset($row, $category);
+                       $stmt->bindParam(':id', $k, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       //  If we actually retrieved a row, add it to the select list
+                       //  after we clean it up.
+                       if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $pages[$k] = array(
+                                       'level' => $v - 1,
+                                       'name' => $row['name']
+                               );
+                       }
+               }
+
+               return $pages;
+       }
+
+       //      }}}
+       //      {{{ getCities()
+
+       /**
+        * Configure the cities for member stored in the database into an array
+        *
+     * @return array the cities
+        * @access protected
+        */
+       protected function getCities()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM city
+                                ORDER BY city_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $cities[$row['city_id']] = $row['city_name'];
+                       }
+                       if (!empty($cities)) {
+                               $cities = array('' => '-- Select --') + $cities;
+                       } else {
+                               $cities = array('' => '-- No Cities Created Yet -- ');
+                       }
+                       return $cities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     _getStates()
+
+    /**
+     * get all the statis available in alpha order
+     *
+     * @return array alpha order of states available in the DB
+     * @access private
+     */
+       private function _getStates()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM state
+                 ORDER BY state_name";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute();
+                       $stmt->bindColumn('state_id', $cid);
+                       $stmt->bindColumn('state_name', $name);
+
+                       $states = array('' => '-- Select --');
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $states[$cid] = $name;
+                       }
+
+                       return $states;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $tpl = '<tr align="center"><td colspan="2">{element}</td></tr>';
+               $renderer->setElementTemplate($tpl, 'submit');
+       }
+
+    //  @codeCoverageIgnoreEnd
+       //      }}}
+
+       //      {{{     toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+        * @access protected
+        * @return string $output The Form to be rendered or success msg.
+        */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       $output = parent::toHTML();
+               } elseif ($this->isSubmitted()) {
+                       $output = $this->errorMsg;
+                       $output .= parent::toHTML();
+               } else {
+                       $output = parent::toHTML();
+               }
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/BillingController.php b/Toolkit/Members/Admin/BillingController.php
new file mode 100644 (file)
index 0000000..2310fd7
--- /dev/null
@@ -0,0 +1,105 @@
+<?php
+/**
+ * BillingController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_BillingController
+ * 
+ * Description of Toolkit_Members_Admin_BillingController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+
+class Toolkit_Members_Admin_BillingController
+       extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+    /**
+     * Description of getPageLayout()
+     * 
+     * @param string $html HTML string
+     * 
+     * @return string
+     * @access protected 
+     */
+    protected function getPageLayout($html)
+    {
+        $GLOBALS['styleSheets'][]
+            = BASE_URL . 'Toolkit/Members/Billing/billing.css';
+        $this->registry->controllerObject->content = $html;
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+    }
+    
+    /**
+     * Description of indexAction()
+     * 
+     * @return string
+     * @access public 
+     */
+       public function indexAction()
+       {
+        $paymentTypes = new Toolkit_Members_Billing_ListPaymentTypes(
+            Toolkit_Database::getInstance(),
+            50,
+            null,
+            null
+        );
+        $html = $paymentTypes->toHTML();
+               return $this->getPageLayout($html);
+       }
+    
+    /**
+     * Description of editPaymentTypeAction()
+     * 
+     * @return string
+     * @access public
+     */
+    public function editPaymentTypeAction()
+    {
+        $form = new Toolkit_Members_Billing_EditPaymentType(
+            Toolkit_Database::getInstance(),
+            'edit-payment-type'
+        );
+        $form->configureForm();
+        $html = $form->toHtml();
+        return $this->getPageLayout($html);
+    }
+
+    /**
+     * Description of paymentTypeAction
+     * 
+     * @return string
+     * @accesspublic
+     */
+    public function paymentTypeAction()
+    {
+        return $this->indexAction();
+    }
+    
+}
diff --git a/Toolkit/Members/Admin/CategoriesController.php b/Toolkit/Members/Admin/CategoriesController.php
new file mode 100644 (file)
index 0000000..148f6a0
--- /dev/null
@@ -0,0 +1,118 @@
+<?php
+/**
+ * CategoriesController.php
+ * 
+ * PHP versions 4 and 5
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Newsletters.php,v 1.9 2009/09/16 19:00:58 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+
+/**
+ * Toolkit_Members_Admin_CategoriesController
+ * 
+ * Description of Toolkit_Members_Admin_CategoriesController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_CategoriesController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    /**
+     * Main action for controller. Runs admin template, list out all regions
+     * 
+     * @return string
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $GLOBALS['bottomScripts'][]
+                       = GLM_APP_BASE_URL . 'libjs/jsTree/libjs/css.js';
+               $GLOBALS['bottomScripts'][]
+                       = GLM_APP_BASE_URL . 'libjs/jquery.listen.js';
+               $GLOBALS['bottomScripts'][]
+                       = GLM_APP_BASE_URL . 'libjs/jsTree/source/tree_component.js';
+               $GLOBALS['bottomScripts'][]
+                       = GLM_APP_BASE_URL . 'libjs/jquery.cookie.js';
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/list-categories.js';
+               $GLOBALS['styleSheets'][]
+                       = GLM_APP_BASE_URL . 'libjs/jsTree/source/tree_component.css';
+
+               $categoryList = new Toolkit_Members_Admin_ListCategories($this->registry->dbh);
+               $this->registry->controllerObject->content = $categoryList->renderCategories();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     editCategoryAction()
+    /**
+     * Description of editCategoryAction()
+     * 
+     * @return string
+     * @access public 
+     */
+       public function editCategoryAction()
+       {
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/edit-category.js';
+
+               $form = new Toolkit_Members_Admin_EditCategory(
+            $this->registry->dbh,
+            'edit_category'
+        );
+        $form->configureForm();
+               $this->registry->controllerObject->content = $form->toHtml();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     listCategoriesAction()
+    /**
+     * Description of listCategoriesAction()
+     * 
+     * @return array
+     * @access public 
+     */
+       public function listCategoriesAction()
+       {
+               return $this->indexAction();
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/CitiesController.php b/Toolkit/Members/Admin/CitiesController.php
new file mode 100644 (file)
index 0000000..53592dd
--- /dev/null
@@ -0,0 +1,109 @@
+<?php
+/**
+ * CitiesController.php
+ * 
+ * PHP versions 4 and 5
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Newsletters.php,v 1.9 2009/09/16 19:00:58 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Admin_CitiesController
+ * 
+ * Description for Toolkit_Members_Admin_CitiesController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      http://demo.gaslightmedia.com
+ */
+
+class Toolkit_Members_Admin_CitiesController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    
+    /**
+     * Main action for controller. Runs admin template, list out all regions
+     * 
+     * @return string
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $cityList = new Toolkit_Members_Admin_ListCities($this->registry->dbh);
+               $this->registry->controllerObject->content = $cityList->renderCities();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     editCityAction()
+    /**
+     * Description of editCityAction()
+     * 
+     * @return string
+     * @access public 
+     */
+       public function editCityAction()
+       {
+               $GLOBALS['bottomScripts'][]
+                       = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/edit-city.js';
+
+               $form = new Toolkit_Members_Admin_EditCity(
+            $this->registry->dbh,
+            'edit_city'
+        );
+        $form->setImageServer(new Toolkit_Image_Server());
+        $form->configureForm($this->registry->config);
+               $this->registry->controllerObject->content = $form->toHtml();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     listCitiesAction()
+    /**
+     * Description of listCitiesAction()
+     * 
+     * @return array
+     * @access public 
+     */
+       public function listCitiesAction()
+       {
+               return $this->indexAction();
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/CountiesController.php b/Toolkit/Members/Admin/CountiesController.php
new file mode 100644 (file)
index 0000000..719c225
--- /dev/null
@@ -0,0 +1,103 @@
+<?php
+/**
+ * CountiesController.php
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Newsletters.php,v 1.9 2009/09/16 19:00:58 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Admin_CountiesController
+ *
+ * Description for Toolkit_Members_Admin_CountiesController
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_CountiesController
+       extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    /**
+     * Main action for controller. Runs admin template, list out all regions
+     *
+     * @return string
+     * @access public
+     */
+       public function indexAction()
+       {
+               $countyList = new Toolkit_Members_Admin_ListCounties($this->registry->dbh);
+               $this->registry->controllerObject->content = $countyList->renderCounties();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     editCountyAction()
+    /**
+     * Description for editCountyAction()
+     *
+     * @return string
+     * @access public
+     */
+       public function editCountyAction()
+       {
+        $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/edit-county.js';
+               $form = new Toolkit_Members_Admin_EditCounty(
+            $this->dbh,
+            'edit_county'
+        );
+        $form->configureForm($this->registry->dbh, $this->registry->config);
+               $this->registry->controllerObject->content = $form->toHtml();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     listCountiesAction()
+    /**
+     * Description for listCountiesAction()
+     *
+     * @return array
+     * @access public
+     */
+       public function listCountiesAction()
+       {
+               return $this->indexAction();
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/EditAmenity.php b/Toolkit/Members/Admin/EditAmenity.php
new file mode 100644 (file)
index 0000000..c5391a3
--- /dev/null
@@ -0,0 +1,365 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Controls Amenity definitions for the member db
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditAmenity.php,v 1.10 2010/08/09 17:58:32 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handles creating / editing amenities that the members will use
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_EditAmenity
+    extends Toolkit_Members_Auxiliary implements Toolkit_Form
+{
+       //      {{{     properties
+
+    /**
+     * Description for public
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'amenity';
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+       protected $formTemplate = 'editAmenity.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+       //      {{{ checkAmenityName()
+
+    /**
+     * Check that the amenity name is not in use already
+     *
+     * @param string $name name to check
+     *
+     * @return boolean if the name is valid or not
+     * @access public
+     */
+       public function checkAmenityName($name)
+       {
+               try {
+                       //      If we're editing a amenity, they
+                       //      can save that amenity as its
+                       //      own name. so don't include that
+                       //      amenity in the check.
+                       if (isset($_GET['id'])) {
+                               $and = "AND amenity_id <> :id";
+                       }
+                       $sql = "
+                SELECT count(*) AS total
+                  FROM {$this->tableName}
+                 WHERE amenity_name = :name
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':name', $name, PDO::PARAM_STR);
+                       if (isset($_GET['id'])) {
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $total);
+                       $stmt->fetch();
+
+                       return !(bool) $total;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+    /**
+     * Set up the default values for the form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+        $d = array();
+
+               if ($amenityId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM {$this->tableName}
+                                        WHERE amenity_id = :id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':id', $amenityId, PDO::PARAM_INT);
+                               $stmt->execute();
+                               $d = $stmt->fetch();
+                       } catch (PDOException $e) {
+                               $this->handleError($e);
+                       }
+               }
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements()
+       {
+               $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.
+               //      This includes group element definitions.
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'AmenityInfoHdr',
+                       'display' => 'Member Amenities'
+               );
+               $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'display_form',
+                       'display' => 'Display on Form',
+                       'val'     => array(0, 1)
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'amenity_name',
+                       'display' => 'Amenity Name'
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+
+               $r[] = array(
+            'element' => 'amenity_name',
+            'message' => 'ERROR: Amenity already exists!',
+            'type' => 'callback',
+            'format' => array($this, 'checkAmenityName'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ deleteAmenity()
+
+    /**
+     * Remove a region from the db
+     *
+     * @param integer $id region id
+     *
+     * @return boolean result of db query
+     * @access protected
+     */
+       protected function deleteAmenity($id)
+       {
+        if (!is_numeric($id)) {
+            return false;
+        }
+               try {
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                                WHERE amenity_id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Create a new amenity
+     *
+     * @param array $values Submitted form values
+     *
+     * @return boolean Result of insertion into DB
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $sql = Toolkit_Common::createSQLInsert(
+            $this->tableName,
+            array_keys($values)
+        );
+        try {
+                       $stmt = Toolkit_Common::prepareQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+
+            return $stmt->execute();
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the data for an amenity
+     *
+     * @param array $values submitted form results
+     *
+     * @return boolean result of sql update query
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+               if ($amenityId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       //      We aren't updating a region, we're deleting it.
+                       if (array_key_exists('delete', $values)) {
+                               return $this->deleteAmenity($amenityId);
+                       }
+
+                       $sql = Toolkit_Common::createSQLUpdate(
+                               $this->tableName,
+                               array_keys($values),
+                               array('amenity_id = :id')
+                       );
+
+                       $values['id'] = $amenityId;
+                       try {
+                               $stmt = Toolkit_Common::prepareQuery(
+                                       $this->dbh,
+                                       $this->tableName,
+                                       $sql,
+                                       $values
+                               );
+                               return $stmt->execute();
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{ toHTML()
+
+       /**
+        * Renders the form for viewing
+        *
+        * This function validates the form if needed, and if it successfully
+        * validates attempts to insert or update the data record.
+        * If it is unsuccessful, it will return an error to the user
+        * informing them of what went wrong.
+        *
+        * @return string The compiled and filled form template.
+        * @access public
+        */
+       public function toHtml()
+       {
+               $listPage = BASE_URL . 'admin/members.php?rt=Amenities&ac=listAmenities';
+               return parent::toHtml($listPage);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/EditCategory.php b/Toolkit/Members/Admin/EditCategory.php
new file mode 100644 (file)
index 0000000..0bc851f
--- /dev/null
@@ -0,0 +1,531 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditCategory.php,v 1.14 2010/07/14 23:27:59 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Edit categories used within the member database
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the member categories.  Handles both adding / editing category
+ * details, including:
+ *
+ * 1. Modules associated with a category.
+ * 2. Updating sub-categories to mirror parent category module settings.
+ * 3. Removal of top level categories that contain sub-level categories.
+ *             see (deleteCategory())
+ *
+ * Once categories are added, they are not allow to be moved to another parent.
+ * This keeps the updating to a minimum and elminates logic that would be
+ * caused by this move: (maintaining category-module settings after the move).
+ *
+ * @category  MembersDB
+ * @package      Toolkit_Members
+ * @author       Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ * @see                  Toolkit_Members, member_admin
+ */
+
+class Toolkit_Members_Admin_EditCategory
+    extends Toolkit_Members_Auxiliary implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data of the categories
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'category';
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editCategory.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               if ($categoryId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE category_id = :cid";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':cid', $categoryId, PDO::PARAM_INT);
+                               $stmt->execute();
+                               $category = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $defaults = array(
+                                       'category_id'           => $category['category_id'],
+                                       'name'                          => $category['name'],
+                                       'parent_id'                     => $category['parent_id'],
+                                       'accommodations'        => $category['accommodations'],
+                                       'restaurant'            => $category['restaurant'],
+                                       'golf'                          => $category['golf'],
+                               );
+                       } catch (PDOException $e) {
+                               $this->handleError($e);
+                       }
+               }
+
+               $this->setupDefaults($defaults);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * Categories are populated into the protected class property $categories.
+        * These categories are used to populate the select list of categories.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+        $e = array();
+
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'categoryInfoHdr',
+            'display' => 'Member Categories'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'name',
+            'display' => 'Category Name'
+        );
+               $e[] = array(
+            'type' => 'select',
+            'req' => false,
+            'name' => 'parent_id',
+            'display' => 'Parent',
+            'opts' => array(0 => 'No Parent (top level)'),
+            'att' => array('id' => 'categories')
+        );
+//             $e[] = array(
+//            'type' => 'advcheckbox',
+//            'req' => false,
+//            'name' => 'accommodations',
+//            'display' => 'Is Accommodation Category',
+//            'val' => array(0, 1)
+//        );
+//             $e[] = array(
+//            'type' => 'advcheckbox',
+//            'req' => false,
+//            'name' => 'restaurant',
+//            'display' => 'Is Restaurant Category',
+//            'val' => array(0, 1)
+//        );
+//             $e[] = array(
+//            'type' => 'advcheckbox',
+//            'req' => false,
+//            'name' => 'golf',
+//            'display' => 'Is Golfing Category',
+//            'val' => array(0, 1)
+//        );
+
+               $this->setupElements($e);
+        $this->loadMemberCategories();
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureDefaults();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ deleteCategory()
+
+       /**
+        * Removes a category from the database
+        *
+        * All first level sub-categories will become main level categories
+        * and will hold the structure of any sub-categories beneath them.
+        *
+        * @param int $id The category_id of the category you wish to remove.
+        *
+        * @return bool False on SQL error, otherwise true.
+        * @access protected
+        */
+       protected function deleteCategory($id)
+       {
+        if (!is_numeric($id)) {
+            return false;
+        }
+
+               try {
+                       $sql = "
+                UPDATE {$this->tableName}
+                   SET parent_id   = 0
+                 WHERE parent_id   = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+
+            if (   defined('MEMBER_STREAMSEND_API')
+                && MEMBER_STREAMSEND_API) {
+                // send member to streamsend
+                $memberStreamSend = new Toolkit_Members_StreamSend($this->dbh);
+                $memberStreamSend->updateOptionByCategoryId($id);
+            }
+
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                 WHERE category_id = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Create a new category
+     *
+     * @param array $values Submitted form values
+     *
+     * @return boolean Result of insertion into DB
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $sql = Toolkit_Common::createSQLInsert(
+            $this->tableName,
+            array_keys($values)
+        );
+        try {
+            $stmt = Toolkit_Common::prepareQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+            $ret = $stmt->execute();
+            $categoryId = $this->dbh->lastInsertId('category_category_id_seq');
+            if (   defined('MEMBER_STREAMSEND_API')
+                && MEMBER_STREAMSEND_API) {
+                // send member to streamsend
+                $memberStreamSend = new Toolkit_Members_StreamSend($this->dbh);
+                $memberStreamSend->updateOptionByCategoryId($categoryId);
+            }
+            return $ret;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+
+    //  {{{ loadMemberCategories()
+
+    /**
+     * Loads member categories into the select list
+     *
+     * Gets an array structure of the member categories in a linear tree order
+     * Then walk through the array and load each category into the select list
+     *
+     * @return void
+     * @access protected
+     */
+    protected function loadMemberCategories()
+    {
+        if (!$this->elementExists('parent_id')) {
+            return;
+        }
+        try {
+                       if (isset($_GET['id']) && ctype_digit((string)$_GET['id'])) {
+                               $sql = "
+                    select count(*) AS total
+                      from category
+                     where parent_id = :pid";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':pid', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                               if ($row['total'] > 0) {
+                                       return;
+                               }
+                       }
+            //  Get a tree list of categories in linear order with
+            //  category keys in the values and their level in the tree
+            //  in the value
+            $c = Toolkit_Common::getHierarchicalTreeStructure(
+                $this->dbh,
+                'category',
+                'category_id',
+                'parent_id',
+                               'name',
+                               0,
+                               1
+            );
+
+            //  Get all the data about each category
+            $sql = "
+                SELECT *
+                  FROM category
+                 WHERE category_id = ?";
+
+            $stmt = $this->dbh->prepare($sql);
+            //  Get the member categories select list element
+            $e =& $this->getElement('parent_id');
+            foreach ($c as $i => $j) {
+                $stmt->execute(array($i));
+                $row = $stmt->fetch();
+                //  the class level is always 1 less than what is reported
+                //  from our $c array
+                $x = $j - 1;
+                //  Add the option data to the select list.
+                $e->addOption($row['name'], $i, array('class' => "level-$x"));
+            }
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself. Calls the Auxiliary base class function to handle
+        * the rendering.
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml()
+       {
+               $listPage = BASE_URL . 'admin/members.php?rt=Categories&ac=listCategories';
+               return parent::toHtml($listPage);
+       }
+
+       //      }}}
+
+       //      {{{ updateChildren()
+
+       /**
+        * Recusively updates all sub-categories to mirror the top category
+        *
+        * @param array $values The array of settings to update and the parent
+        *                                              id so you can find the children.
+        *
+        * @return bool false on error, otherwise true.
+        * @access protected
+        */
+       protected function updateChildren($values)
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM connectby('category', 'category_id', 'parent_id',
+                                                                       'pos', :cid, 0)
+                                       AS t(id text, parent text, level int, pos int)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':cid', $_GET['id'], PDO::PARAM_STR);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch()) {
+                               $children[] = $row;
+                       }
+                       //      If we actually got some subcategories,
+                       //      update their settings and check to see
+                       //      if they have any subcategories we can update.
+                       if (is_array($children)) {
+                               $sql = "
+                                       UPDATE {$this->tableName}
+                                          SET accommodations = :accommodations,
+                                              restaurant = :restaurant,
+                                                  golf = :golf
+                                        WHERE category_id = :category_id";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               foreach ($children as $k => &$v) {
+                                       $stmt->bindParam('category_id', $v['id'], PDO::PARAM_INT);
+                                       $stmt->bindParam(
+                        'accommodations',
+                        $values['accommodations'],
+                        PDO::PARAM_BOOL
+                    );
+                                       $stmt->bindParam(
+                        'restaurant',
+                        $values['restaurant'],
+                        PDO::PARAM_BOOL
+                    );
+                                       $stmt->bindParam('golf', $values['golf'], PDO::PARAM_BOOL);
+                                       $stmt->execute();
+                               }
+                               return true;
+                       } else {
+                               //      Otherwise we got no subcategories
+                               return true;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ updateData()
+
+       /**
+        * Update the settings for this category
+        *
+        * Any modules that are assigned to this category will be updated.
+        * And if this category has any sub-categories, those childrens
+        * module settings will be updated to mirror this categories settings.
+        *
+        * @param array $values Values submitted from the form
+        *
+        * @return bool false on sql error, otherwise true.
+        * @access protected
+        */
+       protected function updateData($values)
+       {
+               //      We aren't updating a category, we're deleting it.
+               if (array_key_exists('delete', $values)) {
+                       return $this->deleteCategory($_GET['id']);
+               }
+
+        $sql = Toolkit_Common::createSQLUpdate(
+            $this->tableName,
+            array_keys($values),
+            array('category_id = :id')
+        );
+
+        $values['id'] = $_GET['id'];
+        try {
+            Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+            if (   defined('MEMBER_STREAMSEND_API')
+                && MEMBER_STREAMSEND_API) {
+                // send member to streamsend
+                $memberStreamSend = new Toolkit_Members_StreamSend($this->dbh);
+                $memberStreamSend->updateOptionByCategoryId($_GET['id']);
+            }
+            return $this->updateChildren($values);
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/EditCity.php b/Toolkit/Members/Admin/EditCity.php
new file mode 100644 (file)
index 0000000..269f6ec
--- /dev/null
@@ -0,0 +1,639 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Edit cities stored in the DB for members
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditCity.php,v 1.13 2010/07/14 23:27:59 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Edit cities in the member database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditCity.php,v 1.13 2010/07/14 23:27:59 jamie Exp $
+ */
+class Toolkit_Members_Admin_EditCity
+    extends Toolkit_Members_Auxiliary
+    implements Toolkit_Form
+{
+       //      {{{      properties
+
+    /**
+     * Table name in DB
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'city';
+
+    /**
+     * Form template
+     * @var    string
+     * @access protected
+     */
+       protected $formTemplate = 'editCity.tpl';
+
+    /**
+     * Image Server
+     * @var    object
+     * @access protected
+     */
+    protected $is;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+       //      {{{ checkCityName()
+
+    /**
+     * Check that the city name is not in use already
+     *
+     * @param string $name name to check
+     *
+     * @return boolean if the name is valid or not
+     * @access public
+     */
+       public function checkCityName($name)
+       {
+               try {
+                       //      If we're editing a city, they
+                       //      can save that city as its
+                       //      own name. so don't include that
+                       //      city in the check.
+                       if (isset($_GET['id'])) {
+                               $and = "AND city_id <> :id";
+                       }
+                       $sql = "
+                SELECT COUNT(*) AS total
+                  FROM {$this->tableName}
+                 WHERE city_name = :name
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':name', $name, PDO::PARAM_STR);
+                       if (isset($_GET['id'])) {
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $total);
+                       $stmt->fetch();
+
+                       return !(bool) $total;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+    /**
+     * Set up the default values for the form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+               if (isset($_GET['id'])) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM city
+                                        WHERE city_id = :id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $city = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $defaults = array(
+                                       'city_name'                     => $city['city_name'],
+                                       'county_id'                     => $city['county_id'],
+                                       'state_id'                      => $city['state_id'],
+//                                     'description'           => $city['description'],
+//                                     'image_rmv'                     => "<image src=".MEMBER_THUMB."{$city['image']} />",
+//                                     'uploaded_file_rmv'     => $city['image'],
+                                       'noCharLimit'       => true
+                               );
+
+                               //      If the user is editing a city, and no image has been uploaded yet.
+                               //      there is no point in showing an empty "current image" field, so remove
+                               //      that element from the form.
+                               if (empty($city['image']) && !$this->isSubmitted()) {
+                                       $this->removeElement('image_rmv', false);
+                                       $this->removeElement('remove_image', false);
+                               }
+                       } catch (PDOException $e) {
+                               $this->handleError($e);
+                       }
+               }
+
+               $this->setupDefaults($defaults);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements(Config_Container $c)
+       {
+        $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'cityInfoHdr',
+            'display' => 'Member Cities'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'city_name',
+            'display' => 'City'
+        );
+        $e[] = array(
+            'type' => 'select',
+            'req' => false,
+            'name' => 'county_id',
+            'display' => 'County',
+            'opts' => $this->getCounties(),
+        );
+               $e[] = array(
+            'type' => 'select',
+            'req' => true,
+            'name' => 'state_id',
+            'display' => 'State',
+            'opts' => array('' => '-- Select --') + Toolkit_Common::getStates($this->dbh),
+        );
+               //      If we're editing a city, show the current
+               //      city image in the form.
+//             if ($this->_hasImage()) {
+//                     $e[] = array(
+//                             'type'    => 'checkbox',
+//                             'req'     => false,
+//                             'name'    => 'remove_image_rmv',
+//                             'display' => 'Remove Image'
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'static',
+//                             'req'     => false,
+//                             'name'    => 'image_rmv',
+//                             'display' => 'Current Image'
+//                     );
+//            $e[] = array(
+//                             'type' => 'hidden',
+//                             'req'  => false,
+//                             'name' => 'old_image_rmv'
+//                     );
+//             }
+//             $e[] = array(
+//                     'type'    => 'file',
+//                     'req'     => false,
+//                     'name'    => 'new_image_rmv',
+//                     'display' => 'New Image',
+//             );
+//             $e[] = array(
+//            'type' => 'textarea',
+//            'req' => false,
+//            'name' => 'description',
+//            'display' => 'Description',
+//            'opts' => array(
+//                'id' => 'description',
+//                'rows' => 7,
+//                'cols' => 45
+//            ),
+//            'noCharLimit' => true
+//        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(Config_Container $c)
+    {
+        $this->configureElements($c);
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+
+               $mimeTypes = array(
+                       'image/jpe',
+                       'image/jpeg',
+                       'image/jpg',
+                       'image/jfif',
+                       'image/pjpeg',
+                       'image/pjp',
+                       'image/gif',
+                       'image/png',
+               );
+
+        $r[] = array(
+            'element' => 'new_image_rmv',
+            'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+            'type' => 'mimetype',
+            'format' => $mimeTypes,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'city_name',
+            'message' => 'ERROR: City already exists!',
+            'type' => 'callback',
+            'format' => array($this, 'checkCityName'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ deleteCity()
+
+    /**
+     * Delete city from db
+     *
+     * @param integer $id city id
+     *
+     * @return boolean result of removing city
+     * @access protected
+     */
+       protected function deleteCity($id)
+       {
+        $city = new Toolkit_Members_City($this->dbh);
+        return $city->deleteCity($id);
+       }
+
+       //      }}}
+
+       //      {{{ getRegions()
+
+    /**
+     * Get the regions stored in the DB
+     *
+     * @return array regions
+     * @access protected
+     */
+       protected function getCounties()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM county
+                 ORDER BY county_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $counties[$row['county_id']] = $row['county_name'];
+                       }
+                       if (!empty($counties)) {
+                               $counties = array('' => '-- Select --') + $counties;
+                       } else {
+                               $counties = array('' => '-- No County Created Yet --');
+                       }
+
+                       return $counties;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ _hasImage()
+
+    /**
+     * Determine if the city record has a image
+     *
+     * @return boolean if the record has a image or not
+     * @access private
+     */
+       private function _hasImage()
+       {
+               try {
+            if (!is_numeric($_GET['id'])) {
+                return false;
+            }
+
+                       $sql = "
+                SELECT image
+                  FROM {$this->tableName}
+                 WHERE city_id = :city_id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':city_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+
+                       $hasLogo = !is_null($row['image']);
+
+                       return $hasLogo;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Create a new city
+     *
+     * @param array $values Submitted form values
+     *
+     * @return boolean Result of insertion into DB
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $city = new Toolkit_Members_City($this->dbh);
+        $city->setName($values['city_name']);
+        $city->setState($values['state_id']);
+        $city->setCounty($values['county_id']);
+//        $city->setImage($values['image']);
+//        $city->setDescription($values['description']);
+
+        return $city->createNewCity();
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+    /**
+     * clean unneeded form elements out of the submitted values array
+     *
+     * @param array $values QuickForm submitted elements
+     *
+     * @return boolean Result of insert/update functions
+     * @access public
+     */
+       public function processData($values)
+       {
+               $this->processImage($values);
+
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       case 'MAX_FILE_SIZE' :
+                               unset($values[$k]);
+                               break;
+
+                       default :
+                if (substr($k, -4) == '_rmv') {
+                                       unset($values[$k]);
+                               }
+                               break;
+                       }
+               }
+
+        $function = is_numeric($_GET['id']) ? 'updateData' : 'insertData';
+        return $this->$function($values);
+       }
+
+       //      }}}
+       //      {{{     processImage()
+
+    /**
+     * create or update city images
+     *
+     * @param array $values submitted form values
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+       protected function processImage($values)
+       {
+               //      Keep a tidy house.
+               //      There are 2 scenarios to deal w/ images:
+               //      1.  Removing image:
+               //              Delete the image from the image server
+               //              and set the values['image'] to null.
+               //      2.  New image:
+               //              Check to see if old_image_rmv holds a value,
+               //              if it does then remove that image
+               //              Upload the image and put new filename
+               //              into values['image'] variable.
+               $imgServer  = new Toolkit_Image_Server();
+
+               if ($values['remove_image_rmv'] == 1) {
+                       $imgServer->imageDelete($values['old_image_rmv']);
+                       $values['image'] = null;
+               }
+
+               //      If a new image is uploaded, have the image server
+               //      process that image and give us back the file name on
+               //      the server.
+               if ($values['new_image_rmv']['size'] > 0) {
+                       $imgName = $imgServer->imageUpload('new_image_rmv');
+                       $values['image'] = $imgName;
+                       $img = '<img alt="'. $imgName . '" src="'.MEMBER_PHOTOS . $imgName.'">';
+
+                       //      If the old_image_rmv key is set and not empty
+                       //      then we are replacing an existing image and did not
+                       //      check the remove image checkbox.
+                       //      remove this old image just for good house keeping.
+                       if (isset($values['old_image_rmv']) && !empty($values['old_image_rmv'])) {
+                               $imgServer->imageDelete($values['old_image_rmv']);
+                               //      update the elements on the form if we are replacing an existing image.
+                               if ($this->elementExists('old_image_rmv')) {
+                                       $e =& $this->getElement('old_image_rmv');
+                                       $e->setValue($imgName);
+                               }
+                               if ($this->elementExists('image_rmv')) {
+                                       $e =& $this->getElement('image_rmv');
+                                       $e->setValue($img);
+                               }
+                       } else {
+                               $source =& $this->createElement(
+                    'checkbox',
+                    'remove_image_rmv',
+                    'Remove Logo'
+                );
+                               $this->insertElementBefore($source, 'new_image_rmv');
+
+                               $source =& $this->addElement('hidden', 'old_image_rmv');
+                               $source->setValue($imgName);
+
+                               $source =& $this->createElement(
+                    'static',
+                    'image_rmv',
+                    'Current Logo'
+                );
+                               $source->setValue($img);
+                               $element = $this->insertElementBefore($source, 'new_image_rmv');
+
+                               if (PEAR::isError($element)) {
+                                       die ('there was an error uploading your file!');
+                               } else {
+                                       //  I don't know why, but the insertElementBefore
+                                       //  function was erasing the value we set earlier.
+                                       //  so just reset it to make double sure its there.
+                                       $element->setValue($img);
+                               }
+                       }
+               }
+
+               //      We clicked to remove the image and did not upload a new one.
+               if ($values['remove_image_rmv'] == 1 && $values['new_image_rmv']['size'] == 0) {
+                       if ($this->elementExists('remove_image_rmv')) {
+                               $this->removeElement('remove_image_rmv', false);
+                       }
+                       if ($this->elementExists('image_rmv')) {
+                               $this->removeElement('image_rmv', false);
+                       }
+                       if ($this->elementExists('old_image_rmv')) {
+                               $this->removeElement('old_image_rmv', false);
+                       }
+               }
+       }
+
+       //      }}}
+
+    //  {{{ setImageServer()
+
+    /**
+     * Set the image server object to use
+     *
+     * @param Toolkit_Image_Server $is Image Server Object
+     *
+     * @return void
+     * @access public
+     */
+    public function setImageServer(Toolkit_Image_Server $is)
+    {
+        $this->is = $is;
+    }
+
+    //  }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form for viewing
+        *
+        * This function validates the form if needed, and if it successfully
+        * validates attempts to insert or update the data record.
+        * If it is unsuccessful, it will return an error to the user
+        * informing them of what went wrong.
+        *
+        * @return string The compiled and filled form template.
+        * @access public
+        */
+       public function toHtml()
+       {
+               $listPage = BASE_URL . 'admin/members.php?rt=Cities&ac=listCities';
+               return parent::toHtml($listPage);
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the data for a region
+     *
+     * @param array $values submitted form results
+     *
+     * @return boolean result of sql update query
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+               //      We aren't updating a region, we're deleting it.
+               if (array_key_exists('delete', $values)) {
+                       return $this->deleteCity($_GET['id']);
+               }
+
+        $city = new Toolkit_Members_City($this->dbh);
+        $city->setName($values['city_name']);
+        $city->setState($values['state_id']);
+        $city->setCounty($values['county_id']);
+//        $city->setImage($values['image']);
+//        $city->setDescription($values['description']);
+
+        return $city->updateCity($_GET['id']);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/EditCounty.php b/Toolkit/Members/Admin/EditCounty.php
new file mode 100644 (file)
index 0000000..651f457
--- /dev/null
@@ -0,0 +1,383 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Edit member regions
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditRegion.php,v 1.11 2010/07/14 23:27:59 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Edit Member Regions
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_EditCounty
+    extends Toolkit_Members_Auxiliary
+    implements Toolkit_Form
+{
+       //      {{{ properties
+
+    /**
+     * Description for public
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'county';
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+       protected $formTemplate = 'editCounty.tpl';
+
+       //      }}}
+
+       //      {{{ checkRegionName()
+
+    /**
+     * Check that the region name is not in use already
+     *
+     * @param string $name name to check
+     *
+     * @return boolean if the name is valid or not
+     * @access public
+     */
+       public function checkRegionName($name)
+       {
+               try {
+                       //      If we're editing a region, they
+                       //      can save that region as its
+                       //      own name. so don't include that region
+                       //      in the check.
+                       if (isset($_GET['id'])) {
+                               $and = "AND county_id <> :rid";
+                       }
+                       $sql = "
+                               SELECT COUNT(*) AS total
+                                 FROM {$this->tableName}
+                                WHERE lower(county_name) = lower(:name)
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':name', $name, PDO::PARAM_STR);
+                       if (isset($_GET['id'])) {
+                               $stmt->bindParam(':rid', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $total);
+                       $stmt->fetch();
+
+                       return !(bool) $total;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+    /**
+     * Set up the default values for the form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+        $d = array();
+
+               if (isset($_GET['id']) && ctype_digit($_GET['id'])) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM {$this->tableName}
+                                        WHERE county_id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':cid', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $county = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $d = array(
+                                       'county_name' => $county['county_name'],
+                    'region_id'   => $county['region_id'],
+                    'state_id'    => $county['state_id']
+                               );
+                       } catch (PDOException $e) {
+                Toolkit_Common::handleError($e);
+                       }
+               }
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+        * @param Config_Container $c Application Configuration
+        *
+     * @return void
+     * @access public
+     */
+       public function configureElements(Config_Container $c)
+       {
+        $e = array();
+
+               $singularType = $c->getItem('section', 'county type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+               $pluralType = $c->getItem('section', 'county type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+        //  get reference to [listing type] section of config file
+        $config =& $c->getItem('section', 'conf');
+        $regionDirective =& $config->getItem('directive', 'regions');
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'countyInfoHdr',
+            'display' => "Member {$pluralType}"
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'county_name',
+            'display' => "{$singularType} Name"
+        );
+//        if ($regionDirective->getContent()) {
+//                     $e[] = array(
+//                'type' => 'select',
+//                'req' => false,
+//                'name' => 'region_id',
+//                'display' => 'Region',
+//                'opts' => $this->getRegions(),
+//            );
+//             }
+               $e[] = array(
+            'type' => 'select',
+            'req' => true,
+            'name' => 'state_id',
+            'display' => 'State',
+            'opts' => array('' => '-- Select --') + Toolkit_Common::getStates($this->dbh),
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+        * @param PDO              $dbh Database handler
+        * @param Config_Container $c   Application Configuration
+        *
+     * @return void
+     * @access public
+     */
+    public function configureForm(PDO $dbh, Config_Container $c)
+    {
+               $this->dbh = $dbh;
+        $this->configureElements($c);
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+
+               $r[] = array(
+            'element' => 'county_name',
+            'message' => 'ERROR: Name already exists!',
+            'type' => 'callback',
+            'format' => array($this, 'checkCountyName'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+    // {{{ getRegions()
+
+    /**
+     * Get the regions stored in the DB
+     *
+     * @return array regions
+     * @access protected
+     */
+       protected function getRegions()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM region
+                 ORDER BY region_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $regions[$row['region_id']] = $row['region_name'];
+                       }
+                       if (!empty($regions)) {
+                               $regions = array('' => '-- Select --') + $regions;
+                       } else {
+                               $regions = array('' => '-- No Regions Created Yet --');
+                       }
+
+                       return $regions;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ deleteRegion()
+
+    /**
+     * Remove a region from the db
+     *
+     * @param integer $id region id
+     *
+     * @return boolean result of db query
+     * @access protected
+     */
+       protected function deleteCounty($id)
+       {
+        if (!ctype_digit((string)$id)) {
+            return false;
+        }
+               try {
+                       $sql = "
+            DELETE FROM {$this->tableName}
+             WHERE county_id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Create a new region
+     *
+     * @param array $values Submitted form values
+     *
+     * @return boolean Result of insertion into DB
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $sql = Toolkit_Common::createSQLInsert(
+            $this->tableName,
+            array_keys($values)
+        );
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form for viewing
+        *
+        * This function validates the form if needed, and if it successfully
+        * validates attempts to insert or update the data record.
+        * If it is unsuccessful, it will return an error to the user
+        * informing them of what went wrong.
+        *
+        * @return string The compiled and filled form template.
+        * @access public
+        */
+       public function toHtml()
+       {
+               $listPage = BASE_URL . 'admin/members.php?rt=Counties&ac=listCounties';
+               return parent::toHtml($listPage);
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the data for a region
+     *
+     * @param array $values submitted form results
+     *
+     * @return boolean result of sql update query
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+               //      We aren't updating a region, we're deleting it.
+               if (array_key_exists('delete', $values)) {
+                       return $this->deleteCounty($_GET['id']);
+               }
+
+        $sql = Toolkit_Common::createSQLUpdate(
+            $this->tableName,
+            array_keys($values),
+            array('county_id = :id')
+        );
+
+        $values['id'] = $_GET['id'];
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/EditHtmlEmail.php b/Toolkit/Members/Admin/EditHtmlEmail.php
new file mode 100644 (file)
index 0000000..44a27d4
--- /dev/null
@@ -0,0 +1,375 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Controls Amenity definitions for the member db
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditHtmlEmail.php,v 1.10 2010/07/28 12:42:37 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handles creating / editing amenities that the members will use
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_EditHtmlEmail
+    extends Toolkit_Members_Auxiliary implements Toolkit_Form
+{
+       //      {{{     properties
+
+    /**
+     * Description for public
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'member_newsletters';
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+       protected $formTemplate = 'editHtmlEmail.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @access public
+        */
+    public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+       //      {{{ checkAmenityName()
+
+    /**
+     * Check that the amenity name is not in use already
+     *
+     * @param string $name name to check
+     *
+     * @return boolean if the name is valid or not
+     * @access public
+     */
+       public function checkSubjectName($name)
+       {
+               try {
+                       //      If we're editing a amenity, they
+                       //      can save that amenity as its
+                       //      own name. so don't include that
+                       //      amenity in the check.
+                       if (isset($_GET['id'])) {
+                               $and = "AND id <> :id";
+                       }
+                       $sql = "
+                SELECT count(*) AS total
+                  FROM {$this->tableName}
+                 WHERE subject = :name
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':name', $name, PDO::PARAM_STR);
+                       if (isset($_GET['id'])) {
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $total);
+                       $stmt->fetch();
+
+                       return !(bool) $total;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+    /**
+     * Set up the default values for the form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+        $d = array();
+
+               if (isset($_GET['id'])) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM {$this->tableName}
+                                        WHERE id = :id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $d = $stmt->fetch();
+                       } catch (PDOException $e) {
+                           Toolkit_Common::handleError($e);
+                       }
+               }
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements()
+       {
+               $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.
+               //      This includes group element definitions.
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'HtmlEmailInfoHdr',
+                       'display' => 'Html Newsletters'
+               );
+               $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'archived',
+                       'display' => 'Archived'
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'subject',
+                       'display' => 'Email Subject'
+               );
+               $e[] = array(
+            'type' => 'textarea',
+            'req' => false,
+            'name' => 'response',
+            'display' => 'Email Body',
+            'opts' => array(
+                'id' => 'response',
+                'rows' => 7,
+                'cols' => 45
+            ),
+                       'noCharLimit' => true
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+
+               $r[] = array(
+            'element' => 'subject',
+            'message' => 'ERROR: Newsletter already exists!',
+            'type' => 'callback',
+            'format' => array($this, 'checkSubjectName'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ deleteAmenity()
+
+    /**
+     * Remove a region from the db
+     *
+     * @param integer $id region id
+     *
+     * @return boolean result of db query
+     * @access protected
+     */
+       protected function deleteHtmlEmail($id)
+       {
+        if (!is_numeric($id)) {
+            return false;
+        }
+               try {
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                                WHERE id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Create a new amenity
+     *
+     * @param array $values Submitted form values
+     *
+     * @return boolean Result of insertion into DB
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $values['last_update'] = date('m/d/Y');
+        $values['archived'] = ($values['archived']) ? $values['archived'] : 0;
+        $sql = Toolkit_Common::createSQLInsert(
+            $this->tableName,
+            array_keys($values)
+        );
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the data for an amenity
+     *
+     * @param array $values submitted form results
+     *
+     * @return boolean result of sql update query
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+           $values['last_update'] = date('m/d/Y');
+           $values['archived'] = ($values['archived']) ? $values['archived'] : 0;
+               //      We aren't updating a region, we're deleting it.
+               if (array_key_exists('delete', $values)) {
+                       return $this->deleteHtmlEmail($_GET['id']);
+               }
+
+        $sql = Toolkit_Common::createSQLUpdate(
+            $this->tableName,
+            array_keys($values),
+            array('id = :id')
+        );
+
+        $values['id'] = $_GET['id'];
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+
+       //      {{{ toHTML()
+
+       /**
+        * Renders the form for viewing
+        *
+        * This function validates the form if needed, and if it successfully
+        * validates attempts to insert or update the data record.
+        * If it is unsuccessful, it will return an error to the user
+        * informing them of what went wrong.
+        *
+        * @return string The compiled and filled form template.
+        * @access public
+        */
+       public function toHtml()
+       {
+               $listPage = BASE_URL . 'admin/members.php?rt=Newsletter&ac=listHtmlEmails';
+               return parent::toHtml($listPage);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/EditPackages.php b/Toolkit/Members/Admin/EditPackages.php
new file mode 100644 (file)
index 0000000..57fa369
--- /dev/null
@@ -0,0 +1,1567 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles the packages tab in the member record
+ *
+ * Controls setting up the add package form if applicable, and rendering
+ * each uploaded package edit form to edit/delete the package.
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditPackages.php,v 1.20 2010/07/16 20:53:24 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit/Image/Server.php
+ */
+
+
+/**
+ * The image server processing class
+ */
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Constructor class to setup the page layout
+ *
+ * this class determines if the user can upload any more packages to their
+ * account and if so renders the add package form.  It also controls
+ * rending the individual forms for each previously uploaded package.
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_EditPackages
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_packages';
+
+    /**
+     * Template used to layout form when editing a package
+     * @var    string
+     * @access protected
+     */
+       protected $pageTemplate = 'editPackages.tpl';
+
+       /**
+        * Sets the max number of packages allowed for each listing
+        * @var integer
+        * @access protected
+        */
+       protected $maxPackages = 2;
+
+    /**
+     * What is the maximum caption length for packages
+        *
+     * @var    array
+     * @access public
+     * @static
+     */
+       static public $maxTitleLength = 60;
+
+    /**
+     * Objects that will go into the page (add form, edit package forms)
+     * @var    object
+     * @access protected
+     */
+       protected $page;
+
+    /**
+     * Description for protected
+     * @var    PDO
+     * @access protected
+     */
+    protected $dbh;
+
+       //      }}}
+
+    //  {{{ __construct()
+
+    /**
+     * Constructor
+     *
+     * @param PDO                 $pdo     PHP Data Object to use for DB calls
+     * @param HTML_Template_Flexy $tEngine Templating Engine
+     *
+     * @return void
+     * @access public
+     */
+    public function __construct(PDO $pdo, HTML_Template_Flexy $tEngine)
+    {
+        $this->dbh = $pdo;
+        $this->tEngine = $tEngine;
+    }
+
+    //  }}}
+
+       //      {{{     canAddPackages()
+
+       /**
+        * Determine if this member can have more packages added to their profile
+        *
+        * Load the entire package gallery into member via a linked list.
+        * Then return if the # of linked list nodes is smaller than
+        * the maximum limit of packages.
+        *
+        * @access protected
+        * @return boolean If the linked list is smaller than max packages allowed
+        */
+       protected function canAddPackages()
+       {
+               $ll = new Toolkit_Members_Packages(null, $_GET['id']);
+        $ll->setDbh($this->dbh);
+               $ll->createMemberList();
+               return ($ll->getListSize() < $this->maxPackages);
+       }
+
+       //      }}}
+
+       //      {{{     displayPage()
+
+    /**
+     * Displays the page to the screen
+     *
+     * @param Toolkit_Members_RecordNavigation $nav Record subnav object
+     *
+     * @return void
+     * @access public
+     */
+       public function displayPage(Toolkit_Members_RecordNavigation $nav)
+       {
+               echo $this->getPage($nav);
+       }
+
+       //      }}}
+
+       //      {{{     getPage()
+
+    /**
+     * Sets up the flexy template and returns the rendered page
+     *
+     * @param Toolkit_Members_RecordNavigation $nav record subnav object
+     *
+     * @return object rendered page
+     * @access public
+     */
+       public function getPage(Toolkit_Members_RecordNavigation $nav)
+       {
+               $this->page->nav = $nav->getPageNav();
+               $this->tEngine->compile($this->pageTemplate);
+               return $this->tEngine->bufferedOutputObject($this->page);
+       }
+
+       //      }}}
+
+       //      {{{     getUploadedPackages()
+
+       /**
+        * Get an array of package ids from the DB that have been uploaded for this member
+        *
+        * - Create a linked list of all the members packages
+        * - Walk through the linked list extracting the id from each node into an array
+        *
+        * @access protected
+        * @return array Ids of all uploaded packages for this member
+        */
+       protected function getUploadedPackages()
+       {
+               $packages = new Toolkit_Members_Packages(null, $_GET['id']);
+        $packages->setDbh($this->dbh);
+               $packages->createMemberList();
+               $packages->rewind();
+
+               $ids = array();
+               foreach ($packages as $i) {
+                       //      Don't show the pending packages here.
+                       if (!$i->getPending()) {
+                               $ids[] = $i->getId();
+                       }
+               }
+
+               return $ids;
+       }
+
+       //      }}}
+
+       //      {{{     setUpPage()
+
+       /**
+        * Sets up the page to manipulate packages for a member
+        *
+        * Checks if all the packages uploaded for a member (pending & non-pending)
+        * exceed or match the maximum # of packages allowed for each member to
+        * upload to their account.
+        *
+        * For every package that is already uploaded, create an edit-package form that
+        * will allow the user to update the caption or delete the package.
+        *
+        * @return void
+        * @access public
+        */
+       public function setUpPage()
+       {
+               $this->page = new StdClass;
+
+               //      Find out if we can still add packages to the record.
+               //      If we can, then add the upload form to the page for the member to see.
+               if ($this->canAddPackages()) {
+                       $addForm = new AddAdminPackage(
+                               $this->dbh,
+                'new_member_package',
+                'post',
+                '',
+                '',
+                null,
+                true
+                       );
+
+            $addForm->configureForm();
+                       $this->page->uploadForm = $addForm->toHtml($this->tEngine);
+               }
+
+               //      Find out if we have any packages already uploaded.
+               //      If we do, then add the edit package form to the page for each package
+               //      so the member can edit/delete their packages.
+               if ($packages = $this->getUploadedPackages()) {
+                       $this->page->editForm = array();
+                       while (list($i, $j) = each($packages)) {
+                               $editForm = new EditAdminPackage(
+                                       $this->dbh,
+                    "edit_member_package_$j",
+                    'post',
+                    '',
+                    '',
+                    array('id' => $j),
+                    true
+                               );
+
+                $editForm->configureForm();
+                               $this->page->editForm[] = $editForm->toHtml($this->tEngine);
+                       }
+               }
+       }
+
+       //      }}}
+}
+
+/**
+ * Form to handle creating a new package in the members only area
+ *
+ * Handles inserting new package into db as a pending package and creating a
+ * tuple in the member_updates table which will allow the admin to
+ * approve/deny the new package request.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class AddAdminPackage extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_packages';
+
+       /**
+        * Some special forms dont utlize this stylesheet
+        * Allow classes to override this setting so it doesn't
+        * get included
+        *
+        * @var boolean
+        * @access protected
+        */
+       protected $includeContactStyleSheet = false;
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'addPackage.tpl';
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+    protected $successMsg
+        = '<div id="form-success-top">
+            You successfully uploaded your package.
+           </div>';
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $mimeTypes = array(
+        'image/jpe',
+        'image/jpeg',
+        'image/jpg',
+        'image/jfif',
+        'image/pjpeg',
+        'image/pjp',
+        'image/gif',
+        'image/png',
+    );
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+        * @param PDO    $pdo         PHP Data Object to use for DB calls
+        * @param string $formName    Form's name.
+        * @param string $method      (optional) Form's method defaults to 'POST'
+        * @param string $action      (optional) Form's action.
+        * @param string $target      (optional) Form's target defaults to '_self'
+        * @param mixed  $attributes  (optional) Extra attributes for <form> tag.
+        * @param bool   $trackSubmit (optional) Whether to track if the form was
+        *                                                                               submitted by adding a special hidden
+        *                                                                               field.
+        *
+        * @access public
+        * @see    Toolkit_Members_Admin_EditPackages
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+    //  {{{ configureForm()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+               $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'title',
+            'display' => 'Package Title',
+               );
+               $e[] = array(
+                       'type'        => 'textarea',
+                       'req'         => false,
+                       'name'        => 'description',
+            'display'     => 'Package Description',
+            'opts'        => array('id' => 'descrAdd', 'class' => 'ckeditor'),
+                       'noCharLimit' => true
+               );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'sdate',
+            'display' => 'Start Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'edate',
+            'display' => 'End Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'checkbox',
+            'req'     => false,
+            'name'    => 'remove_img_rmv',
+            'display' => 'Remove Image',
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'curr_image',
+            'display' => 'Current Image',
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'curr_image_rmv',
+        );
+               $e[] = array(
+                       'type'    => 'file',
+                       'req'     => false,
+                       'name'    => 'image',
+            'display' => 'Upload a Package Photo / Image',
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'add_rmv',
+                       'display' => 'Upload new package',
+                       'opts'    => array('class' => 'submit')
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+    /**
+     * Configure rules for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+               $r = array();
+
+        $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));');
+               $r[] = array(
+                       'element'    => 'sdate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'edate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'image',
+                       'message'    => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                       'type'       => 'mimetype',
+                       'format'     => $this->mimeTypes,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{ configureConstants()
+
+    /**
+     * Configure constants for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+               $c = array(
+            'remove_img_rmv' => false
+        );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Configure filters for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+               $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+
+    //  {{{ deleteImage()
+
+    /**
+     * Remove an image record
+     *
+     * @param Toolkit_Image_Server $is  Image Server Object
+     * @param string               $img image name
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+    protected function deleteImage(Toolkit_Image_Server $is, $img)
+    {
+        return $is->imageDelete($img);
+    }
+
+    //  }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Create a new package in the db
+     *
+     * @param array &$values Form submitted values
+        *
+     * @return object    db result of adding package
+     * @access protected
+     */
+       protected function insertData(&$values)
+       {
+               try {
+            $sql = Toolkit_Common::createSQLInsert(
+                $this->tableName,
+                array_keys($values)
+            );
+
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+        //     }}}
+
+       //      {{{ processData()
+
+       /**
+        * Handles setting up the from processing and which function to get it done
+        *
+        * @param array $values Submitted values from the form.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function processData($values)
+       {
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+        $e =& $this->getElement('curr_image_rmv');
+
+               $packages = new Toolkit_Members_Packages(null, $_GET['id']);
+        $packages->setDbh($this->dbh);
+               $packages->createMemberList();
+               $values['pos']       = $packages->getListSize() + 1;
+        $values['image'] = $e->getValue('curr_image_rmv');
+               $values['member_id'] = $_GET['id'];
+               $values['pending']   = 0;
+        $values['sdate'] = implode('-', $values['sdate']);
+        $values['edate'] = implode('-', $values['edate']);
+               unset($values['MAX_FILE_SIZE'],
+                         $values['curr_image_rmv'],
+                         $values['remove_img_rmv'],
+              $values['add_rmv']);
+
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               $this->insertData($values);
+
+               $listPage = BASE_URL .
+                       "admin/members.php?rt=Members&ac=editMember&tab=packages&id={$_GET['id']}";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ setupRenderers()
+
+    /**
+     * Set up the rendering engine we are going to use to display this form
+     *
+     * @param HTML_Template_Flexy &$tEngine Templating Engine
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers(HTML_Template_Flexy &$tEngine)
+       {
+               $renderer = new HTML_QuickForm_Renderer_ObjectFlexy($tEngine);
+
+               $this->accept($renderer);
+               $this->view              = new stdClass();
+        $this->view->showCurrImg = $this->showCurrImg;
+               $this->view->form        = $renderer->toObject();
+               $tEngine->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+    //  {{{ validNewImg()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $newImg Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+    function validNewImg(array $newImg)
+    {
+        return (   is_numeric($newImg['size'])
+                               && $newImg['size'] > 0
+                               && in_array($newImg['type'], $this->mimeTypes));
+    }
+
+    //  }}}
+    //  {{{ removeOldImage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is     Parameter description (if any) ...
+     * @param string               $oldImg Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    function removeOldImage(Toolkit_Image_Server $is, $oldImg)
+    {
+        $this->deleteImage($is, $oldImg);
+        if ($this->elementExists('curr_image_rmv')) {
+            $e =& $this->getElement('curr_image_rmv');
+            $e->setValue(null);
+            $this->_submitValues['curr_image_rmv'] = null;
+        }
+    }
+
+    //  }}}
+    //  {{{ syncCurrImage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+    protected function syncCurrImage()
+    {
+        $is = new Toolkit_Image_Server();
+
+        $delImg = $this->getSubmitValue('remove_img_rmv');
+        $oldImg = $this->getSubmitValue('curr_image_rmv');
+        $newImg = $this->getSubmitValue('image');
+
+        if ($delImg && $oldImg) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        } elseif ($oldImg && $this->validNewImg($newImg)) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        }
+
+        if ($this->validNewImg($newImg)) {
+            $image = $this->uploadImage($is, 'image');
+        } else {
+            $image = $oldImg;
+        }
+
+        if ($image) {
+            $this->updatePhotoElements($is, $image);
+            $this->showCurrImg = true;
+        }
+    }
+
+    //  }}}
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+     * @param HTML_Template_Flexy $tEngine Templating Engine
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(HTML_Template_Flexy $tEngine)
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+
+        //  If they have submitted the form and uploaded a proper image
+        //  but some other element had an error, then we need to show
+        //  their uploaded image in the form
+        if ($this->isSubmitted()) {
+            $this->syncCurrImage();
+        }
+
+               $this->setupRenderers($tEngine);
+
+               if ($this->validated) {
+                       $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+               }
+
+               return $tEngine->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+    //  {{{ updatePhotoElements()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is    Parameter description (if any) ...
+     * @param string               $image Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    public function updatePhotoElements(Toolkit_Image_Server $is, $image)
+    {
+        //  Get the dimensions of the image
+        $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image);
+        if (PEAR::isError($dimensions)) {
+            Toolkit_Common::handleError($dimensions);
+        }
+        list($w, $h) = $dimensions;
+        $s = MEMBER_PHOTOS . $image;
+
+        //  Set the image to show in the element
+        $e =& $this->getElement('curr_image');
+        $e->setText('<img width="'.$w.'" height="'.$h.'" src="'.$s.'">');
+
+        //  updated the hidden elements value to make sure it
+        //  holds the most up-to-date image name
+        $e =& $this->getElement('curr_image_rmv');
+        $e->setValue($image);
+    }
+
+    //  }}}
+    //  {{{ uploadImage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is    Parameter description (if any) ...
+     * @param string               $field Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+    protected function uploadImage(Toolkit_Image_Server $is, $field)
+    {
+        return $is->imageUpload($field);
+    }
+
+    //  }}}
+}
+
+/**
+ * Form to handle editing/deleting existing packages in members only area
+ *
+ * Handles updating caption requests for a member or to remove a
+ * package from thier profile
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class EditAdminPackage extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_packages';
+
+       /**
+        * Some special forms dont utlize this stylesheet
+        * Allow classes to override this setting so it doesn't
+        * get included
+        *
+        * @var boolean
+        * @access protected
+        */
+       protected $includeContactStyleSheet = false;
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editPackage.tpl';
+
+    /**
+     * Id of package in db
+     * @var    integer
+     * @access protected
+     */
+       protected $packageId;
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+    protected $successMsg
+        = '<div id="form-success-top">
+            You successfully updated your package.
+           </div>';
+
+    /**
+     * Any rules we want to register for this form
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $mimeTypes = array(
+        'image/jpe',
+        'image/jpeg',
+        'image/jpg',
+        'image/jfif',
+        'image/pjpeg',
+        'image/pjp',
+        'image/gif',
+        'image/png',
+    );
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+        * @param PDO    $pdo         PHP Data Object to use for DB calls
+        * @param string $formName    Form's name.
+        * @param string $method      (optional) Form's method defaults to 'POST'
+        * @param string $action      (optional) Form's action.
+        * @param string $target      (optional) Form's target defaults to '_self'
+        * @param mixed  $attributes  (optional) Extra attributes for <form> tag.
+        * @param bool   $trackSubmit (optional) Whether to track if the form was
+        *                                                                               submitted by adding a special hidden
+        *                                                                               field.
+        *
+        * @access public
+        * @see    Toolkit_Members_Admin_EditPackages
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               $this->packageId = $attributes['id'];
+               $this->packages  = new Toolkit_Members_Packages(null, $_GET['id']);
+        $this->packages->setDbh($pdo);
+               $this->packages->createMemberList();
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+    //  {{{ configureForm()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureDefaults();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{ configureDefaults()
+
+       /**
+        * Setup the element default values for form
+        *
+        * @access public
+        * @see    Toolkit_FormBuilder::setupDefaults()
+        * @return void
+        */
+       public function configureDefaults()
+       {
+        $sql = "
+            SELECT *
+              FROM {$this->tableName}
+             WHERE id = {$this->packageId}";
+
+        $defaults = $this->dbh->query($sql)->fetch(PDO::FETCH_ASSOC);
+        $defaults['curr_image_rmv'] = $defaults['image'];
+        $img = '<img src="%s">';
+        $defaults['curr_image'] = sprintf($img, MEMBER_PHOTOS . $defaults['image']);
+        $this->showCurrImg = $defaults['image'];
+               $this->setupDefaults($defaults);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * @access public
+        * @see    Toolkit_FormBuilder::setupElements()
+        * @return void
+        */
+       public function configureElements()
+       {
+               $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'title',
+            'display' => 'Package Title',
+               );
+               $e[] = array(
+                       'type'        => 'textarea',
+                       'req'         => false,
+                       'name'        => 'description',
+            'display'     => 'Package Description',
+            'opts'        => array('id' => 'descr' . $this->packageId, 'class' => 'ckeditor'),
+                       'noCharLimit' => true
+               );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'sdate',
+            'display' => 'Start Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'edate',
+            'display' => 'End Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'checkbox',
+            'req'     => false,
+            'name'    => 'remove_img_rmv',
+            'display' => 'Remove Image',
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'curr_image',
+            'display' => 'Current Image',
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'curr_image_rmv',
+        );
+               $e[] = array(
+                       'type'    => 'file',
+                       'req'     => false,
+                       'name'    => 'image',
+            'display' => 'Upload a Package Photo / Image',
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'add_rmv',
+                       'display' => 'Update Package',
+                       'opts'    => array('class' => 'submit')
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'remove_rmv',
+                       'display' => 'Remove Package',
+                       'opts'    => array('class' => 'submit')
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+    /**
+     * Configure rules for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+               $r = array();
+
+        $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));');
+               $r[] = array(
+                       'element'    => 'sdate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'edate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'image',
+                       'message'    => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                       'type'       => 'mimetype',
+                       'format'     => $this->mimeTypes,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{ configureConstants()
+
+    /**
+     * Configure constants for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+               $c = array(
+            'remove_img_rmv' => false
+        );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Configure filters for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+               $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+
+    //  {{{ deleteImage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is  Parameter description (if any) ...
+     * @param string               $img Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+    protected function deleteImage(Toolkit_Image_Server $is, $img)
+    {
+        return $is->imageDelete($img);
+    }
+
+    //  }}}
+
+       //      {{{ processData()
+
+       /**
+        * Handles setting up the from processing and which function to get it done
+        *
+        * @param array $values Submitted values from the form.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function processData($values)
+       {
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+        $e =& $this->getElement('curr_image_rmv');
+
+        $values['image'] = $e->getValue('curr_image_rmv');
+        $values['sdate'] = implode('-', $values['sdate']);
+        $values['edate'] = implode('-', $values['edate']);
+               unset($values['MAX_FILE_SIZE'],
+                         $values['curr_image_rmv'],
+                         $values['remove_img_rmv'],
+              $values['add_rmv']);
+
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               $this->updateData($values);
+
+               $listPage = BASE_URL .
+                       "admin/members.php?rt=Members&ac=editMember&tab=packages&id={$_GET['id']}";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ setupRenderers()
+
+    /**
+     * Set up the rendering engine we are going to use to display this form
+     *
+     * @param HTML_Template_Flexy &$tEngine Templating Engine
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers(HTML_Template_Flexy &$tEngine)
+       {
+               $renderer = new HTML_QuickForm_Renderer_ObjectFlexy($tEngine);
+
+               $this->accept($renderer);
+               $this->view              = new stdClass();
+        $this->view->showCurrImg = $this->showCurrImg;
+               $this->view->form        = $renderer->toObject();
+               $tEngine->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+    //  {{{ validNewImg()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $newImg Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+    function validNewImg(array $newImg)
+    {
+        return (   is_numeric($newImg['size'])
+                               && $newImg['size'] > 0
+                               && in_array($newImg['type'], $this->mimeTypes));
+    }
+
+    //  }}}
+    //  {{{ removeOldImage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is     Parameter description (if any) ...
+     * @param string               $oldImg Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    function removeOldImage(Toolkit_Image_Server $is, $oldImg)
+    {
+        $this->deleteImage($is, $oldImg);
+        if ($this->elementExists('curr_image_rmv')) {
+            $e =& $this->getElement('curr_image_rmv');
+            $e->setValue(null);
+            $this->_submitValues['curr_image_rmv'] = null;
+        }
+    }
+
+    //  }}}
+    //  {{{ syncCurrImage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+    protected function syncCurrImage()
+    {
+        $is = new Toolkit_Image_Server();
+
+        $delImg = $this->getSubmitValue('remove_img_rmv');
+        $oldImg = $this->getSubmitValue('curr_image_rmv');
+        $newImg = $this->getSubmitValue('image');
+
+        if ($delImg && $oldImg) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        } elseif ($oldImg && $this->validNewImg($newImg)) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        }
+
+        if ($this->validNewImg($newImg)) {
+            $image = $this->uploadImage($is, 'image');
+        } else {
+            $image = $oldImg;
+        }
+
+        if ($image) {
+            $this->updatePhotoElements($is, $image);
+            $this->showCurrImg = true;
+        }
+    }
+
+    //  }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+     * @param HTML_Template_Flexy $tEngine Templating Engine
+     *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(HTML_Template_Flexy $tEngine)
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+
+        //  If they have submitted the form and uploaded a proper image
+        //  but some other element had an error, then we need to show
+        //  their uploaded image in the form
+        if ($this->isSubmitted()) {
+            $this->syncCurrImage();
+        }
+
+               $this->setupRenderers($tEngine);
+
+               if ($this->validated) {
+                       $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+               }
+
+               return $tEngine->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+       //      {{{     removePackage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param int $id Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+       protected function removePackage($id)
+       {
+               try {
+            //  need to delete the image associated w/ this package here.
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                                WHERE id = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the package caption
+     *
+     * @param array $values Submitted form values
+        *
+     * @return boolean Result of updating the caption in the db
+     * @access public
+     */
+       protected function updateData($values)
+       {
+        try {
+            if (array_key_exists('remove_rmv', $values)) {
+                return $this->removePackage($this->packageId);
+            }
+            $sql = Toolkit_Common::createSQLUpdate(
+                $this->tableName,
+                array_keys($values),
+                array('id = :id')
+            );
+
+            $values['id'] = $this->packageId;
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+    //  {{{ updatePhotoElements()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is    Parameter description (if any) ...
+     * @param string               $image Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    public function updatePhotoElements(Toolkit_Image_Server $is, $image)
+    {
+        //  Get the dimensions of the image
+        $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image);
+        if (PEAR::isError($dimensions)) {
+            Toolkit_Common::handleError($dimensions);
+        }
+        list($w, $h) = $dimensions;
+        $s = MEMBER_PHOTOS . $image;
+
+        //  Set the image to show in the element
+        $e =& $this->getElement('curr_image');
+        $e->setText('<img width="'.$w.'" height="'.$h.'" src="'.$s.'">');
+
+        //  updated the hidden elements value to make sure it
+        //  holds the most up-to-date image name
+        $e =& $this->getElement('curr_image_rmv');
+        $e->setValue($image);
+    }
+
+    //  }}}
+    //  {{{ uploadImage()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is    Parameter description (if any) ...
+     * @param string               $field Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+    protected function uploadImage(Toolkit_Image_Server $is, $field)
+    {
+        return $is->imageUpload($field);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/EditPhoto.php b/Toolkit/Members/Admin/EditPhoto.php
new file mode 100644 (file)
index 0000000..24bb215
--- /dev/null
@@ -0,0 +1,387 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles the photos tab in the member record
+ *
+ * Controls setting up the add photo form if applicable, and rendering
+ * each uploaded photo edit form to edit/delete the photo.
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditPhoto.php,v 1.4 2010/07/16 20:53:36 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit/Image/Server.php
+ */
+
+
+/**
+ * The image server processing class
+ */
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Form to handle editing/deleting existing photos in members only area
+ *
+ * Handles updating caption requests for a member or to remove a
+ * photo from thier profile
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_EditPhoto extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_photos';
+
+       /**
+        * Some special forms dont utlize this stylesheet
+        * Allow classes to override this setting so it doesn't
+        * get included
+        *
+        * @var boolean
+        * @access protected
+        */
+       protected $includeContactStyleSheet = false;
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editPhoto.tpl';
+
+    /**
+     * Id of photo in db
+     * @var integer
+     * @access protected
+     */
+       protected $photoId;
+
+    /**
+     * Success message when a photo gets successfully updated
+     * @var string
+     * @access protected
+     */
+    protected $successMsg = '
+        <div id="form-success-top">
+            You successfully updated your photo.
+        </div>';
+
+    /**
+     * Any rules we want to register for this form
+     * @var array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+        * @param PDO                    $pdo         PHP Data Object
+     * @param Toolkit_Members_Photos $ll          Linked List of member photos
+        * @param string                 $formName    Form's name.
+        * @param string                 $method      (optional) Form's method
+        * @param string                 $action      (optional) Form's action.
+        * @param string                 $target      (optional) Form's target
+        * @param mixed                  $attributes  (optional) Extra attributes
+        * @param bool                   $trackSubmit (optional) Whether to track
+     *                                            if the form was submitted by
+        *                                                                                    adding a special hidden field.
+        *
+        * @access public
+        * @see    Toolkit_Members_Admin_EditPhotos
+        */
+       public function __construct(
+        PDO $pdo,
+        Toolkit_Members_Photos $ll,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh     = $pdo;
+               $this->photoId = $attributes['id'];
+        $this->photos  = $ll;
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               $photo    = $this->photos->findNode($this->photoId);
+               $defaults = array(
+                       'caption' => $photo->getCaption(),
+                       'pos'     => $photo->getPosition(),
+                       'pid'     => $photo->getId(),
+               );
+               $this->setupDefaults($defaults);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+     * @param Config_Container $c application configuration
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements(Config_Container $c)
+       {
+               $positions = range(1, $this->photos->getListSize(true));
+               $options   = array_combine($positions, $positions);
+
+        $config =& $c->getItem('section', 'photos');
+        $maxLength =& $config->getItem('directive', 'maxCaptionLength');
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $cur = $this->photos->findNode($this->photoId);
+
+               $elements[] = array(
+                       'type' => 'hidden',
+                       'req'  => false,
+                       'name' => 'pid'
+               );
+               $elements[] = array(
+                       'type' => 'text',
+                       'req'  => false,
+                       'name' => 'caption',
+            'display' => 'Image Caption',
+                       'opts' => array(
+                               'class'     => 'text',
+                               'maxlength' => $maxLength->getContent(),
+                       ),
+            'noCharLimit' => true
+               );
+               $elements[] = array(
+                       'type'    => 'select',
+                       'req'     => false,
+                       'name'    => 'pos',
+                       'display' => 'Position',
+                       'opts'    => $options,
+                       'att'     => array('id' => "pos{$cur->getPosition()}")
+               );
+               $elements[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'update',
+                       'display' => 'Update Photo',
+                       'opts'    => array('class' => 'submit')
+               );
+               $elements[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'delete',
+                       'display' => 'Delete Photo',
+                       'opts'    => array('class' => 'photoDelete')
+               );
+
+               $this->setupElements($elements);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+        * helper function to set up entire form definition
+        *
+     * @param Config_Container $c application configuration
+        *
+        * @return void
+        * @access public
+     */
+    public function configureForm(Config_Container $c)
+    {
+        $this->configureElements($c);
+        $this->configureDefaults();
+               $this->configureRules($c);
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Configures any rules we want to use on the form
+        *
+     * @param Config_Container $c application configuration
+     *
+     * @access public
+     * @return void
+     */
+       public function configureRules(Config_Container $c)
+       {
+               $r = array();
+
+        $config =& $c->getItem('section', 'photos');
+        $maxLength =& $config->getItem('directive', 'maxCaptionLength');
+
+               $r[] = array(
+                       'element'    => 'caption',
+                       'message'    => "ERROR: Please limit caption to {$maxLength->getContent()} characters!",
+                       'type'       => 'maxlength',
+                       'format'     => $maxLength->getContent(),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+       /**
+        * Handles setting up the from processing and which function to get it done
+        *
+        * @param array $values submitted values from the form
+        *
+        * @return array Submitted values from the form.
+        * @access protected
+        */
+       protected function processData($values)
+       {
+               if (!$this->getSubmitValue('delete')) {
+            unset($values['update']);
+            $photo = $this->photos->findNode($values['pid']);
+            try {
+                //     This value might be removed by JS so make sure
+                //     its in place before you try to update the positions
+                //
+                //     This is taken out in JS instead of just hiding it
+                //     b/c if the image gets dragged and repositioned,
+                //     and then the caption is updated, the old positions
+                //     in the hidden select list will override all the
+                //     newly positioned photos.
+                //     This value might be removed by JS so make sure
+                //     its in place before you try to update the positions
+                $this->dbh->beginTransaction();
+                if (isset($values['pos']) && $values['pos'] != $photo->getPosition()) {
+                    $this->photos->moveNode($photo->getId(), $values['pos']);
+                }
+                $curCaption = $photo->getCaption();
+                if ($curCaption != $values['caption']) {
+                    $photo->setCaption($values['caption']);
+                }
+                return $this->dbh->commit();
+            } catch (PDOException $e) {
+                $this->dbh->rollback();
+                return Toolkit_Common::handleError($e);
+            }
+               }
+
+        header('Location:' . $this->getAttribute('action'));
+       }
+
+       //      }}}
+
+       //      {{{ setupRenderers()
+
+    /**
+     * Set up the rendering engine we are going to use to display this form
+     *
+     * @param HTML_Template_Flexy $tEngine Templating Engine
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers(HTML_Template_Flexy $tEngine)
+       {
+               $renderer = new HTML_QuickForm_Renderer_ObjectFlexy($tEngine);
+
+               $this->accept($renderer);
+               $this->view          = new stdClass();
+               $this->view->photoId = $this->photoId;
+               $this->view->form    = $renderer->toObject();
+               $photo               = $this->photos->findNode($this->photoId);
+               $this->view->pending = $photo->getPending();
+               $this->view->img_alt = $photo->getCaption();
+               $this->view->img_src = MEMBER_PHOTOS . $photo->getImage();
+               $tEngine->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+     * @param HTML_Template_Flexy  $tEngine Templating Engine
+     * @param Cache_Lite           $cache   Caching Engine
+     * @param Toolkit_Image_Server $is      Image Server
+     * @param Config_Container     $c       Application configuration
+     *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(
+        HTML_Template_Flexy $tEngine,
+        Cache_Lite $cache,
+        Toolkit_Image_Server $is,
+        Config_Container $c
+    ) {
+               if ($this->validate()) {
+            $res = $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+            if ($this->getSubmitValue('delete')) {
+                $this->photos->removeNode($is, $c, $this->getSubmitValue('pid'));
+            }
+
+                       $this->process(array(&$this, 'processData'), $this->mergeFiles);
+               }
+
+               $this->setupRenderers($tEngine);
+
+               return $tEngine->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/EditRegion.php b/Toolkit/Members/Admin/EditRegion.php
new file mode 100644 (file)
index 0000000..7fb7dc4
--- /dev/null
@@ -0,0 +1,334 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Edit member regions
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditRegion.php,v 1.11 2010/07/14 23:27:59 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Edit Member Regions
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_EditRegion
+    extends Toolkit_Members_Auxiliary implements Toolkit_Form
+{
+       //      {{{ properties
+
+    /**
+     * Description for public
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'region';
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+       protected $formTemplate = 'editRegion.tpl';
+
+       //      }}}
+
+       //      {{{ checkRegionName()
+
+    /**
+     * Check that the region name is not in use already
+     *
+     * @param string $name name to check
+     *
+     * @return boolean if the name is valid or not
+     * @access public
+     */
+       public function checkRegionName($name)
+       {
+               try {
+                       //      If we're editing a region, they
+                       //      can save that region as its
+                       //      own name. so don't include that region
+                       //      in the check.
+                       if (isset($_GET['id'])) {
+                               $and = "AND region_id <> :rid";
+                       }
+                       $sql = "
+                               SELECT COUNT(*) AS total
+                                 FROM {$this->tableName}
+                                WHERE lower(region_name) = lower(:name)
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':name', $name, PDO::PARAM_STR);
+                       if (isset($_GET['id'])) {
+                               $stmt->bindParam(':rid', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $total);
+                       $stmt->fetch();
+
+                       return !(bool) $total;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+    /**
+     * Set up the default values for the form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+        $d = array();
+
+               if (isset($_GET['id']) && ctype_digit($_GET['id'])) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM region
+                                        WHERE region_id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':cid', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $region = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $d = array(
+                                       'region_name'   => $region['region_name'],
+                               );
+                       } catch (PDOException $e) {
+                Toolkit_Common::handleError($e);
+                       }
+               }
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+        * @param Config_Container $c Application Configuration
+        *
+     * @return void
+     * @access public
+     */
+       public function configureElements(Config_Container $c)
+       {
+        $e = array();
+
+               $singularType = $c->getItem('section', 'region type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+               $pluralType = $c->getItem('section', 'region type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'regionInfoHdr',
+            'display' => "Member {$pluralType}"
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'region_name',
+            'display' => "{$singularType} Name"
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+        * @param PDO              $dbh Database handler
+        * @param Config_Container $c   Application Configuration
+        *
+     * @return void
+     * @access public
+     */
+    public function configureForm(PDO $dbh, Config_Container $c)
+    {
+               $this->dbh = $dbh;
+        $this->configureElements($c);
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+
+               $r[] = array(
+            'element' => 'region_name',
+            'message' => 'ERROR: Name already exists!',
+            'type' => 'callback',
+            'format' => array($this, 'checkRegionName'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ deleteRegion()
+
+    /**
+     * Remove a region from the db
+     *
+     * @param integer $id region id
+     *
+     * @return boolean result of db query
+     * @access protected
+     */
+       protected function deleteRegion($id)
+       {
+        if (!ctype_digit((string)$id)) {
+            return false;
+        }
+               try {
+                       $sql = "
+                               DELETE FROM {$this->tableName}
+                                WHERE region_id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Create a new region
+     *
+     * @param array $values Submitted form values
+     *
+     * @return boolean Result of insertion into DB
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $sql = Toolkit_Common::createSQLInsert(
+            $this->tableName,
+            array_keys($values)
+        );
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form for viewing
+        *
+        * This function validates the form if needed, and if it successfully
+        * validates attempts to insert or update the data record.
+        * If it is unsuccessful, it will return an error to the user
+        * informing them of what went wrong.
+        *
+        * @return string The compiled and filled form template.
+        * @access public
+        */
+       public function toHtml()
+       {
+               //      Regions & Counties are not finished to work correctly together
+               //      at the same time.
+
+               //      currently we've just been converting regions to be counties when needed.
+               $listPage = BASE_URL . 'admin/members.php?rt=Regions&ac=listRegions';
+               return parent::toHtml($listPage);
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the data for a region
+     *
+     * @param array $values submitted form results
+     *
+     * @return boolean result of sql update query
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+               //      We aren't updating a region, we're deleting it.
+               if (array_key_exists('delete', $values)) {
+                       return $this->deleteRegion($_GET['id']);
+               }
+
+        $sql = Toolkit_Common::createSQLUpdate(
+            $this->tableName,
+            array_keys($values),
+            array('region_id = :id')
+        );
+
+        $values['id'] = $_GET['id'];
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ExportController.php b/Toolkit/Members/Admin/ExportController.php
new file mode 100644 (file)
index 0000000..a66e9db
--- /dev/null
@@ -0,0 +1,116 @@
+<?php
+/**
+ * ExportController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_ExportController
+ * 
+ * Description of Toolkit_Members_Admin_ExportController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_ExportController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    
+    /**
+     * Description for indexAction()
+     * 
+     * @return string
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $GLOBALS['styleSheets'][] = BASE_URL . 'css/contactform.css';
+
+        HTTP_Session2::set('newSearch', true);
+               $searchForm = new Toolkit_Members_Admin_AdvancedSearch(
+            'advanced-record-search',
+                       'get',
+                       BASE_URL . 'admin/members.php',
+                       '',
+                       null,
+                       true
+               );
+
+        $searchForm->configureForm($this->registry->dbh, $this->registry->config);
+
+               $this->registry->controllerObject->content =
+                       $searchForm->toHtml($this->registry->dbh, $this->registry->config);
+               if ($results = $searchForm->getSearchResults()) {
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/member-list.js';
+                       // Export File Form
+                       $export = new Toolkit_Members_Admin_ExportFileForm(
+                               'file_export',
+                               'POST',
+                               urldecode($_SERVER['REQUEST_URI']),
+                               '',
+                               null,
+                               true
+                       );
+
+                       $export->configureForm($this->registry->config);
+                       $this->registry->controllerObject->content .= $export->toHtml(
+                               $results,
+                               $this->registry->dbh,
+                               $this->registry->config
+                       );
+
+                       $membersList = new Toolkit_Members_Admin_AdvancedSearchDataGrid(
+                               $this->registry->dbh,
+                               50
+                       );
+                       if (   isset($_GET['d'])
+                               && $_GET['d'] == 't'
+                               && $memberId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
+                       ) {
+                               $membersList->removeMember(
+                                       $memberId,
+                                       new Toolkit_Image_Server()
+                               );
+                       }
+                       $membersList->setQuery($results);
+                       $membersList->setDefaultSort(array('sort_field' => 'ASC'));
+
+                       //  rendering engine to use
+                       $rEngine = new Structures_DataGrid_Renderer_Flexy();
+                       $rEngine->setContainer($this->registry->tEngine);
+
+                       $this->registry->controllerObject->content .=
+                               $membersList->toHtml($rEngine, 'listMembers.tpl');
+               }
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/ExportFileForm.php b/Toolkit/Members/Admin/ExportFileForm.php
new file mode 100644 (file)
index 0000000..d061632
--- /dev/null
@@ -0,0 +1,207 @@
+<?php
+
+/**
+ * Admin search functionality for memberdb
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ExportFileForm.php,v 1.8 2010/07/14 23:27:59 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form to search the members database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ExportFileForm
+    extends Toolkit_FormBuilder
+{
+    // {{{ configureConstants()
+
+    /**
+     * Form constant definitions
+     *
+     * @return void
+     * @access public
+     */
+    public function configureConstants()
+    {
+        $c = array(
+            'rt' => $_GET['rt'],
+            'ac' => $_GET['ac'],
+        );
+
+        $this->setupConstants($c);
+    }
+
+    // }}}
+    // {{{ configureDefaults()
+
+    /**
+     * Form default value definitions
+     *
+     * @return void
+     * @access public
+     */
+    public function configureDefaults()
+    {
+        $d = array('file_type' => 'csv');
+
+        $this->setupDefaults($d);
+    }
+
+    // }}}
+    // {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements(Config_Container $c)
+    {
+        $e = array();
+
+        //  get reference to [listing type] section of config file
+        $pluralType = $c->getItem('section', 'listing type')
+            ->getItem('directive', 'plural')
+            ->getContent();
+
+        //     All Grouped Elements are created here.
+        //     All Elements are created here.  This includes group element definitions.
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'rt'
+        );
+        $e[]   = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'ac'
+        );
+        $e[]   = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'file_type',
+            'display' => 'CSV File Type',
+            'opts'    => array(
+                'csv'  => 'CSV (Comma Seperated)',
+                'tab'  => 'Tab Seperated',
+                'pipe' => 'Pipe Seperated',
+            )
+        );
+        $e[]   = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit',
+            'display' => 'Export ' . $pluralType
+        );
+
+        $this->setupElements($e);
+    }
+
+    // }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(Config_Container $c)
+    {
+        $this->configureElements($c);
+        $this->configureConstants();
+        $this->configureDefaults();
+        $this->configureRules();
+    }
+
+    //  }}}
+    // {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules()
+    {
+        $r = array();
+
+        $this->setupRules($r);
+    }
+
+    // }}}
+    // {{{     setupRenderers()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+    protected function setupRenderers()
+    {
+        parent::setupRenderers();
+        $renderer = & $this->defaultRenderer();
+        $tpl      = '<tr align="center"><td colspan="2">{element}</td></tr>';
+        $renderer->setElementTemplate($tpl, 'submit');
+    }
+
+    //  @codeCoverageIgnoreEnd
+    // }}}
+    // {{{     toHtml()
+
+    /**
+     * Call the rendering function to get the form in a string. If the form is
+     * submitting and validated it sets the sorting fields and calls exportAsFile
+     * method and exits
+     *
+     * @param array            $results Search Results
+     * @param PDO              $dbh     Database Connection
+     * @param Config_Container $c       Config Container (members)
+     *
+     * @access protected
+     * @return string $output The Form to be rendered or success msg.
+     */
+    public function toHtml(array $results, PDO $dbh, Config_Container $c)
+    {
+        $this->setupRenderers();
+
+        if ($this->validate()) {
+            $export = new Toolkit_Members_Admin_ExportMembers($dbh);
+            $export->setConfig($c);
+            $export->setQuery($results);
+            $export->setDefaultSort(
+                array(
+                    'sort2_field' => 'ASC',
+                    'sort_field'  => 'ASC'
+                )
+            );
+            $export->exportAsFile();
+        }
+
+        return parent::toHTML();
+    }
+
+    // }}}
+}
diff --git a/Toolkit/Members/Admin/ExportMembers.php b/Toolkit/Members/Admin/ExportMembers.php
new file mode 100644 (file)
index 0000000..0513809
--- /dev/null
@@ -0,0 +1,517 @@
+<?php
+
+/**
+ * ExportMembers.php
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $Id:$
+ * @link      <>
+ */
+
+/**
+ * using our extension of the Pear Structures Datagrid set the
+ * renderer to CSV so we can send it out as a file.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: @package_version@
+ * @link      <>
+ */
+class Toolkit_Members_Admin_ExportMembers
+    extends Toolkit_DataGridBuilder
+{
+
+    /**
+     * Options to pass to DataGrid
+     *
+     * @var    array
+     * @access protected
+     */
+    protected $options;
+
+    /**
+     * Rendering options for DataGrid
+     *
+     * @var    array
+     * @access protected
+     */
+    protected $rendererOptions = array(
+        'buildFooter'       => true,
+        'buildHeader'       => true,
+        'delimiter'         => ',',
+        'enclosure'         => '"',
+        'encoding'          => 'ISO-8859-1',
+        'filename'          => false,
+        'fillWithEmpytRows' => false,
+        'lineBreak'         => "\n",
+        'numberAlign'       => true,
+        'saveToFile'        => false,
+        'useQuotes'         => true,
+    );
+
+    /**
+     * SQL query used to obtain the DataGrid
+     *
+     * @var    unknown
+     * @access protected
+     */
+    protected $sql;
+
+    /**
+     * How many records must exist in the Datagrid before the sort form shows up
+     *
+     * @var    integer
+     * @access protected
+     */
+    protected $sortableAfter = 10;
+
+    /**
+     * The HTML table id of the DataGrid
+     *
+     * @var    string
+     * @access protected
+     */
+    protected $tableId = 'dataGrid';
+
+    /**
+     * The HTML class name of the DataGrid
+     *
+     * @var    string
+     * @access protected
+     */
+    protected $tableClass = 'dataGrid';
+
+    /**
+     * The HTML id of the DataGrid sorting form (when present)
+     *
+     * @var    string
+     * @access protected
+     */
+    protected $sortFormId = 'gridSorter';
+
+    /**
+     * Message to display to users if no records were found
+     *
+     * @var            String
+     * @access Protected
+     * @see            Toolkit_DataGridBuilder::setNoRecordMessage()
+     */
+    protected $noRecMessage = 'No Records';
+
+    /**
+     * Configures the columns (fields) that will be used in our datagrid renderer.
+     *
+     * @return void
+     * @access public
+     */
+    protected function configureColumns()
+    {
+        //  get reference to [controlledCities] section of config file
+        $ctrlCities = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'controlledCities')
+            ->getContent();
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Trail Name',
+                'member_name'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Active',
+                'active'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Street Address',
+                'street'
+            )
+        );
+
+        if ($ctrlCities) {
+            $this->addColumn(
+                new Structures_DataGrid_Column(
+                    'City',
+                    'city_name'
+                )
+            );
+        } else {
+            $this->addColumn(
+                new Structures_DataGrid_Column(
+                    'City',
+                    'city'
+                )
+            );
+        }
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'County',
+                'county_name'
+            )
+        );
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Region',
+                'region_name'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'State',
+                'state_name'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Zip',
+                'zip'
+            )
+        );
+
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Phone',
+//                'phone'
+//            )
+//        );
+//
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Fax',
+//                'fax'
+//            )
+//        );
+
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Toll Free Phone Number',
+//                'toll_free'
+//            )
+//        );
+//
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Website Address',
+//                'url'
+//            )
+//        );
+
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Primary Contact First Name',
+//                'primary_contact_fname'
+//            )
+//        );
+//
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Primary Contact Last Name',
+//                'primary_contact_lname'
+//            )
+//        );
+
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Primary Contact Email',
+//                'process_email'
+//            )
+//        );
+//
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Email on Website',
+//                'member_contact_email'
+//            )
+//        );
+
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Mailing Street Address',
+//                'mailing_address',
+//                null,
+//                null,
+//                null,
+//                array($this, 'mailingAddress')
+//            )
+//        );
+//
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Mailing City',
+//                'mailing_city',
+//                null,
+//                null,
+//                null,
+//                array($this, 'mailingCity')
+//            )
+//        );
+//
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Mailing State',
+//                'mailing_state_name',
+//                null,
+//                null,
+//                null,
+//                array($this, 'mailingState')
+//            )
+//        );
+
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Mailing Zip',
+//                'mailing_zip',
+//                null,
+//                null,
+//                null,
+//                array($this, 'mailingZip')
+//            )
+//        );
+
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Join Date',
+//                'join_date'
+//            )
+//        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Create Date',
+                'create_date'
+            )
+        );
+//        $this->addColumn(
+//            new Structures_DataGrid_Column(
+//                'Member Contact',
+//                'sort2_field',
+//                null,
+//                null,
+//                null,
+//                array($this, 'isMemberContact')
+//            )
+//        );
+    }
+
+    /**
+     * Returns true if member contact field (sort2_field) is set
+     *
+     * @param array $data Array of data from structure datagrid
+     *
+     * @return string
+     * @access public
+     */
+    public function isMemberContact($data)
+    {
+        return
+            ($data['record']['sort2_field'])
+            ? 'Yes'
+            : '';
+    }
+
+
+    /**
+     * Returns mailing Address
+     *
+     * @param array $data Array of data from structure datagrid
+     *
+     * @return string
+     * @access public
+     */
+    public function mailingAddress($data)
+    {
+        return
+            ($data['record']['mailing_address'])
+            ? $data['record']['mailing_address']
+            : $data['record']['street'];
+    }
+
+    /**
+     * Returns mailing City
+     *
+     * @param array $data Array of data from structure datagrid
+     *
+     * @return string
+     * @access public
+     */
+    public function mailingCity($data)
+    {
+        if ($data['record']['mailing_city'] != '') {
+            $city = $data['record']['mailing_city'];
+        } else if ($data['record']['city_name'] != '') {
+            $city = $data['record']['city_name'];
+        } else {
+            $city = '';
+        }
+        return $city;
+    }
+
+    /**
+     * Returns mailing State
+     *
+     * @param array $data Array of data from structure datagrid
+     *
+     * @return string
+     * @access public
+     */
+    public function mailingState($data)
+    {
+        return
+            ($data['record']['mailing_state_name'])
+            ? $data['record']['mailing_state_name']
+            : $data['record']['state_name'];
+    }
+
+    /**
+     * Returns the mailing zipcode
+     *
+     * @param array $data Array of data from structure datagrid
+     *
+     * @return string
+     * @access public
+     */
+    public function mailingZip($data)
+    {
+        return
+            ($data['record']['mailing_zip'])
+            ? $data['record']['mailing_zip']
+            : $data['record']['zip'];
+    }
+
+    /**
+     * throws out headers to the browser so the file can be downloaded
+     * there's a case for IE browsers which may change in future depending on
+     * Microsoft Whim:(
+     *
+     * @access public
+     * @return void
+     */
+    public function exportAsFile()
+    {
+        // if the file is other than csv then set delimeter
+        if ($_REQUEST['file_type']) {
+            switch ($_REQUEST['file_type']) {
+            case "pipe":
+                $delimiter = "|";
+                break;
+            case "tab":
+                $delimiter = "\t";
+                break;
+            default:
+                $delimiter = ",";
+                break;
+            }
+            $this->rendererOptions['delimiter'] = $delimiter;
+        }
+        $fileOut   = $this->toCSV();
+        if (ini_get('zlib.output_compression')) {
+            ini_set('zlib.output_compression', 'Off');
+        }
+        header("Content-Type: application/force-download\n");
+        /* Correction for the stupid MSIE thing */
+        if (strstr(getenv('HTTP_USER_AGENT'), 'MSIE')) {
+            header("Content-Disposition: inline; filename=\"Member-Export.csv\"");
+        } else {
+            header("Content-Disposition: attachment; filename=\"Member-Export.csv\"");
+        }
+        echo $fileOut;
+        exit();
+    }
+
+    /**
+     * set the configuration object
+     *
+     * @param Config_Container $c App configuration
+     *
+     * @return void
+     * @access public
+     */
+    function setConfig(Config_Container $c)
+    {
+        $this->config = $c;
+    }
+
+    /**
+     * Sets the sql query to use in the DataGrid to get the results
+     *
+     * @param array $ids Array of member id's
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery(array $ids)
+    {
+        $memberIds = implode(', ', $ids);
+        $sql       = "
+                       SELECT m.*,
+                   LOWER(m.member_name) AS sort_field,
+                   c.city_name,
+                              s.state_name,
+                   ct.county_name,
+                   r.region_name,
+                   0 as sort2_field
+              FROM member m
+              LEFT JOIN city c ON m.city_id   = c.city_id
+              LEFT JOIN county ct ON m.county = ct.county_id
+              LEFT JOIN region r ON m.region  = r.region_id
+              LEFT JOIN state s ON m.state_id = s.state_id
+             WHERE member_id IN ($memberIds)";
+
+        parent::setQuery($sql);
+    }
+
+    /**
+     * returns a CSV file of the datagrid
+     *
+     * @return string|boolean
+     * @access public
+     * @throws PEAR_Error
+     */
+    public function toCSV()
+    {
+        $this->configureColumns();
+        $members = array();
+        try {
+            $dbh  = Toolkit_Database::getInstance();
+            $stmt = $dbh->query($this->sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $members[] = $row;
+            }
+            $bind      = $this->bind($members, $this->options, 'Array');
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+
+        if (PEAR::isError($bind)) {
+            return Toolkit_Common::handleError($bind);
+        } elseif (($recCount = $this->getRecordCount()) > 0) {
+            $this->setRendererOptions($this->rendererOptions);
+            $csv = $this->getOutput(DATAGRID_RENDER_CSV, $this->rendererOptions);
+            if (PEAR::isError($gridBody)) {
+                return Toolkit_Common::handleError($gridBody);
+            }
+            return $csv;
+        } else {
+            return false;
+        }
+    }
+
+}
diff --git a/Toolkit/Members/Admin/IndexController.php b/Toolkit/Members/Admin/IndexController.php
new file mode 100644 (file)
index 0000000..3b02eb6
--- /dev/null
@@ -0,0 +1,93 @@
+<?php
+/**
+ * IndexController.php
+ * 
+ * PHP versions 4 and 5
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Newsletters.php,v 1.9 2009/09/16 19:00:58 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Admin_IndexController
+ * 
+ * Description for Toolkit_Members_Admin_IndexController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_IndexController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+
+    /**
+     * Main action for controller. Runs admin template, list out all regions
+     * 
+     * @return string
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $GLOBALS['styleSheets'][]   = BASE_URL . 'css/contactform.css';
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/member-list.js';
+
+        HTTP_Session2::set('newSearch', true);
+               $search = new Toolkit_Members_Admin_BasicSearch(
+            'record_search',
+                       'get',
+                       BASE_URL . 'admin/members.php',
+                       '',
+                       null,
+                       true
+               );
+
+        $search->configureForm($this->registry->dbh, $this->registry->config);
+
+               $membersList = new Toolkit_Members_Admin_ListMembers(
+                       $this->registry->dbh,
+                       50
+               );
+               $memberId     = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
+               $deleteMember = filter_input(INPUT_GET, 'd', FILTER_SANITIZE_STRING);
+
+               if ($memberId && $deleteMember == 't') {
+            $membersList->removeMember($memberId, new Toolkit_Image_Server());
+        }
+
+        $membersList->setQuery($this->registry->config);
+        $membersList->setDefaultSort(array('sort_field' => 'ASC'));
+
+        //  rendering engine to use
+        $rEngine = new Structures_DataGrid_Renderer_Flexy();
+        $rEngine->setContainer($this->registry->tEngine);
+
+               $this->registry->controllerObject->content =
+                       $search->toHtml() .
+                   $membersList->toHtml($rEngine, 'listMembers.tpl');
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/InvoicingController.php b/Toolkit/Members/Admin/InvoicingController.php
new file mode 100644 (file)
index 0000000..1d9f3f4
--- /dev/null
@@ -0,0 +1,245 @@
+<?php
+/**
+ * InvoicingController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_InvoicingController
+ * 
+ * Description of Toolkit_Members_Admin_InvoicingController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_InvoicingController
+       extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+    
+    /**
+     * Description of createInvoicesAction()
+     * 
+     * @return mixed
+     * @access public 
+     */
+    public function createInvoicesAction()
+    {
+        $dbh = Toolkit_Database::getInstance();
+        $rt = filter_input(
+            INPUT_GET,
+            'rt',
+            FILTER_SANITIZE_STRING
+        );
+        $ac = filter_input(
+            INPUT_GET,
+            'ac',
+            FILTER_SANITIZE_STRING
+        );
+        $tab = filter_input(
+            INPUT_GET,
+            'tab',
+            FILTER_SANITIZE_STRING
+        );
+        $filterForm = new Toolkit_Members_Billing_InvoiceFilterForm(
+            'filter-form',
+            'post',
+            BASE_URL 
+            . "admin/members.php?rt={$rt}&ac={$ac}&tab={$tab}"
+        );
+        $filterForm->configureForm();
+        if ($_POST['submit']) {
+            $mc  = new Toolkit_Members_Billing_Invoices();
+            $out = $mc->createInvoices($dbh);
+        } else {
+            $mc  = new Toolkit_Members_Billing_MemberLists($dbh);
+            $out = $filterForm->toHTML() . $mc->getNeededInvoices();
+        }
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     * Description of createLabelsAction()
+     * 
+     * @return string
+     * @access public 
+     */
+    public function createLabelsAction()
+    {
+        $dbh = Toolkit_Database::getInstance();
+        $rt = filter_input(
+            INPUT_GET,
+            'rt',
+            FILTER_SANITIZE_STRING
+        );
+        $ac = filter_input(
+            INPUT_GET,
+            'ac',
+            FILTER_SANITIZE_STRING
+        );
+        $tab = filter_input(
+            INPUT_GET,
+            'tab',
+            FILTER_SANITIZE_STRING
+        );
+        $filterForm = new Toolkit_Members_Billing_InvoiceFilterForm(
+            'filter-form',
+            'post',
+            BASE_URL 
+            . "admin/members.php?rt={$rt}&ac={$ac}&tab={$tab}"
+        );
+        $filterForm->configureForm();
+        if ($_POST['submit']) {
+            $out = '<pre>'.print_r($_REQUEST, true).'</pre>';
+            $label = new Toolkit_Members_Billing_MailingLabelPdf();
+            $out = $label->printMailingLabels($dbh);
+        } else {
+            $mc  = new Toolkit_Members_Billing_MemberLists($dbh);
+            $out = $filterForm->toHTML() . $mc->getMailableInvoices();
+        }
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     * Runs admin template, list out all regions
+     * 
+     * @param string $html Description of $html
+     * 
+     * @return string 
+     */
+    protected function getPageLayout($html)
+    {
+        $GLOBALS['styleSheets'][]
+            = BASE_URL . 'Toolkit/Members/Billing/billing.css';
+        $this->registry->controllerObject->content = $html;
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+    }
+    
+    /**
+     * Description of printInvoicesAction
+     * 
+     * @return string
+     * @access public 
+     */
+    public function printInvoicesAction()
+    {
+        $dbh = Toolkit_Database::getInstance();
+        $rt = filter_input(
+            INPUT_GET,
+            'rt',
+            FILTER_SANITIZE_STRING
+        );
+        $ac = filter_input(
+            INPUT_GET,
+            'ac',
+            FILTER_SANITIZE_STRING
+        );
+        $tab = filter_input(
+            INPUT_GET,
+            'tab',
+            FILTER_SANITIZE_STRING
+        );
+        $filterForm = new Toolkit_Members_Billing_InvoiceFilterForm(
+            'filter-form',
+            'post',
+            BASE_URL 
+            . "admin/members.php?rt={$rt}&ac={$ac}&tab={$tab}"
+        );
+        $filterForm->configureForm();
+        if ($_POST['submit']) {
+            $inv = new Toolkit_Members_Billing_PrintInvoices();
+            $ret = $inv->printInvoices($dbh);
+            if (!$ret) {
+                $out = '<p>Nothing to print</p>';
+            }
+        } else {
+            $mc  = new Toolkit_Members_Billing_MemberLists($dbh);
+            $out = $filterForm->toHTML() . $mc->getPrintableInvoices();
+        }
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     * Description of indexAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function indexAction()
+       {
+        $mc  = new Toolkit_Members_Billing_MemberLists(
+            Toolkit_Database::getInstance()
+        );
+        $html = $mc->getOpenAccounts();
+               return $this->getPageLayout($html);
+       }
+       
+    /**
+     * Description of sendEmailAction()
+     * 
+     * @return string
+     * @access public 
+     */
+    public function sendEmailAction()
+    {
+        $dbh = Toolkit_Database::getInstance();
+        $rt = filter_input(
+            INPUT_GET,
+            'rt',
+            FILTER_SANITIZE_STRING
+        );
+        $ac = filter_input(
+            INPUT_GET,
+            'ac',
+            FILTER_SANITIZE_STRING
+        );
+        $tab = filter_input(
+            INPUT_GET,
+            'tab',
+            FILTER_SANITIZE_STRING
+        );
+        $filterForm = new Toolkit_Members_Billing_InvoiceFilterForm(
+            'filter-form',
+            'post',
+            BASE_URL 
+            . "admin/members.php?rt={$rt}&ac={$ac}&tab={$tab}"
+        );
+        $filterForm->configureForm();
+        if ($_POST['submit']) {
+            $emailInvoice = new Toolkit_Members_Billing_EmailInvoices();
+            $ret = $emailInvoice->emailInvoices($dbh);
+            if ($ret) {
+                $out = '<p>Emails sent to members</p>';
+            } else {
+                $out = '<p>Nothing to email</p>';
+            }
+        } else {
+            $mc  = new Toolkit_Members_Billing_MemberLists($dbh);
+            $out = $filterForm->toHTML() . $mc->getEmailableInvoices();
+        }
+        return $this->getPageLayout($out);
+    }
+}
diff --git a/Toolkit/Members/Admin/ListAmenities.php b/Toolkit/Members/Admin/ListAmenities.php
new file mode 100644 (file)
index 0000000..e6d48be
--- /dev/null
@@ -0,0 +1,133 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * List the amenities available for members
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ListAmenities.php,v 1.11 2010/01/26 19:46:15 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * List the amenities available for members
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ListAmenities
+{
+       //      {{{ properties
+
+       /**
+        * Database Handler
+        *
+        * @var object
+        * @access protected
+        */
+       protected $dbh;
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'amenity';
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access private
+        */
+       private $_template = 'listAmenities.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Constructor
+     *
+     * @param PDO $pdo PHP Data Object
+        *
+        * @access public
+        */
+       public function __construct(PDO $pdo)
+       {
+               $this->dbh = $pdo;
+
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ _getAmenities()
+
+    /**
+     * Get the amenities
+     *
+     * @return array regions stored in the db
+     * @access private
+     */
+       private function _getAmenities()
+       {
+               try {
+                       $amenities = array();
+                       $sql = "
+                               SELECT *
+                                 FROM {$this->tableName}
+                                ORDER BY amenity_name";
+
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $amenities[$row['amenity_id']] = $row['amenity_name'];
+                       }
+
+                       return $amenities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ renderAmenities()
+
+    /**
+     * Render the output
+     *
+     * @return html page
+     * @access public
+     */
+       public function renderAmenities()
+       {
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->amenities = $this->_getAmenities();
+
+               $template->compile($this->_template);
+               return $template->bufferedOutputObject($page);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ListCategories.php b/Toolkit/Members/Admin/ListCategories.php
new file mode 100644 (file)
index 0000000..cf04cb3
--- /dev/null
@@ -0,0 +1,231 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * List the categories available for members
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ListCategories.php,v 1.15 2010/08/09 16:55:44 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * List the categories available for members
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ListCategories
+{
+       //      {{{ properties
+
+       /**
+        * Database Handler
+        *
+        * @var object
+        * @access public
+        */
+       public $dbh;
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'category';
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access private
+        */
+       private $_template = 'listCategories.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Constructor
+     *
+     * @param PDO $pdo PHP Data Object
+        *
+        * @access public
+        */
+       public function __construct(PDO $pdo)
+       {
+               $this->dbh = $pdo;
+
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ _getCategoryList()
+
+    /**
+     * Gets a list of all the available categories in a UL list
+     *
+     * @return string  html list of categories
+     * @access private
+     */
+       private function _getCategoryList()
+       {
+               $tree = Toolkit_Common::getHierarchicalTreeStructure(
+            $this->dbh,
+            'category',
+            'category_id',
+            'parent_id',
+            'name'
+        );
+
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM {$this->tableName}
+                                WHERE category_id = :catid";
+
+                       $stmt = $this->dbh->prepare($sql);
+
+                       reset($tree);
+                       $prevLevel = 1;
+                       while (list($catid, $level) = each($tree)) {
+                               $stmt->bindParam(':catid', $catid, PDO::PARAM_INT);
+                               $stmt->execute();
+                               $row = $stmt->fetch();
+
+                               if ($level == $prevLevel) {
+                                       $list .= $this->_createNode($row, $list);
+                               } elseif ($level > $prevLevel) {
+                                       $list .= $this->_createNewLvlNode($row);
+                               } elseif ($level < $prevLevel) {
+                                       while ($prevLevel-- != $level) {
+                                               $list .= $this->_createLastLvlNode($row);
+                                       }
+                               }
+
+                               $prevLevel = $level;
+                       }
+
+                       while ($prevLevel-- > 1) {
+                               $list .= "</li>\n</ul>\n";
+                       }
+                       $list .= "</li>\n";
+
+                       return "<ul>\n$list</ul>";
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _createNode()
+
+    /**
+     * Create a LI node for the category list
+     *
+     * Long description (if any) ...
+     *
+     * @param array   $cat  Category data
+     * @param string  $list Current UL list being built
+     *
+     * @return string  current list plus new appended LI node
+     * @access private
+     */
+       private function _createNode(array $cat, $list)
+       {
+               //      check for closing node.
+               if (strlen($list) > 0) {
+                       if (substr_compare($list, '</a>', -5, 4) == 0) {
+                               $node = "</li>\n";
+                       }
+               }
+               $url = BASE_URL . "admin/members.php?rt=Categories&amp;ac=editCategory&amp;id={$cat['category_id']}";
+               $node .= "\t<li id=\"predef_{$cat['category_id']}\">\n";
+               $node .= "\t\t<a href=\"$url\">{$cat['name']}</a>\n";
+
+               return $node;
+       }
+
+       //      }}}
+       //      {{{     _createNextLvlNode()
+
+    /**
+     * Create a new level for the UL list
+     *
+     * @param array $cat Category data
+     *
+     * @return string  current UL list plus new level
+     * @access private
+     */
+       private function _createNewLvlNode(array $cat)
+       {
+               $node  = "\t\t<ul>\n";
+               $node .= $this->_createNode($cat, $node);
+
+               return $node;
+       }
+
+       //      }}}
+       //      {{{     _createLastLvlNode()
+
+    /**
+     * Create the closing tags of the current LI node and then append a new node
+     *
+     * @param array $cat Category data
+     *
+     * @return string  current UL list plus new node
+     * @access private
+     */
+       private function _createLastLvlNode(array $cat)
+       {
+               $node  = "</li>\n</ul>\n</li>\n";
+               $node .= $this->_createNode($cat, $node);
+
+               return $node;
+       }
+
+       //      }}}
+       //      {{{ renderCategories()
+
+    /**
+     * Render the output
+     *
+     * @return html page
+     * @access public
+     */
+       public function renderCategories()
+       {
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->baseUrl = BASE_URL;
+               $page->tree = $this->_getCategoryList();
+
+               $template->compile($this->_template);
+               return $template->bufferedOutputObject($page);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ListCities.php b/Toolkit/Members/Admin/ListCities.php
new file mode 100644 (file)
index 0000000..68c1469
--- /dev/null
@@ -0,0 +1,136 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * List the cities available for members
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ListCities.php,v 1.9 2010/01/26 19:46:47 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * List the cities available for members
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ListCities
+{
+       //      {{{ properties
+
+       /**
+        * Database Handler
+        *
+        * @var object
+        * @access protected
+        */
+       public $dbh;
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'city';
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access private
+        */
+       private $_template = 'listCities.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Constructor
+        *
+     * @param PDO $pdo PHP Data Object
+     *
+        * @access public
+        */
+       public function __construct(PDO $pdo)
+       {
+               $this->dbh = $pdo;
+
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ _getCities()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return array   Return description (if any) ...
+     * @access private
+     */
+       private function _getCities()
+       {
+               try {
+                       $cities = array();
+                       $sql = "
+                               SELECT *
+                                 FROM {$this->tableName}
+                                ORDER BY city_name";
+
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $cities[$row['city_id']] = $row['city_name'];
+                       }
+
+                       return $cities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ renderCities()
+
+    /**
+     * Render the output
+     *
+     * @return html page
+     * @access public
+     */
+       public function renderCities()
+       {
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->cities  = $this->_getCities();
+
+               $template->compile($this->_template);
+               return $template->bufferedOutputObject($page);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ListCounties.php b/Toolkit/Members/Admin/ListCounties.php
new file mode 100644 (file)
index 0000000..c4f7386
--- /dev/null
@@ -0,0 +1,132 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * List the regions available for members
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ListRegions.php,v 1.9 2009/12/29 14:14:11 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * List the regions available for members
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ListCounties
+{
+       //      {{{ properties
+
+       /**
+        * Database Handler
+        *
+        * @var object
+        * @access protected
+        */
+       protected $dbh;
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'county';
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access private
+        */
+       private $_template = 'listCounties.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO $pdo PHP Data Object
+     *
+        * @access public
+        */
+       public function __construct(PDO $pdo)
+       {
+               $this->dbh = $pdo;
+
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ _getRegions()
+
+    /**
+     * Get the regions
+     *
+     * @return array regions stored in the db
+     * @access private
+     */
+       private function _getCounties()
+       {
+               try {
+                       $counties = array();
+                       $sql = "
+                               SELECT *
+                                 FROM {$this->tableName}
+                                ORDER BY county_name";
+
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $counties[$row['county_id']] = $row['county_name'];
+                       }
+
+                       return $counties;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ renderRegions()
+
+    /**
+     * Render the output
+     *
+     * @return html page
+     * @access public
+     */
+       public function renderCounties()
+       {
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->counties = $this->_getCounties();
+
+               $template->compile($this->_template);
+               return $template->bufferedOutputObject($page);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/ListHtmlEmails.php b/Toolkit/Members/Admin/ListHtmlEmails.php
new file mode 100644 (file)
index 0000000..9765561
--- /dev/null
@@ -0,0 +1,141 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * List the amenities available for members
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ListHtmlEmails.php,v 1.4 2010/01/28 16:26:52 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * List the amenities available for members
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ListHtmlEmails
+{
+       //      {{{ properties
+
+       /**
+        * Database Handler
+        *
+        * @var object
+        * @access protected
+        */
+       protected $dbh;
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_newsletters';
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access private
+        */
+       private $_template = 'listHtmlEmails.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Constructor
+     *
+     * @param PDO $pdo PHP Data Object
+        *
+        * @access public
+        */
+       public function __construct(PDO $pdo)
+       {
+               $this->dbh = $pdo;
+
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ _getNewsletters()
+
+    /**
+     * Get the newsletters
+     * 
+     * @return array regions stored in the db
+     * @access private
+     */
+       private function _getNewsletters()
+       {
+               try {
+                       $newsletters = array();
+            $where = ($_REQUEST['archived']) ? "WHERE archived = 't'": "WHERE (archived = 'f' OR archived IS NULL)";
+                       $sql = "
+                               SELECT *
+                                 FROM {$this->tableName}
+            $where
+                                ORDER BY last_update DESC";
+
+                       foreach ($this->dbh->query($sql) as $row) {
+                $newsletters[] = array(
+                    'id'          => $row['id'],
+                    'subject'     => $row['subject'],
+                    'last_update' => $row['last_update'],
+                    'archived'    => $row['archived']
+                );
+                       }
+
+                       return $newsletters;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ renderHtmlEmails()
+
+    /**
+     * Render the output
+     *
+     * @return html page
+     * @access public
+     */
+       public function renderHtmlEmails()
+       {
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->newsletters = $this->_getNewsletters();
+        $page->title = ($_REQUEST['archived']) ? "Archived HTML Emails": "HTML Emails";
+
+               $template->compile($this->_template);
+               return $template->bufferedOutputObject($page);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ListMembers.php b/Toolkit/Members/Admin/ListMembers.php
new file mode 100644 (file)
index 0000000..1250597
--- /dev/null
@@ -0,0 +1,361 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @release  CVS: $Id: ListMembers.php,v 1.32 2010/07/19 20:35:14 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * List the members in the database in a datagrid
+ *
+ * Handles listing of the members in the memberDB, pagnation, and sorting.
+ * Also controls the resulting number of members that are rendered on the page.
+ *
+ * @category  MembersDB
+ * @package      Toolkit_Members
+ * @author       Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2008 Gaslight media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ */
+class Toolkit_Members_Admin_ListMembers extends Toolkit_FlexyDataGridBuilder
+{
+       //      {{{ configureColumns()
+
+       /**
+        * Configures the columns (fields) that will be used in our datagrid renderer.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureColumns()
+       {
+               $memberId = new Structures_DataGrid_Column(
+                   'Created',
+            'member_id',
+            'member_id',
+            null,
+            null,
+            array(&$this, 'url')
+        );
+               $this->addColumn($memberId);
+
+               $delUrl = new Structures_DataGrid_Column(
+            'Delete',
+            'del_url',
+            'del_url',
+            null,
+            null,
+            array(&$this, 'delUrl')
+        );
+               $this->addColumn($delUrl);
+
+               $name = new Structures_DataGrid_Column(
+            'Member Name',
+            'member_name',
+            'member_name'
+           );
+               $this->addColumn($name);
+
+               $phone = new Structures_DataGrid_Column(
+            'Member Phone',
+            'phone',
+            'phone'
+           );
+               $this->addColumn($phone);
+
+               $email = new Structures_DataGrid_Column(
+            'Contact Email',
+            'member_contact_email',
+            'member_contact_email'
+           );
+               $this->addColumn($email);
+       }
+
+       //      }}}
+
+       //      {{{ delUrl()
+
+       /**
+        * Returns the url to delete a member.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the url to get to delete the member
+        *
+        * @param array $data The row from the db record
+        *
+        * @return string The url to the edit member page.
+        * @access public
+        */
+       public function delUrl($data)
+       {
+               $queryString = urldecode($_SERVER['QUERY_STRING']);
+               extract($data['record']);
+               $format = BASE_URL . 'admin/members.php?%s&d=t&id=%s';
+               return sprintf(
+                       $format,
+                       $queryString,
+                       $member_id
+               );
+       }
+
+       //      }}}
+
+    //  {{{ removeMember()
+
+    /**
+     * Remove a member from the list / database
+     *
+     * @param integer                     $mid Member id to remove
+        * @param Toolkit_Image_Server $is  Image Server
+     *
+     * @return void
+     * @access public
+     * @throws PEAR_Error
+     */
+    public function removeMember($mid, Toolkit_Image_Server $is)
+    {
+        try {
+                       $sql = "
+                SELECT *
+                  FROM member_photos
+                 WHERE member_id = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $is->imageDelete($row['image']);
+                       }
+
+            $sql  = "
+                DELETE FROM member
+                 WHERE member_id = :id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $mid, PDO::PARAM_INT);
+            $stmt->execute();
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+    //  {{{ setControlObject()
+
+    /**
+     * set the control object to use with the datagrid
+     *
+     * @return void
+     * @access protected
+     * @throws PEAR_Error
+     */
+    protected function setControlObject()
+    {
+        try {
+            $letters = array();
+
+            $sql = "
+                SELECT substr(upper(member_name), 1, 1) AS letter
+                  FROM member
+                                WHERE new_member = CAST(0 AS BOOLEAN)
+                 GROUP BY letter
+                 ORDER BY letter";
+
+            foreach ($this->dbh->query($sql) as $row) {
+                $letters[$row['letter']] = $row['letter'];
+            }
+
+                       $addNumeric = false;
+                       while ($i = current($letters)) {
+                               if (is_numeric($i)) {
+                                       $addNumeric = true;
+                                       unset($letters[key($letters)]);
+                               } else {
+                                       break;
+                               }
+                       }
+
+                       if ($addNumeric) {
+                               array_unshift($letters, '0-9');
+                       }
+
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+
+        //  We only need to show the links of alphabet if we have more than
+        //  one letter to display.
+        if (count($letters) > 1) {
+            foreach ($_GET as $k => $v) {
+                if ($k != 'alpha') {
+                    if (is_array($v)) {
+                        foreach ($v as $i => $j) {
+                            $queryString .= $k . '[' . $i . ']=' . $j . '&';
+                        }
+                    } else {
+                        $queryString .= "$k=$v&";
+                    }
+                }
+            }
+            $links['All']['url'] = BASE_URL . "admin/members.php?{$queryString}";
+            $links['All']['class'] = empty($_GET['alpha']) ? 'curr' : null;
+            foreach ($letters as $v) {
+                $links[$v]['url'] = BASE_URL . "admin/members.php?{$queryString}alpha=$v";
+                if ($_GET['alpha'] == $v) {
+                    $links[$v]['class'] = 'curr';
+                }
+            }
+            $this->ctrlObj['letters'] = $links;
+        }
+    }
+
+    //  }}}
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param Config_Container $c Configuration container
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery(Config_Container $c)
+    {
+        //  get reference to [conf] section of config file
+        $config =& $c->getItem('section', 'conf');
+        //  get controlled cities
+        $citiesDirective =& $config->getItem('directive', 'controlledCities');
+
+               $sql = "
+                       SELECT distinct m.*, LOWER(m.member_name) AS sort_field
+              FROM member m, exploded_members_name emn";
+
+               $p = "m.new_member <> '1' AND emn.mid = m.member_id";
+               $params = array($p);
+
+        //  Limit to members whose first letter starts with the letter
+        //  a user clicked in the narrow alphabetically list.
+               if (   isset($_GET['alpha'])
+            && preg_match('/[0-9]/', $_GET['alpha'])
+        ) {
+                       $params[] = "substr(m.member_name, 1, 1) ~ '[0-9]'";
+               } elseif (isset($_GET['alpha']) && ctype_alpha($_GET['alpha'])) {
+                       $letter = $_GET['alpha'][0];
+            $params[] = "upper(substr(member_name, 1, 1)) = upper(" .
+                               $this->dbh->quote($letter) . ')';
+        }
+
+               if (isset($_GET['category']) && is_array($_GET['category'])) {
+                       $categoryKeys = array();
+                       foreach ($_GET['category'] as $k => $v) {
+                               if (ctype_digit($v)) {
+                                       $tree = Toolkit_Common::getHierarchicalTreeStructure(
+                                               $this->dbh,
+                                               'category',
+                                               'category_id',
+                                               'parent_id',
+                                               'pos',
+                                               $v,
+                                               0,
+                                               false
+                                       );
+                                       $categoryKeys = array_merge($categoryKeys, array_keys($tree));
+                               }
+                       }
+
+                       $params[] = "
+                                 member_id in (
+                                                SELECT member_id
+                                                  FROM member_category
+                                 WHERE category_id in (" . implode(', ', $categoryKeys) . "))";
+               }
+               if (isset($_GET['name']) && !empty($_GET['name'])) {
+                       $noSpaceName = preg_replace('/[^[:alnum:]]/', '', urldecode($_GET['name']));
+                       $spaceName = urldecode($_GET['name']);
+                       $sanitizedNoSpaceName = $this->dbh->quote($noSpaceName);
+                       $sanitizedSpaceName = $this->dbh->quote($spaceName);
+                       //      fuzzy name search
+            /* OR metaphone(m.member_name, 4) = metaphone($sanitizedSpaceName, 4)
+                               )
+                        OR (
+                                    m.member_id = emn.mid
+                                        AND m.new_member <> '1'
+                                AND (
+                                                $sanitizedNoSpaceName ~* regexp_replace(emn.part, '[^[:alnum:]]', '', 'g')
+                                         OR (metaphone($sanitizedSpaceName, 4) = metaphone(emn.part, 4))
+                                        )
+                                AND char_length(emn.part) > 1
+            */
+            $params[] = "(regexp_replace(m.member_name, '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceName)";
+               }
+
+               if (isset($_GET['email']) && !empty($_GET['email'])) {
+                       $email = preg_replace('/[^[:alnum:]]/', '', urldecode($_GET['email']));
+                       $params[] = "regexp_replace(member_contact_email, '[^[:alnum:]]', '', 'g') ~* " .
+                               $this->dbh->quote($email);
+               }
+        if ($citiesDirective->getContent()) {
+                       if ($cityId = filter_input(INPUT_GET, 'city_id', FILTER_VALIDATE_INT)) {
+                $params[] = "city_id = " . $this->dbh->quote($cityId);
+            }
+        } else {
+            if (isset($_GET['city']) && !empty($_GET['city'])) {
+                               $city = preg_replace('/[^[:alnum:]]/', '', urldecode($_GET['city']));
+                $params[] = "reqexp_replace(city, '[^[:alnum:]]', '', 'g') ~* " .
+                                       $this->dbh->quote($city);
+            }
+        }
+               if (   isset($_GET['state'])
+                       && $stateId = filter_input(INPUT_GET, 'state', FILTER_VALIDATE_INT)
+               ) {
+                       $params[] = "state_id = " . $this->dbh->quote($stateId);
+               }
+               if (isset($_GET['zip']) && !empty($_GET['zip'])) {
+                       $params[] = 'zip = ' . $this->dbh->quote($_GET['zip']);
+               }
+
+               if (isset($_GET['_qf__record_search']) && !empty($params)) {
+                       $params = implode(' AND ', $params);
+                       $sql    = "{$sql} WHERE $params";
+               } elseif (!isset($_GET['_qf__record_search'])) {
+                       $sql .= ' WHERE ' . implode(' AND ', $params);
+               }
+
+        parent::setQuery($sql);
+    }
+
+    //  }}}
+
+       //      {{{ url()
+
+       /**
+        * Returns the url to edit a member.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the url to get to the members edit page.
+        *
+        * @param array $data The row from the db record
+        *
+        * @return string The url to the edit member page.
+        * @access public
+        */
+       public function url($data)
+       {
+               $target = $data['record']['member_id'];
+               return BASE_URL . "admin/members.php?rt=Members&ac=editMember&tab=info&id=$target";
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ListNewRequests.php b/Toolkit/Members/Admin/ListNewRequests.php
new file mode 100755 (executable)
index 0000000..d0bfef7
--- /dev/null
@@ -0,0 +1,130 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: ListNewRequests.php,v 1.14 2010/07/14 23:27:59 jamie Exp $
+ * @link        <>
+ */
+
+/**
+ * List the new member requests in the database in a datagrid
+ *
+ * Handles listing of the new member requests in the memberDB, pagnation, and sorting.
+ * Also controls the resulting number of members that are rendered on the page.
+ *
+ * @category  MembersDB
+ * @package      Toolkit_Members
+ * @author       Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ */
+class Toolkit_Members_Admin_ListNewRequests
+       extends Toolkit_FlexyDataGridBuilder
+{
+       //      {{{ configureColumns()
+
+       /**
+        * Configures the columns (fields) that will be used in our datagrid renderer.
+        *
+        * @return void
+        * @access public
+        */
+       protected function configureColumns()
+       {
+               $url = new Structures_DataGrid_Column('Created',
+                                               'member_id',
+                                               'member_id',
+                                               null,
+                                               null,
+                                               array(&$this, 'url'));
+               $this->addColumn($url);
+
+               $name = new Structures_DataGrid_Column('Member Name',
+                                                'member_name',
+                                                'member_name');
+               $this->addColumn($name);
+
+               $phone = new Structures_DataGrid_Column('Member Phone',
+                                                 'phone',
+                                                 'phone');
+               $this->addColumn($phone);
+
+               $email = new Structures_DataGrid_Column('Contact Email',
+                                                 'member_contact_email',
+                                                 'member_contact_email');
+               $this->addColumn($email);
+       }
+
+       //      }}}
+
+       //      {{{ setControlObject()
+
+       /**
+        * Sets any control object variables that are going to be used in the template
+        *
+        * @return void
+        * @access public
+        */
+       protected function setControlObject()
+       {
+               $this->ctrlObj['baseUrl'] = BASE_URL;
+               $this->ctrlObj['glmAppBaseUrl'] = GLM_APP_BASE_URL;
+       }
+
+       //      }}}
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery()
+    {
+               $sql = "
+                       SELECT *
+              FROM member
+                        WHERE new_member = true";
+
+        parent::setQuery($sql);
+    }
+
+    //  }}}
+
+       //      {{{ url()
+
+       /**
+        * Returns the url to edit a member.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the url to get to the members edit page.
+        *
+        * @param array $data The row from the db record
+        *
+        * @return string The url to the edit member page.
+        * @access public
+        */
+       public function url($data)
+       {
+               extract($data['record']);
+               $format = BASE_URL . 'admin/members.php?rt=%s&ac=%s&id=%s';
+               return sprintf(
+                       $format,
+                       'Members',
+                       'newMemberRequests',
+                       $member_id
+               );
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ListPendingMembers.php b/Toolkit/Members/Admin/ListPendingMembers.php
new file mode 100755 (executable)
index 0000000..2a07b34
--- /dev/null
@@ -0,0 +1,120 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: ListPendingMembers.php,v 1.10 2010/07/14 23:27:59 jamie Exp $
+ * @link        <>
+ */
+
+/**
+ * List the pending members in the database in a datagrid
+ *
+ * Handles listing of the pending members in the memberDB, pagnation,
+ * and sorting. Also controls the resulting number of members that are
+ * rendered on the page.
+ *
+ * @category  MembersDB
+ * @package      Toolkit_Members
+ * @author       Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members/index.php?nav_id=2
+ */
+class Toolkit_Members_Admin_ListPendingMembers
+       extends Toolkit_FlexyDataGridBuilder
+{
+       //      {{{ configureColumns()
+
+       /**
+        * Configures the columns (fields) that will be used in our datagrid renderer
+        *
+        * @return void
+        * @access public
+        */
+       protected function configureColumns()
+       {
+               $url = new Structures_DataGrid_Column(
+                       'Created',
+            'member_id',
+            'member_id',
+            null,
+            null,
+            array(&$this, 'url')
+               );
+               $this->addColumn($url);
+
+               $name = new Structures_DataGrid_Column(
+                       'Member Name',
+            'member_name',
+            'member_name'
+               );
+               $this->addColumn($name);
+
+               $email = new Structures_DataGrid_Column(
+                       'Contact Email',
+            'member_contact_email',
+            'member_contact_email'
+               );
+               $this->addColumn($email);
+       }
+
+       //      }}}
+
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery()
+    {
+               $sql = "
+            SELECT *
+              FROM member
+             WHERE member_id IN (
+                                       SELECT DISTINCT member_id
+              FROM member_updates)";
+
+        Toolkit_DataGridBuilder::setQuery($sql);
+    }
+
+    //  }}}
+
+       //      {{{ url()
+
+       /**
+        * Returns the url to edit a member
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the url to get to the members edit page.
+        *
+        * @param array $data The row from the db record
+        *
+        * @return string The url to the edit member page.
+        * @access public
+        */
+       public function url($data)
+       {
+               extract($data['record']);
+               $format = BASE_URL . 'admin/members.php?rt=%s&ac=%s&id=%s';
+               return sprintf(
+                       $format,
+                       'Members',
+                       'pendingUpdates',
+                       $member_id
+               );
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ListRegions.php b/Toolkit/Members/Admin/ListRegions.php
new file mode 100644 (file)
index 0000000..d612ee1
--- /dev/null
@@ -0,0 +1,133 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * List the regions available for members
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ListRegions.php,v 1.9 2009/12/29 14:14:11 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * List the regions available for members
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ListRegions
+{
+       //      {{{ properties
+
+       /**
+        * Database Handler
+        *
+        * @var object
+        * @access protected
+        */
+       protected $dbh;
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'region';
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access private
+        */
+       private $_template = 'listRegions.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO $pdo PHP Data Object
+     *
+        * @access public
+        */
+       public function __construct(PDO $pdo)
+       {
+               $this->dbh = $pdo;
+
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ _getRegions()
+
+    /**
+     * Get the regions
+     *
+     * @return array regions stored in the db
+     * @access private
+     */
+       private function _getRegions()
+       {
+               try {
+                       $regions = array();
+                       $sql = "
+                               SELECT *
+                                 FROM {$this->tableName}
+                                ORDER BY region_name";
+
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $regions[$row['region_id']] = $row['region_name'];
+                       }
+
+                       return $regions;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ renderRegions()
+
+    /**
+     * Render the output
+     *
+     * @return html page
+     * @access public
+     */
+       public function renderRegions()
+       {
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->regions = $this->_getRegions();
+
+               $template->compile($this->_template);
+               return $template->bufferedOutputObject($page);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/MailOut.php b/Toolkit/Members/Admin/MailOut.php
new file mode 100644 (file)
index 0000000..2cd0e71
--- /dev/null
@@ -0,0 +1,391 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * MailOut.php
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: MailOut.php,v 1.12 2010/06/29 13:32:05 matrix Exp $
+ * @link      <>
+ */
+
+/**
+ * Member Newsletter Integration with Spamerizer App
+ * Spamerizer runs on the dev and prod servers every 5 minutes it parses out
+ * the directory /var/spool/Spamerizer
+ * there's four files and the base name of the file must all match
+ * GLMSAMPLE.head  (mailout setting file)
+ * GLMSAMPLE.body  (the body of the email it is sending out)
+ * GLMSAMPLE.to    (all emails one on each line)
+ * GLMSAMPLE.ready (empty file let's script know all files are ready)
+ * (head file format)
+ * ProcessName:    {name of this mail process}
+ * NotifyAddr:     {Owner Notification E-Mail Address}
+ * BlockSize:      {number of address per sendmail call} (keep at one)
+ * ProductionMode: ON
+ * (body file format)
+ * first lines must contain headers From: and To: then two blank lines
+ * (to file format)
+ * One email address per line
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      <>
+ */
+class Toolkit_Members_Admin_MailOut
+{
+    // {{{ Class Properties
+
+
+    /**
+     * table that stores the newsletter
+     * @var    string
+     * @access public
+     */
+    public $tableName = 'member_newsletters';
+
+    /**
+     * the unique name of the file without ext
+     * @var    string
+     * @access private
+     */
+    private $_fileBaseName;
+
+    /**
+     * template for newsletter layout
+     * @var    string
+     * @access private
+     */
+       private $_template = 'previewHtmlEmail.tpl';
+
+    /**
+     * Spamerizer temp directory
+     * @var    string
+     * @access private
+     */
+    private $_tmpDir = '/var/spool/SPAMerizer';
+
+    /**
+     * SQL query used to obtain the DataGrid
+        *
+     * @var    unknown
+     * @access protected
+     */
+       protected $sql;
+    // }}}
+    // {{{ __construct()
+
+
+    /**
+        * Constructor
+     *
+     * @param PDO $pdo PHP Data Object
+     *
+     * @return void
+     * @access public
+     */
+    public function __construct(PDO $pdo)
+    {
+        // PDO
+        $this->dbh = $pdo;
+
+        // flexy options
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+    }
+    // }}}
+    // {{{ _getMembers()
+
+
+    /**
+     * get the members based on the search parameters that are passed
+     * either by post or get (use $_REQUEST)
+     * limit the result funther to those who only have process_email
+     *
+     * @return object  Array of member data with emails
+     * @access private
+     */
+    private function _getMembers()
+    {
+        try {
+            $res = $this->dbh->query($this->sql);
+            return $res->fetchAll(PDO::FETCH_ASSOC);
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    // }}}
+    // {{{ _getMembersContacts()
+
+
+    /**
+     * get the members based on the search parameters that are passed
+     * either by post or get (use $_REQUEST)
+     * limit the result funther to those who only have process_email
+     *
+     * @param array &$members Member data array
+     *
+     * @return object  Array of member data with emails
+     * @access private
+     */
+    private function _getMembersContacts(&$members)
+    {
+        $sql = "
+        SELECT email
+          FROM member_contacts
+         WHERE send_mail = 't'
+           AND member_id = :mid";
+        $stmt = $this->dbh->prepare($sql);
+        if (is_array($members)) {
+            foreach ($members as &$row) {
+                try {
+                    $stmt->bindParam(":mid", $row['member_id'], PDO::PARAM_INT);
+                    $stmt->execute();
+                    $email = $stmt->fetchColumn();
+                    $memberContactData[] = $email;
+                } catch(PDOException $e) {
+                    Toolkit_Common::handleError($e);
+                }
+            }
+        }
+        return $memberContactData;
+    }
+    // }}}
+    // {{{ _getNewsletter()
+
+
+    /**
+     * get the newsletter main content area
+     *
+     * @param unknown $news_id id of the record
+     *
+     * @return object  Return HTML content of newsletter
+     * @access private
+     */
+    private function _getNewsletter($news_id)
+    {
+        $sql = "
+        SELECT subject,response
+          FROM {$this->tableName}
+          WHERE id = :id";
+        try {
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(":id", $news_id, PDO::PARAM_INT);
+            $stmt->execute();
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    // }}}
+    // {{{ _getTempFileName()
+
+
+    /**
+     * creates a unique filename and deletes the file created by tempnam
+     * call. Sets the class private variable _fileBaseName to the name
+     *
+     * @return void
+     * @access private
+     */
+    private function _getTempFileName()
+    {
+        $filename = tempnam($this->_tmpDir, 'GLMMN');
+        unlink($filename);
+        $this->_fileBaseName = $filename;
+    }
+    // }}}
+    // {{{ _writeBodyFile()
+
+
+    /**
+     * writes out the .body file for Spamerizer
+     *
+     * @return void
+     * @access private
+     */
+    private function _writeBodyFile()
+    {
+        $template = new HTML_Template_Flexy($this->flexyOptions);
+        $page     = new stdClass;
+
+        // get data and set response
+        $newsletter     = $this->_getNewsletter($_REQUEST['news_id']);
+        $page->response = $newsletter['response'];
+        $subject        = $newsletter['subject'];
+        // set the sitename
+        $page->sitename = SITENAME;
+        // set the cancel email
+        $page->membersEnewsEmail = FROM_MEMBER_NEWS_EMAIL;
+
+        $template->compile($this->_template);
+        // email body headers
+        $headers = "From: ".FROM_MEMBER_NEWS_EMAIL."\n".
+                               "To: ".OWNER_EMAIL."\n".
+                               "Subject: $subject\n".
+                               "Reply-to: ".REPLY_MEMBER_NEWS_EMAIL."\n".
+                               "Mime-Version: 1.0\n".
+                               "Content-Type: multipart/alternative; boundary=ContentBoundry\n\n";
+        $fileContents = wordwrap($template->bufferedOutputObject($page), 72);
+        $textContents = htmlspecialchars_decode(strip_tags($fileContents));
+        $textContents = preg_replace('/&nbsp;/', ' ', $textContents);
+        $emailBody = $headers
+        . "--ContentBoundry\nContent-Type: text/plain; charset=\"UTF-8\"\n"
+        . $textContents
+        . "\n--ContentBoundry\nContent-Type: text/html; charset=\"UTF-8\"\n"
+        . $fileContents
+        . "\n--ContentBoundry--";
+        $e = File::write($this->_fileBaseName.'.body', $emailBody, FILE_MODE_WRITE);
+        if (PEAR::isError($e)) {
+            Toolkit_Common::handleError($e);
+        }
+        $old = umask(0);
+        chmod($this->_fileBaseName.'.body', 0770);
+        umask($old);
+    }
+    // }}}
+    // {{{ _writeHeadFile()
+
+
+    /**
+     * writes out the .head file for Spamerizer
+     *
+     * @return void
+     * @access private
+     */
+    private function _writeHeadFile()
+    {
+        $fileContents = "NotifyAddr: ".OWNER_EMAIL."\n"
+            . "ProcessName: ".SITENAME."\n"
+            . "From: ".FROM_MEMBER_NEWS_EMAIL."\n"
+            . "ReportInterval: 2\n"
+            . "BlockSize: 1\n"
+            . "ProductionMode: ".PRODUCTION_MODE."\n";
+        $e = File::write($this->_fileBaseName.'.head', $fileContents, FILE_MODE_WRITE);
+        if (PEAR::isError($e)) {
+            Toolkit_Common::handleError($e);
+        }
+        $old = umask(0);
+        chmod($this->_fileBaseName.'.head', 0770);
+        umask($old);
+    }
+    // }}}
+    // {{{ _writeReadyFile()
+
+
+    /**
+     * writes out the .ready file for Spamerizer
+     *
+     * @return void
+     * @access private
+     */
+    private function _writeReadyFile()
+    {
+        $e = File::write($this->_fileBaseName.'.ready', '', FILE_MODE_WRITE);
+        if (PEAR::isError($e)) {
+            Toolkit_Common::handleError($e);
+        }
+        $old = umask(0);
+        chmod($this->_fileBaseName.'.ready', 0770);
+        umask($old);
+    }
+    // }}}
+    // {{{ _writeToFile()
+
+
+    /**
+     * writes out the .to file for Spamerizer
+     *
+     * @param array $data Parameter description (if any) ...
+     *
+     * @return void
+     * @access private
+     */
+    private function _writeToFile($data)
+    {
+        if (is_array($data)) {
+            $fileContents = implode("\n", $data);
+        }
+        $e = File::write($this->_fileBaseName.'.to', $fileContents, FILE_MODE_APPEND);
+        if (PEAR::isError($e)) {
+            Toolkit_Common::handleError($e);
+        }
+        $old = umask(0);
+        chmod($this->_fileBaseName.'.to', 0770);
+        umask($old);
+    }
+    // }}}
+    // {{{ sendEmails()
+
+
+    /**
+     * Runs all the functins grabing the member data and creating the
+     * files to be processed by spamerizer
+     *
+     * @return string Return description (if any) ...
+     * @access public
+     */
+    public function sendEmails()
+    {
+        // get member array
+        $members  = $this->_getMembers();
+        $contacts = $this->_getMembersContacts($members);
+        $this->_getTempFileName();
+        $this->_writeHeadFile();
+        $this->_writeBodyFile();
+        // setup the email array for the to file with no duplicates
+        if (is_array($members)) {
+            foreach ($members as $row) {
+                $emails[$row['process_email']] = $row['process_email'];
+            }
+        }
+        if (is_array($contacts)) {
+            foreach ($contacts as $email) {
+                $emails[$email] = $email;
+            }
+        }
+        $this->_writeToFile($emails);
+        $this->_writeReadyFile();
+        $out .= '<div id="form-warning-top">Do not refresh this page!</div>'
+            . '<p>Your Newsletter has been setup for Processing. '
+            . 'You should receive at least 2 emails at ' . FROM_MEMBER_NEWS_EMAIL
+            . '. One at the beginning, One at the completion of the processing '
+            . 'and may receive others depending on how many emails are being Processed.'
+            . ' Refreshing this page will send out the same newsletter again.</p>';
+        return $out;
+    }
+    // }}}
+       //      {{{ setQuery()
+
+    /**
+     * Sets the sql query to use in the DataGrid to get the results
+     *
+     * @param array $ids An array of member_id1s for the search sql
+     *
+     * @return void
+     * @access public
+     */
+       public function setQuery(array $ids)
+       {
+               $memberIds = implode(', ', $ids);
+               $sql = "
+                       SELECT member_id, process_email
+              FROM member
+             WHERE member_id IN ($memberIds)
+                ";
+
+        $this->sql = $sql;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/MailOutForm.php b/Toolkit/Members/Admin/MailOutForm.php
new file mode 100644 (file)
index 0000000..c299374
--- /dev/null
@@ -0,0 +1,257 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Admin search functionality for memberdb
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: MailOutForm.php,v 1.10 2010/05/25 14:01:21 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form to search the members database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_MailOutForm
+    extends Toolkit_FormBuilder
+{
+       //      {{{ configureConstants()
+
+    /**
+     * Form constant definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+               $c = array(
+                       'page'   => $_GET['page'],
+                       'module' => $_GET['module'],
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+        * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements(PDO $dbh, Config_Container $c)
+       {
+        $e = array();
+
+               //  get reference to [listing type] section of config file
+               $pluralType = $c->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+
+               $newsletters = $this->_getNewsletters($dbh);
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+        $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'page'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'module'
+        );
+               $e[] = array(
+            'type' => 'select',
+            'req' => true,
+            'name' => 'news_id',
+            'display' => 'Newsletter',
+            'opts' => array('' => '-- Select --') + $newsletters
+        );
+               $e[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit',
+            'display' => 'Send to ' . $pluralType,
+            'opts'    => array('id' => 'member-newsletter-mailout')
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+        * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(PDO $dbh, Config_Container $c)
+    {
+        $this->configureElements($dbh, $c);
+        $this->configureRules();
+        $this->configureFilters();
+        $this->configureConstants();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+               $r[] = array(
+            'element' => 'news_id',
+            'message' => 'ERROR: Invalid Newsletter!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     _getNewsletters()
+
+    /**
+     * get all the categories available in alpha order
+     * 
+     * @param PDO $dbh PDO
+     *
+     * @return array|void alpha order of categories available in the DB
+     * @access private
+     * @throws PEAR_Error
+     */
+       private function _getNewsletters(PDO $dbh)
+       {
+               try {
+                       $sql = "
+                               SELECT *, subject || ' (' ||
+                                               to_char(last_update, 'Month DDth, YYYY')
+                                               || ')' AS header
+                  FROM member_newsletters
+                 ORDER BY last_update DESC, subject";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->execute();
+                       $stmt->bindColumn('id', $nid);
+                       $stmt->bindColumn('header', $subject);
+
+                       $categories = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $categories[$nid] = $subject;
+                       }
+
+                       return $categories;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $tpl = '<tr align="center"><td colspan="2">{element}</td></tr>';
+               $renderer->setElementTemplate($tpl, 'submit');
+       }
+
+    //  @codeCoverageIgnoreEnd
+       //      }}}
+
+       //      {{{     toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+     * @param array  $results array of member_id's
+     * @param PDO    $dbh     PDO object reference
+        *
+        * @access protected
+        * @return string $output The Form to be rendered or success msg.
+        */
+       public function toHtml(array $results, PDO $dbh)
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+            $mailOut = new Toolkit_Members_Admin_MailOut($dbh);
+                       $mailOut->setQuery($results);
+            $output = $mailOut->sendEmails();
+               } elseif ($this->isSubmitted()) {
+                       $output = $this->errorMsg;
+                       $output .= parent::toHTML();
+               } else {
+                       $output = parent::toHTML();
+               }
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/MemberReportSearch.php b/Toolkit/Members/Admin/MemberReportSearch.php
new file mode 100644 (file)
index 0000000..4b24107
--- /dev/null
@@ -0,0 +1,215 @@
+<?php
+
+/**
+ * Admin search functionality for memberdb
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AdvancedSearch.php,v 1.14 2010/08/15 19:35:15 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form to search the members database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_MemberReportSearch
+    extends Toolkit_FormBuilder
+{
+
+    /**
+     * Description of $_members
+     *
+     * @var unknown
+     * @access private
+     */
+       private $_members;
+
+       /**
+        * Sets the defaults for the form
+        *
+        * @param PDO $dbh Database handler
+        *
+        * @access public
+     * @return void
+        */
+       public function configureDefaults()
+       {
+               $d = array(
+                       'rt' => $_GET['rt'],
+                       'ac' => $_GET['ac']
+               );
+        $d['reportMonth']
+            = ($_REQUEST['reportMonth'])
+            ? $_REQUEST['reportMonth']
+            : date('n').'|'.date('Y');
+
+               $this->setupDefaults($d);
+       }
+
+    /**
+     * Form element definitions
+     *
+        * @param PDO                      $dbh Databse handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements(PDO $dbh)
+       {
+        $e = array();
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'rt'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'ac'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'searching',
+            'display' => '1'
+        );
+       $e[] = array(
+            'type'    => 'select',
+            'name'    => 'reportMonth',
+            'display' => 'Show Summary for month of ',
+            'opts'    => $this->getMonths(),
+            'req'     => false
+       );
+       $e[] = array(
+            'type'    => 'text',
+            'name'    => 'name',
+            'display' => 'Member Name',
+            'req'     => false
+       );
+       $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Search'
+        );
+
+               $this->setupElements($e);
+       }
+
+    protected function getMonths()
+    {
+        $months = array();
+        try {
+            $sql = "
+            SELECT distinct ON (date_part('year', edate),
+                                date_part('month', edate))
+                                date_part('month', edate) as month,
+                                date_part('year', edate) as year
+              FROM exposure
+             WHERE member_id in (
+                    SELECT distinct member_id
+                      FROM member)
+             ORDER BY date_part('year', edate), date_part('month', edate)";
+            if ($monthData = $this->dbh->query($sql)->fetchAll()) {
+                if (!$_GET['monthYear']) {
+                    $m          = date("n");
+                    $F          = date("F");
+                    $Y          = date("Y");
+                    $monthYear .= $m.' '.$Y;
+                } else {
+                    $monthYear .= $_GET['monthYear'];
+                }
+                foreach ($monthData as $data) {
+                    $monthName = date(
+                        "F",
+                        mktime(0, 0, 0, $data['month'], 1, date('year'))
+                    );
+                    $months[$data['month'].'|'.$data['year']] = $monthName.
+                        ' '.$data['year'];
+                }
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $months;
+    }
+
+    /**
+     * Form filter definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+    /**
+     * Helper function to configure an entire form
+     *
+        * @param PDO                      $dbh Databse handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(PDO $dbh)
+    {
+        $this->configureElements($dbh);
+        $this->configureDefaults();
+        $this->configureFilters();
+    }
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $tpl = '<tr align="center"><td colspan="2">{element}</td></tr>';
+               $renderer->setElementTemplate($tpl, 'submit');
+       }
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+        * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+        *
+        * @access protected
+        * @return string $output The Form to be rendered or success msg.
+        */
+       public function toHtml(PDO $dbh)
+       {
+               $this->setupRenderers();
+
+               return parent::toHTML();
+       }
+
+}
diff --git a/Toolkit/Members/Admin/MembersController.php b/Toolkit/Members/Admin/MembersController.php
new file mode 100644 (file)
index 0000000..37c7a79
--- /dev/null
@@ -0,0 +1,310 @@
+<?php
+/**
+ * MembersController.php
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Newsletters.php,v 1.9 2009/09/16 19:00:58 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Admin_MembersController
+ *
+ * Description for Toolkit_Members_Admin_MembersController
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_MembersController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     _authorizeMemberUpdates()
+    /**
+     * Description of _authorizeMemberUpdates()
+     *
+     * @param int $memberId Int
+     *
+     * @return string
+     * @access private
+     */
+       private function _authorizeMemberUpdates($memberId)
+       {
+               if (filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/authorizeChanges.js';
+               }
+
+               $updateForm = new Toolkit_Members_Admin_AuthorizeUpdates(
+                       $this->registry->dbh,
+                       'auth_updates'
+               );
+               $updateForm->setMember($memberId);
+               $updateForm->configureForm();
+               return $updateForm->toHtml();
+       }
+
+       //      }}}
+       //      {{{     _authorizeNewMember()
+    /**
+     * Description of _authorizeNewMember()
+     *
+     * @return string
+     * @access private
+     */
+       private function _authorizeNewMember()
+       {
+               $GLOBALS['styleSheets'][]  = BASE_URL . 'css/contactform.css';
+               $form = new Toolkit_Members_Admin_AuthorizeNewMemberForm(
+            $this->registry->dbh,
+            'authorize_form'
+        );
+        $form->setConfig($this->registry->config);
+        $form->configureForm();
+               return $form->toHtml();
+       }
+
+       //      }}}
+       //      {{{     _listNewMembers()
+    /**
+     * Description of _listNewMembers()
+     *
+     * @return string
+     * @access private
+     */
+       private function _listNewMembers()
+       {
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/member-list.js';
+               $GLOBALS['styleSheets'][]   = BASE_URL . 'css/contactform.css';
+
+               $nmr = new Toolkit_Members_Admin_ListNewRequests($this->registry->dbh);
+        $nmr->setQuery();
+        $nmr->setDefaultSort(array('member_name' => 'ASC'));
+
+        //  rendering engine to use
+        $rEngine = new Structures_DataGrid_Renderer_Flexy();
+        $rEngine->setContainer($this->registry->tEngine);
+
+               return $nmr->toHtml($rEngine, 'listNewMembers.tpl');
+       }
+
+       //      }}}
+       //      {{{     _listPendingMembers()
+    /**
+     * Description of _listPendingMembers()
+     *
+     * @return string
+     * @access private
+     */
+       private function _listPendingMembers()
+       {
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/member-pending-list.js';
+
+               $pml = new Toolkit_Members_Admin_ListPendingMembers(
+                       $this->registry->dbh
+               );
+        $pml->setQuery();
+        $pml->setDefaultSort(array('member_name' => 'asc'));
+
+        //  rendering engine to use
+        $rEngine = new Structures_DataGrid_Renderer_Flexy();
+        $rEngine->setContainer($this->registry->tEngine);
+
+               return $pml->toHtml($rEngine, 'listPendingMembers.tpl');
+       }
+
+       //      }}}
+
+       //      {{{     editMemberAction()
+    /**
+     * Description of editMemberAction()
+     *
+     * @return string
+     * @access public
+     */
+       public function editMemberAction()
+       {
+               $member = new Toolkit_Members();
+
+               $this->registry->controllerObject->content = $member->toHtml();
+               $this->registry->controllerObject->breadcrumbs = true;
+               $this->registry->controllerObject->listingType
+                       = $this->registry->config
+            ->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+               $this->registry->controllerObject->searchResults
+                       = HTTP_Session2::get('searchResults');
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     indexAction()
+    /**
+     * Description of indexAction()
+     *
+     * @return unknown
+     * @access public
+     */
+       public function indexAction()
+       {
+               $indexController = new Toolkit_Members_Admin_IndexController($this->registry);
+               return $indexController->indexAction();
+       }
+
+       //      }}}
+       //      {{{     listMembersAction()
+    /**
+     * Description of listMembersAction()
+     *
+     * @return unknown
+     * @access public
+     */
+       public function listMembersAction()
+       {
+               return $this->indexAction();
+       }
+
+       //      }}}
+       //      {{{     memberReportsAction()
+    /**
+     * Description of memberReportsAction()
+     *
+     * @return string
+     * @access public
+     */
+       public function memberReportsAction()
+       {
+        //  rendering engine to use
+        $rEngine = new Structures_DataGrid_Renderer_Flexy();
+        $rEngine->setContainer($this->registry->tEngine);
+
+               if ($memberId = filter_input(INPUT_GET, 'member_id', FILTER_VALIDATE_INT)) {
+            $detail = new Toolkit_Members_ExposureDetailReports($this->registry->dbh);
+            $detail->setQuery($memberId);
+            $detail->setDefaultSort(array('month' => 'desc'));
+            $urlFormat = '<a href="%s">Reports</a>';
+            $url = BASE_URL . 'admin/members.php?rt=Members&ac=memberReports';
+            if ($_REQUEST['reportMonth']) {
+                $url .= '&reportMonth=' . $_REQUEST['reportMonth'];
+            }
+            $this->registry->controllerObject->content = sprintf(
+                $urlFormat,
+                $url
+            );
+            $this->registry->controllerObject->content .= $detail->toHtml($rEngine);
+        } else {
+            $form = new Toolkit_Members_Admin_MemberReportSearch(
+                'MemberSearchReport',
+                'get'
+            );
+            $form->configureForm($this->registry->dbh);
+            $this->registry->controllerObject->content .= $form->toHtml($this->registry->dbh);
+            if ($_REQUEST['searching']) {
+                $reports = new Toolkit_Members_ExposureReports(
+                    $this->registry->dbh,
+                    50
+                );
+                $reports->setQuery();
+                $this->registry->controllerObject->content .= $reports->toHtml($rEngine);
+            }
+        }
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     newMemberRequestsAction()
+    /**
+     * Description of newMemberRequestsAction()
+     *
+     * @return string
+     * @access public
+     */
+       public function newMemberRequestsAction()
+       {
+               if ($memberId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $this->registry->controllerObject->content
+                               = $this->_authorizeNewMember($memberId);
+               } else {
+                       $this->registry->controllerObject->content = $this->_listNewMembers();
+               }
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     pendingUpdatesAction()
+    /**
+     * Description of pendingUpdatesAction()
+     *
+     * @return string
+     * @access public
+     */
+       public function pendingUpdatesAction()
+       {
+               if ($memberId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $this->registry->controllerObject->content
+                               = $this->_authorizeMemberUpdates($memberId);
+               } else {
+                       $this->registry->controllerObject->content = $this->_listPendingMembers();
+               }
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/Navigation.php b/Toolkit/Members/Admin/Navigation.php
new file mode 100644 (file)
index 0000000..eab7a9d
--- /dev/null
@@ -0,0 +1,403 @@
+<?php
+/**
+ * Navigation.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    SJamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_Navigation
+ *
+ * Description of Toolkit_Members_Admin_Navigation
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_Navigation extends Toolkit_NavigationAbstract
+       implements Toolkit_INavigation
+{
+       //      {{{     __construct()
+
+    /**
+     * Class constructor
+     *
+     * @param HTML_Menu          $menu    Description for $menu
+     * @param HTML_Menu_Renderer $rEngine Description for $rEngine
+     *
+     * @access public
+     */
+       public function __construct(
+               HTML_Menu $menu,
+               HTML_Menu_Renderer $rEngine
+       ) {
+               $this->menu      = $menu;
+               $this->rEngine   = $rEngine;
+               $this->currIndex = 'members';
+       }
+
+       //      }}}
+
+       //      {{{     _hasPendingMemberUpdates()
+
+    /**
+     * Description of _hasPendingMemberUpdates()
+     *
+     * @param PDO $dbh PDO
+     *
+     * @return string|boolean|mixedd
+     * @access private
+     */
+       private function _hasPendingMemberUpdates(PDO $dbh)
+       {
+               try {
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM member_updates";
+
+                       $row = $dbh->query($sql)->fetch();
+                       return $row['total'] ? 'hasPending' : false;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     _hasNewMemberRequests()
+
+    /**
+     * Description of _hasNewMemberRequests
+     *
+     * @param PDO $dbh PDO
+     *
+     * @return string|boolean|mixed
+     * @access private
+     */
+       private function _hasNewMemberRequests(PDO $dbh)
+       {
+               try {
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM member
+                                WHERE new_member";
+
+                       $row = $dbh->query($sql)->fetch();
+                       return $row['total'] ? 'hasPending' : false;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     getNavSructure()
+       //      @codeCoverageIgnoreStart
+
+    /**
+     * Sets up a multi dimensional array used for the nav structure
+        *
+        * @param PDO                      $dbh Database handler
+        * @param Config_Container $c   Application configuration
+     *
+     * @return mixed false on sql error. otherwise void
+     * @access public
+     */
+       public function getNavStructure(PDO $dbh, Config_Container $c)
+       {
+        //  get reference to [listing type] section of config file
+        $singularType = strtolower(
+                       $c->getItem('section', 'listing type')
+                         ->getItem('directive', 'singular')
+                         ->getContent()
+               );
+        $pluralType = strtolower(
+                       $c->getItem('section', 'listing type')
+                         ->getItem('directive', 'plural')
+                         ->getContent()
+               );
+        $singularRegion = strtolower(
+                       $c->getItem('section', 'region type')
+              ->getItem('directive', 'singular')
+                         ->getContent()
+               );
+        $pluralRegion = strtolower(
+                       $c->getItem('section', 'region type')
+              ->getItem('directive', 'plural')
+                         ->getContent()
+               );
+
+               $nav = array(
+                       'Members' => array(
+                               'Title' => ucfirst($pluralType),
+                               'url' => BASE_URL . 'admin/members.php?rt=Members',
+                               'desc' => "View and edit $pluralType in the database",
+                               'sub' => array(
+                                       'listMembers' => array(
+                                               'Title' => 'List ' . ucfirst($pluralType),
+                                               'url' => BASE_URL . 'admin/members.php?rt=Members&amp;ac=listMembers',
+                                               'desc' => "Show all $pluralType in the database",
+                                       ),
+                                       'editMember' => array(
+                                               'Title' => 'Add ' . ucfirst($singularType) . ' Listing',
+                                               'url' => BASE_URL . 'admin/members.php?rt=Members&amp;ac=editMember&amp;tab=info',
+                                               'desc' => "Add a $singularType record to the database",
+                                       ),
+//                                     'pendingUpdates' => array(
+//                                             'Title' => 'Pending ' . ucfirst($singularType) . ' Listing Update',
+//                                             'url' => BASE_URL . "admin/members.php?rt=Members&amp;ac=pendingUpdates",
+//                                             'desc' => "Accept or reject any $singularType record changes",
+//                                             'class' => $this->_hasPendingMemberUpdates($dbh)
+//                                     ),
+//                                     'newMemberRequests' => array(
+//                                             'Title' => 'New ' . ucfirst($singularType) . ' Requests',
+//                                             'url' => BASE_URL . 'admin/members.php?rt=Members&amp;ac=newMemberRequests',
+//                                             'desc' => "Accept or reject any new $singularType requests",
+//                                             'class' => $this->_hasNewMemberRequests($dbh)
+//                                     ),
+                                       'memberReports' => array(
+                                               'Title' => 'Reports',
+                                               'url' => BASE_URL . 'admin/members.php?rt=Members&amp;ac=memberReports',
+                                               'desc' => 'View reports on view,detail,or clicks',
+                                       )
+                               )
+                       ),
+                       'Settings' => array(
+                               'Title' => 'Settings',
+                               'url' => BASE_URL . 'admin/members.php?rt=Settings',
+                               'desc' => 'Application settings',
+                               'sub' => array(
+                                       'Categories' => array(
+                                               'Title' => 'Categories',
+                                               'url' => BASE_URL . 'admin/members.php?rt=Categories',
+                                               'desc' => "View and edit $singularType categories",
+                                               'sub' => array(
+                                                       'listCategories' => array(
+                                                               'Title' => 'List Categories',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Categories&amp;ac=listCategories',
+                                                               'desc' => "Show a list of all $singularType categories in the databse",
+                                                       ),
+                                                       'editCategory' => array(
+                                                               'Title' => 'Add Category',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Categories&amp;ac=editCategory',
+                                                               'desc' => "Add a $singularType category to the database",
+                                                       )
+                                               )
+                                       ),
+                                       'Amenities' => array(
+                                               'Title' => "Amenities",
+                                               'url' => BASE_URL . 'admin/members.php?rt=Amenities',
+                                               'desc' => "View and edit $singularType amenities",
+                                               'sub' => array(
+                                                       'listAmenities' => array(
+                                                               'Title' => 'List Amenities',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Amenities&amp;ac=listAmenities',
+                                                               'desc' => "Show a list of all $singularType amenities in the database",
+                                                       ),
+                                                       'editAmenity' => array(
+                                                               'Title' => 'Add Amenity',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Amenities&amp;ac=editAmenity',
+                                                               'desc' => "Add a $singularType amenity to the database",
+                                                       )
+                                               )
+                                       ),
+                                       'Regions' => array(
+                                               'Title' => ucfirst($pluralRegion),
+                                               'url' => BASE_URL . 'admin/members.php?rt=Regions',
+                                               'desc' => "View and edit " . strtolower($singularType) . ' ' . $pluralRegion,
+                                               'sub' => array(
+                                                       'listRegions' => array(
+                                                               'Title' => 'List ' . ucfirst($pluralRegion),
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Regions&amp;ac=listRegions',
+                                                               'desc' => "Show a list of all $singularType $pluralRegion in the database",
+                                                       ),
+                                                       'editRegion' => array(
+                                                               'Title' => 'Add ' . ucfirst($singularRegion),
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Regions&amp;ac=editRegion',
+                                                               'desc' => "Add a $singularType $singularRegion to the database",
+                                                       )
+                                               )
+                                       ),
+                                       'Counties' => array(
+                                               'Title' => "Counties",
+                                               'url' => BASE_URL . 'admin/members.php?rt=Counties',
+                                               'desc' => "View and edit $singularType counties",
+                                               'sub' => array(
+                                                       'listCounties' => array(
+                                                               'Title' => 'List Counties',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Counties&amp;ac=listCounties',
+                                                               'desc' => "Show a list of all $singularType counties in the database",
+                                                       ),
+                                                       'editCounty' => array(
+                                                               'Title' => 'Add County',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Counties&amp;ac=editCounty',
+                                                               'desc' => "Add a $singularType county to the database",
+                                                       )
+                                               )
+                                       ),
+                                       'Cities' => array(
+                                               'Title' => "Cities",
+                                               'url' => BASE_URL . 'admin/members.php?rt=Cities',
+                                               'desc' => "View and edit $singularType cities",
+                                               'sub' => array(
+                                                       'listCities' => array(
+                                                               'Title' => 'List Cities',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Cities&amp;ac=listCities',
+                                                               'desc' => "Show a list of all $singularType cities in the database",
+                                                       ),
+                                                       'editCity' => array(
+                                                               'Title' => 'Add City',
+                                                               'url' => BASE_URL . 'admin/members.php?rt=Cities&amp;ac=editCity',
+                                                               'desc' => "Add a $singularType city to the database",
+                                                       )
+                                               )
+                                       )
+                               )
+                       ),
+                       'Newsletter' => array(
+                               'Title' => "Newsletter",
+                               'url' => BASE_URL . 'admin/members.php?rt=Newsletter',
+                               'desc' => "Prepare a $singularType newsletter mailing",
+                               'sub' => array(
+                                       'search' => array(
+                                               'Title' => 'Search',
+                                               'url' => BASE_URL . 'admin/members.php?rt=Newsletter&amp;ac=search',
+                                               'desc' => 'View and edit HTML email templates to use in the newsletter',
+                                       ),
+                                       'listHtmlEmails' => array(
+                                               'Title' => 'HTML Emails',
+                                               'url' => BASE_URL . 'admin/members.php?rt=Newsletter&amp;ac=listHtmlEmails',
+                                               'desc' => 'View and edit HTML email templates to use in the newsletter',
+                                       ),
+                                       'listArchivedHtmlEmails' => array(
+                                               'Title' => 'Archived HTML Emails',
+                                               'url' => BASE_URL . 'admin/members.php?rt=Newsletter&amp;archived=1&amp;ac=listArchivedHtmlEmails',
+                                               'desc' => 'View and edit HTML email templates to use in the newsletter',
+                                       ),
+                                       'editHtmlEmail' => array(
+                                               'Title' => 'Add HTML Email',
+                                               'url' => BASE_URL . 'admin/members.php?rt=Newsletter&amp;ac=editHtmlEmail',
+                                               'desc' => 'Create a HTML email templates to use in the newsletter',
+                                       ),
+                                       //'memberExportFile' => array( 'Title' => ucfirst($singularType) . ' Export File', 'url' => BASE_URL . 'admin/members.php?rt=Newsletter&amp;ac=memberExportFile', 'desc' => '',),
+                                       //85 => array('Title' => $singularType . ' Subscriptions', 'url' => BASE_URL . 'admin/members.php?cat=8&subCat=4', 'desc' => '', 'ac' => 'memberSubscriptions',),
+                               )
+                       ),
+                       'AdvancedSearch' => array(
+                               'Title' => 'Advanced Search',
+                               'url' => BASE_URL . 'admin/members.php?rt=AdvancedSearch',
+                               'desc' => 'Advanced database search'
+                       ),
+                       'Export' => array(
+                               'Title' => 'Export',
+                               'url' => BASE_URL . 'admin/members.php?rt=Export',
+                               'desc' => 'Export records from the database'
+                       )
+               );
+
+        //  get reference to [conf] section of config file
+        $config =& $c->getItem('section', 'conf');
+
+        //  get region
+        $directive =& $config->getItem('directive', 'regions');
+               if (!$directive->getContent()) {
+                       unset($nav['Settings']['sub']['Regions']);
+               }
+        //  get controlled cities
+        $directive =& $config->getItem('directive', 'controlledCities');
+               if (!$directive->getContent()) {
+                       unset($nav['Settings']['sub']['Cities']);
+               }
+        //  get counties
+        $directive =& $config->getItem('directive', 'counties');
+               if (!$directive->getContent()) {
+            unset($nav['Settings']['sub']['Counties']);
+        }
+        //  get amenities
+        $directive =& $config->getItem('directive', 'amenities');
+               if (!$directive->getContent()) {
+                       unset($nav['Settings']['sub']['Amenities']);
+               }
+
+        //  get new member requests
+        $directive =& $config->getItem('directive', 'newMemberRequests');
+               if (!$directive->getContent()) {
+                       unset($nav['Members']['sub']['newMemberRequests']);
+               }
+
+        $billingModule = $c->getItem('section', 'admin')
+            ->getItem('directive', 'billing')
+            ->getContent();
+
+
+        if ($billingModule) {
+            $billingNav = new Toolkit_Members_Billing_AdminNavigation();
+            $nav['Billing'] = $billingNav->getNavigationArray($c);
+        }
+               return $nav;
+       }
+
+       //      @codeCoverageIgnoreEnd
+       //      }}}
+
+       //      {{{     setCurrentIndex()
+
+    /**
+     * Description of setCurrentIndex()
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setCurrentIndex()
+       {
+               if ($action = filter_input(INPUT_GET, 'ac')) {
+                       $this->menu->forceCurrentIndex($action);
+               } elseif ($route = filter_input(INPUT_GET, 'rt')) {
+                       $this->menu->forceCurrentIndex($route);
+               } else {
+                       $this->menu->forceCurrentIndex('Members');
+               }
+       }
+
+       //      }}}
+       //      {{{     setNavTemplates()
+
+    /**
+     * Description of setNavTemplates()
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setNavTemplates()
+       {
+               $tpl = '<li><a class="%s" href="%s" title="%s">{Title}</a></li>';
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_INACTIVE,
+                       sprintf($tpl, '{class}', '{url}', '{desc}', '{Title}')
+               );
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVE,
+                       sprintf($tpl, 'active {class}', '{url}', '{desc}', '{Title}')
+               );
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVEPATH,
+                       sprintf($tpl, 'active {class}', '{url}', '{desc}', '{Title}')
+               );
+               $this->rEngine->setMenuTemplate('<div>', '</div>');
+               $this->rEngine->setRowTemplate('<ul class="navlist">', '</ul>');
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/NewsletterController.php b/Toolkit/Members/Admin/NewsletterController.php
new file mode 100644 (file)
index 0000000..fbe39a6
--- /dev/null
@@ -0,0 +1,230 @@
+<?php
+/**
+ * NewsletterController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_NewsletterController
+ * 
+ * Description of Toolkit_Members_Admin_NewsletterController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_NewsletterController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     editHtmlEmailAction()
+    /**
+     * Description of editHtmlEmailAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function editHtmlEmailAction()
+       {
+               if (isset($_GET['preview'])
+                       && $newsId = filter_input(INPUT_GET, 'news_id', FILTER_VALIDATE_INT)
+               ) {
+            $preview = new Toolkit_Members_Admin_PreviewHtmlEmail(
+                               $this->registry->dbh,
+                               $this->registry->tEngine
+                       );
+                       $this->registry->controllerObject->content
+                               = $preview->renderPreviewIFrame(
+                    $newsId,
+                    'previewNewsletterWrapper.html'
+                );
+        } else if (isset($_GET['previewFrame'])
+            && $newsId = filter_input(INPUT_GET, 'news_id', FILTER_VALIDATE_INT)
+        ) {
+            $preview = new Toolkit_Members_Admin_PreviewHtmlEmail(
+                               $this->registry->dbh,
+                               $this->registry->tEngine
+                       );
+                       echo $this->registry->controllerObject->content
+                               = $preview->renderPreview(
+                    $newsId,
+                    'previewHtmlEmail.tpl'
+                );
+            exit;
+        } else {
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-html-email.js';
+
+            $form = new Toolkit_Members_Admin_EditHtmlEmail(
+                $this->registry->dbh,
+                'edit_html_email'
+            );
+            $form->configureForm();
+                       $this->registry->controllerObject->content = $form->toHtml();
+        }
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+
+       //      {{{     indexAction()
+    /**
+     * Description of indexAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function indexAction()
+       {
+               $GLOBALS['styleSheets'][] = BASE_URL . 'css/contactform.css';
+
+               HTTP_Session2::set('newSearch', true);
+               $searchForm = new Toolkit_Members_Admin_AdvancedSearch(
+            'advanced-record-search',
+                       'get',
+                       BASE_URL . 'admin/members.php',
+                       '',
+                       null,
+                       true
+               );
+
+        $searchForm->configureForm($this->registry->dbh, $this->registry->config);
+
+               $this->registry->controllerObject->content
+                       = $searchForm->toHtml($this->registry->dbh, $this->registry->config);
+               if ($results = $searchForm->getSearchResults()) {
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/member-list.js';
+
+            // Newsletter Mailout Form
+            $news = new Toolkit_Members_Admin_MailOutForm(
+                'mailout_news',
+                'POST',
+                               urldecode($_SERVER['REQUEST_URI']),
+                '',
+                null,
+                true
+            );
+
+            $news->configureForm($this->registry->dbh, $this->registry->config);
+                       $this->registry->controllerObject->content
+                               .= $news->toHtml($results, $this->registry->dbh);
+
+                       $membersList = new Toolkit_Members_Admin_AdvancedSearchDataGrid(
+                               $this->registry->dbh,
+                               50
+                       );
+                       if (   isset($_GET['d'])
+                               && $_GET['d'] == 't'
+                               && $memberId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
+                       ) {
+                               $membersList->removeMember(
+                                       $memberId,
+                                       new Toolkit_Image_Server()
+                               );
+                       }
+                       $membersList->setQuery($results);
+                       $membersList->setDefaultSort(array('sort_field' => 'ASC'));
+
+                       //  rendering engine to use
+                       $rEngine = new Structures_DataGrid_Renderer_Flexy();
+                       $rEngine->setContainer($this->registry->tEngine);
+
+                       $this->registry->controllerObject->content
+                               .= $membersList->toHtml($rEngine, 'listMembers.tpl');
+               }
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+
+       //      {{{     listArchivedHtmlEmailsAction()
+    /**
+     * Description of listArchivedHtmlEmailsAction
+     * 
+     * @return string
+     * @access public
+     */
+       public function listArchivedHtmlEmailsAction()
+       {
+               return $this->listHtmlEmailsAction();
+       }
+
+       //      }}}
+       //      {{{     listHtmlEmailsAction()
+    /**
+     * Description of listHtmlEmailsAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function listHtmlEmailsAction()
+       {
+               $emailList = new Toolkit_Members_Admin_ListHtmlEmails($this->registry->dbh);
+               $this->registry->controllerObject->content = $emailList->renderHtmlEmails();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+
+       //      {{{     searchAction()
+    /**
+     * Description of searchAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function searchAction()
+       {
+               return $this->indexAction();
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Admin/Newsletters.php b/Toolkit/Members/Admin/Newsletters.php
new file mode 100644 (file)
index 0000000..bd451e2
--- /dev/null
@@ -0,0 +1,340 @@
+<?php
+/**
+ * Newsletters.php
+ * 
+ * PHP versions 4 and 5
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Newsletters.php,v 1.9 2009/09/16 19:00:58 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+
+/**
+ * Toolkit_Members_Admin_Newsletters
+ * 
+ * Search for Members to send out E-Blast
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_Newsletters extends Toolkit_FlexyDataGridBuilder
+{
+    //  {{{  Properties
+
+    /**
+     * Message for no record found
+     * @var string
+     * @access protected
+     */
+    protected $noRecMessage = 'No Data Found';
+    /**
+     * Table name for tracking
+     * @var    string   
+     * @access protected
+     */
+    protected $tableName = 'member';
+
+    /**
+     * Description for protected
+     * @var    array    
+     * @access protected
+     */
+    protected $queryParams = array();
+
+    /**
+     * Template File
+     * @var    string   
+     * @access protected
+     */
+    protected $template = 'memberContactsList.tpl';
+
+    //  }}}
+    //  {{{ __construct()
+
+    /**
+     * Class constructor
+     *
+     * define where templates for the data grid are at, 
+     * then call the parent constructor which will handle
+     * finishing the settings for the datagrid.
+     *
+     * After all settings are finished you can call the toHTML()
+     * function on this object and the datagrid
+     * will be rendered and returned as a string.  
+     * Optionally you could call show() and the datagrid would
+     * be rendered and output immediatley to the screen.
+     *
+     * @param PDO    $pdo          PHP Data Object to use for DB calls
+     * @param string $limit        The number of records to display per page.
+     * @param int    $page                The current page viewed.
+     *                             In most cases, this is useless.
+     *                             Note: if you specify this, the "page" GET 
+     *                             variable will be ignored.
+     * @param string $rendererType The type of renderer to use.
+     *                             You may prefer to use the $type argument
+     *                             of {@link render}, {@link fill} or 
+     *                             {@link getOutput}
+     * 
+     * @access public
+     */
+    public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null
+    ) {
+        $this->pagerOptions['containerClass'] = 'pages';
+        parent::__construct($pdo, $limit, $page, $rendererType);
+    }
+
+    //  }}}
+
+    //  {{{ configureColumns()
+
+    /**
+     * Configures the columns (fields) that will be used in our datagrid renderer.
+     *
+     * @return  void
+     * @access public
+     */
+    protected function configureColumns()
+    {
+        $directUrl = new Structures_DataGrid_Column(
+            'DirectURL',
+            'directUrl',
+            'directUrl',
+            null,
+            null,
+            array(&$this, 'recordUrl')
+        );
+        $this->addColumn($directUrl);
+
+        $memberName = new Structures_DataGrid_Column(
+            'Member Name',
+            'member_name',
+            'member_name'
+        );
+        $this->addColumn($memberName);
+
+        $fname = new Structures_DataGrid_Column(
+            'First Name',
+            'fname',
+            'fname'
+        );
+        $this->addColumn($fname);
+
+        $lname = new Structures_DataGrid_Column(
+            'Last Name',
+            'lname',
+            'lname'
+        );
+        $this->addColumn($lname);
+    }
+
+    //  }}}
+
+    //  {{{ getMemberCats()
+
+    /**
+     * getMemberCats 
+     * 
+     * @return array
+     * @access protected
+     * @throws PEAR_Error
+     */
+    protected function getMemberCats()
+    {
+        $sql = "
+                       SELECT *
+                         FROM category
+                        WHERE parent_id = 0
+                        ORDER BY parent_id, name";
+        try {
+            $stmt = $this->dbh->query($sql);
+            //$categories[] = '';
+            while ($row = $stmt->fetch()) {
+                unset($subs);
+                $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE parent_id = :id
+                                        ORDER BY parent_id, name";
+                try {
+                    $stmt2 = $this->dbh->prepare($sql);
+                    $stmt2->bindParam(":id", $row['category_id'], PDO::PARAM_INT);
+                    $stmt2->execute();
+                    while ($row2 = $stmt2->fetch()) {
+                        $subs[$row2['category_id']] = $row2['name'];
+                    }
+                } catch(PDOException $e) {
+                                       return Toolkit_Common::handleError($e);
+                }
+                if ($subs) {
+                    $categories[$row['name']] = $subs;
+                }
+            }
+            if (is_array($categories)) {
+                $select = '<select name="Categories[]" multiple="multiple" size="10">';
+                foreach ($categories as $label => $cat_id) {
+                    $select .= '<optgroup label="'.$label.'">';
+                    foreach ($cat_id as $category_id => $name) {
+                        $select .= '<option value="'.$category_id.'"';
+                        if ($_REQUEST['Categories'] && in_array($category_id, $_REQUEST['Categories'])) {
+                            $select .= 'selected';
+                        }
+                        $select .= '>'.$name.'</option>';
+                    }
+                    $select .= '</optgroup>';
+                }
+                $select .= '</select>';
+            }
+            return $select;
+        } catch(PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+    //  {{{ getNewsletters()
+
+    /**
+     * getNewsletters 
+     * 
+     * @return array
+     * @access public
+     * @throws PEAR_Error
+     */
+    protected function getNewsletters()
+    {
+        $sql = "
+                       SELECT id, subject
+                         FROM news_response
+                        ORDER BY subject";
+        try {
+            $stmt = $this->dbh->query($sql);
+            while ($row = $stmt->fetch()) {
+                $newsletters[$row['id']] = $row['subject'];
+            }
+            return $newsletters;
+        } catch(PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+        }
+    }
+        
+    //  }}}
+
+    //  {{{ recordUrl()
+
+    /**
+     * Returns the url for a member.
+     *
+     * Used when configuring the columns for the data grid. This
+     * function generates the url to get to the member detail page
+     *
+     * @param array $data Structure_DataGrid
+     *
+     * @return string
+     * @access public
+     */
+    public function recordUrl($data)
+    {
+        return "members.php?".
+            "id={$data['record']['member_id']}".
+            "&cat=2".
+            "&subCat=2";
+    }
+
+    //  }}}
+
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery()
+    {
+        $sql = "
+                       SELECT mc.member_id, m.member_name, mc.fname, mc.lname
+                         FROM member m LEFT OUTER JOIN member_contacts mc USING (member_id)";
+        if ($_REQUEST['Categories']) {
+            $where[] = "
+            m.member_id IN 
+                (SELECT member_id
+                FROM    member_category
+                WHERE   category_id IN (".implode(",", $_REQUEST['Categories'])."))";
+        }
+        if ($_REQUEST['Search']) {
+            $where[] = "
+            m.member_name ilike '%{$_REQUEST['Search']}%'";
+        }
+        if (is_array($where)) {
+            $sql .= " WHERE ".implode(" AND ", $where);
+        }
+
+        parent::setQuery($sql);
+    }
+
+    //  }}}
+    //  {{{ setControlObject()
+
+    /**
+     * Sets any control object variables that are going to be used in the template
+     *
+     * @return void
+     * @access public
+     */
+    protected function setControlObject()
+    {
+        $form = new HTML_QuickForm('ReportsListForm', 'get');
+        $form->addElement('hidden', 'cat', $_REQUEST['cat']);
+        $form->addElement('hidden', 'subCat', $_REQUEST['subCat']);
+        $form->addElement('text', 'Search', 'Search', $_REQUEST['Search']);
+        $form->addElement('static', 'Categories', 'Categories', $this->getMemberCats());
+        $form->addElement(
+            'select', 
+            'Output', 
+            'Output', 
+            array(
+                'HTML'=>'HTML',
+                'FILE'=>'FILE'
+            )
+        );
+        $form->addElement('submit', 'reportSubmit', 'Search Contacts');
+        if ($_REQUEST['reportMonth']) {
+            $form->setDefaults(
+                array(
+                    'reportMonth' => $_REQUEST['reportMonth']
+                )
+            );
+        } else {
+            $form->setDefaults(
+                array(
+                    'reportMonth' => date('n').'|'.date('Y')
+                )
+            );
+        }
+        $this->ctrlObj['memberContactSearchForm'] = $form->toHTML();
+        // second form will send the list out to either 
+        // a file download page
+        // or mailout page
+        $form2 = new HTML_QuickForm('memberSendForm', 'get');
+        $form2->addElement('select', 'newsletter', 'Newsletter', $this->getNewsletters());
+        $form2->addElement('submit', 'sendSubmit', 'Send Newsletter');
+        $this->ctrlObj['memberSendForm']          = $form2->toHTML();
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/PaymentController.php b/Toolkit/Members/Admin/PaymentController.php
new file mode 100644 (file)
index 0000000..102bae5
--- /dev/null
@@ -0,0 +1,82 @@
+<?php
+/**
+ * PaymentController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_PaymentController
+ * 
+ * Description of Toolkit_Members_Admin_PaymentController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_PaymentController
+       extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+    
+    /**
+     * Description of getPageLayout()
+     * 
+     * @param string $html Description of $html
+     * 
+     * @return string
+     * @access protected
+     */
+    protected function getPageLayout($html)
+    {
+        $this->registry->controllerObject->content = $html;
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+    }
+    
+    /**
+     * Description of indeAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function indexAction()
+       {
+        $form = new Toolkit_Members_Billing_PaymentForm(
+            Toolkit_Database::getInstance(),
+            'paymentForm',
+            'post',
+            BASE_URL . 'admin/members.php?rt=Payment' 
+        );
+        $form->configureForm();
+        $out = '';
+        if ($_REQUEST['formSubmitGood']) {
+            $out = '<div id="form-success-top">
+                The information below has been successfully submitted.
+            </div>';
+        }
+        $out .= $form->toHtml();
+               return $this->getPageLayout($out);
+       }
+    
+}
diff --git a/Toolkit/Members/Admin/PreviewHtmlEmail.php b/Toolkit/Members/Admin/PreviewHtmlEmail.php
new file mode 100644 (file)
index 0000000..45bb4f2
--- /dev/null
@@ -0,0 +1,145 @@
+<?php
+
+/**
+ * PreviewHtmlEmail.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: PreviewHtmlEmail.php,v 1.3 2009/12/30 16:48:56 matrix Exp $
+ * @link      <>
+ */
+
+/**
+ * Generate a preview of the newsletter
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      <>
+ */
+class Toolkit_Members_Admin_PreviewHtmlEmail
+{
+       //      {{{ properties
+
+       /**
+        * Database Handler
+        *
+        * @var PDO
+        * @access private
+        */
+       private $_dbh;
+
+       /**
+        * Templating engine to use
+        *
+        * @var HTML_Template_Flexy
+        * @access private
+        */
+       private $_tEngine;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO                 $pdo     PHP Data Object
+     * @param HTML_Template_Flexy $tEngine Templating engine to use
+     *
+        * @access public
+        */
+       public function __construct(PDO $pdo, HTML_Template_Flexy $tEngine)
+       {
+               $this->_dbh     = $pdo;
+               $this->_tEngine = $tEngine;
+       }
+
+       //      }}}
+
+    // {{{ _getNewsResponse()
+
+    /**
+     * Get the response field the table based on id
+     *
+     * @param int $id mathe id field
+     *
+     * @return string  Return response
+     * @access private
+     * @throws Toolkit_Members_Exception
+     */
+    private function _getNewsResponse($id)
+    {
+        try {
+            $sql = "
+                               SELECT response
+                                 FROM member_newsletters
+                                WHERE id = :id";
+            $stmt = $this->_dbh->prepare($sql);
+            $stmt->bindParam(":id", $id, PDO::PARAM_INT);
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch(PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               "unable to fetch member newsletter `$id`"
+                       );
+        }
+    }
+    // }}}
+    /**
+     * Renders the preview IFrame for the newsletter preview
+     * inner iframe src is directed to the method renderPreview
+     *
+     * @param int     $id       news id
+     * @param unknown $template template file
+     * 
+     * @return string
+     * @access public
+     */
+    public function renderPreviewIFrame($id, $template)
+    {
+        $page = new stdClass();
+
+        // get data and set response
+        $page->src = BASE_URL . 'admin/members.php?' .
+            'rt=Newsletter&ac=editHtmlEmail&previewFrame=1&news_id=' .
+            $id;
+
+        $this->_tEngine->compile($template);
+        return $this->_tEngine->bufferedOutputObject($page);
+    }
+    // {{{ renderPreview()
+
+    /**
+     * render the preview
+     *
+     * @param int     $id       id of newsletter to preview
+     * @param unknown $template Template to use
+     *
+     * @return string  Return html of template
+     * @access public
+     */
+    public function renderPreview($id, $template)
+    {
+        $page = new stdClass();
+
+        // get data and set response
+        $page->response = $this->_getNewsResponse($id);
+        // set the sitename
+        $page->sitename = SITENAME;
+        // set the cancel email
+        $page->membersEnewsEmail = FROM_MEMBER_NEWS_EMAIL;
+
+        $this->_tEngine->compile($template);
+        return $this->_tEngine->bufferedOutputObject($page);
+    }
+    // }}}
+}
diff --git a/Toolkit/Members/Admin/RegionsController.php b/Toolkit/Members/Admin/RegionsController.php
new file mode 100644 (file)
index 0000000..1c4dc95
--- /dev/null
@@ -0,0 +1,102 @@
+<?php
+/**
+ * RegionsController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_RegionsController
+ * 
+ * Description of Toolkit_Members_Admin_RegionsController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_RegionsController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    /**
+     * Main action for controller. Runs admin template, list out all regions
+     * 
+     * @return string
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $regionList = new Toolkit_Members_Admin_ListRegions($this->registry->dbh);
+               $this->registry->controllerObject->content = $regionList->renderRegions();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     editRegionAction()
+    /**
+     * Description of editRegionAction
+     * 
+     * @return string
+     * @access public 
+     */
+       public function editRegionAction()
+       {
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/edit-region.js';
+
+               $form = new Toolkit_Members_Admin_EditRegion('edit_region');
+        $form->configureForm($this->registry->dbh, $this->registry->config);
+               $this->registry->controllerObject->content = $form->toHtml();
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+       //      {{{     listRegionsAction()
+    /**
+     * Description of listRegionsAction()
+     * 
+     * @return string
+     * @access public
+     */
+       public function listRegionsAction()
+       {
+               return $this->indexAction();
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/ReportsController.php b/Toolkit/Members/Admin/ReportsController.php
new file mode 100644 (file)
index 0000000..eaa89ae
--- /dev/null
@@ -0,0 +1,175 @@
+<?php
+/**
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AdvancedSearch.php,v 1.14 2010/08/15 19:35:15 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Admin_ReportsController
+ *
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_ReportsController
+       extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+    /**
+     * Runs admin template, list out all regions
+     * 
+     * @param string $html html
+     * 
+     * @return string
+     * @access protected 
+     */
+    protected function getPageLayout($html)
+    {
+        $GLOBALS['styleSheets'][]
+            = BASE_URL . 'Toolkit/Members/Billing/billing.css';
+        $this->registry->controllerObject->content = $html;
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+    }
+    
+    /**
+     * Description for indexAction
+     * 
+     * @return string 
+     * @access public
+     */
+       public function indexAction()
+       {
+               return $this->getPageLayout('');
+       }
+    
+    /**
+     * Description of accountByAgeAction
+     * 
+     * @return string
+     * @access public
+     */
+    public function accountByAgeAction()
+    {
+        $mc  = new Toolkit_Members_Billing_MemberLists(
+            Toolkit_Database::getInstance()
+        );
+        $out = $mc->getAccountsByAge();
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     * Description of openAccountsAction
+     * 
+     * @return string
+     * @access public 
+     */
+    public function openAccountsAction()
+    {
+        $mc  = new Toolkit_Members_Billing_MemberLists(
+            Toolkit_Database::getInstance()
+        );
+        $out = $mc->getOpenAccounts();
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     * Description of closedAccounts()
+     * 
+     * @return string
+     * @access public
+     */
+    public function closedAccounts()
+    {
+        $mc  = new Toolkit_Members_Billing_MemberLists(
+            Toolkit_Database::getInstance()
+        );
+        $out = $mc->getClosedAccounts();
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     * Description for allAccountsAction()
+     * 
+     * @return string
+     * @access public 
+     */
+    public function allAccountsAction()
+    {
+        $mc  = new Toolkit_Members_Billing_MemberLists(
+            Toolkit_Database::getInstance()
+        );
+        $out = $mc->getAllAccounts();
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     *Description for noAccountsAction()
+     * 
+     * @return string
+     * @access public  
+     */
+    public function noAccountsAction()
+    {
+        $mc  = new Toolkit_Members_Billing_MemberLists(
+            Toolkit_Database::getInstance()
+        );
+        $out = $mc->getAccountsNeedingData();
+        return $this->getPageLayout($out);
+    }
+    
+    /**
+     * Description for searchReportsAction()
+     * 
+     * @return string
+     * @access public
+     */
+    public function searchReportsAction()
+    {
+        $dbh = Toolkit_Database::getInstance();
+        $form = new Toolkit_Members_Billing_ReportSearch(
+            'search-reports',
+            'get',
+            'members.php',
+            null,
+            null,
+            null
+        );
+        $form->configureForm();
+        $reports = new Toolkit_Members_Billing_Report(
+            $dbh,
+            null,
+            null,
+            null
+        );
+        $params = $reports->setQuery();
+        if ($_REQUEST['report_type'] == 'file') {
+            $reports->exportFile($dbh, $params);
+            exit;
+            return '<pre>'.print_r($_REQUEST, true).'</pre>
+                <pre>'.print_r($params, true).'</pre>';
+        }
+        $out = $form->toHtml()
+           . $reports->toHTML()
+           . $reports->getGrandTotals($dbh, $params);
+        return $this->getPageLayout($out);
+    }
+}
diff --git a/Toolkit/Members/Admin/Search.php b/Toolkit/Members/Admin/Search.php
new file mode 100644 (file)
index 0000000..279e45a
--- /dev/null
@@ -0,0 +1,468 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Admin search functionality for memberdb
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Search.php,v 1.18 2010/05/25 14:01:21 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form to search the members database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Admin_Search
+    extends Toolkit_FormBuilder implements Toolkit_Form
+{
+       //      {{{     properties
+
+       /**
+        * The default rules to register for validating
+        *
+        * We have to register these rules, or any others we want, before
+        * we are able to use them in our forms.
+        *
+        * @var         string
+        * @access      protected
+        */
+       protected $registeredRules = array('zip');
+
+       //      }}}
+
+       //      {{{     __construct()
+
+       /**
+        * Constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @see    HTML_QuickForm
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+               $this->template = BASE . 'Toolkit/Members/templates/currentTables/';
+       }
+
+       //      }}}
+
+       //      {{{ configureConstants()
+
+    /**
+     * Form constant definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+               $c = array(
+                       'page' => 'members',
+                       'module' => 'listMembers',
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements(Config_Container $c)
+       {
+        $e = array();
+
+        //  get reference to [listing type] section of config file
+        $config =& $c->getItem('section', 'listing type');
+        //  get coupon
+        $singularDirective =& $config->getItem('directive', 'singular');
+        $singularType = $singularDirective->getContent();
+        $pluralDirective =& $config->getItem('directive', 'plural');
+        $pluralType = $pluralDirective->getContent();
+
+        //  get reference to [conf] section of config file
+        $config =& $c->getItem('section', 'conf');
+        //  get controlled cities
+        $ctrlCtyDirective =& $config->getItem('directive', 'controlledCities');
+
+               $states = $this->_getStates();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'page'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'module'
+        );
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'categoryInfoHdr',
+            'display' => 'Search by Category'
+        );
+               $e[] = array(
+            'type' => 'selectglm',
+            'req' => false,
+            'name' => 'category',
+            'display' => 'Category',
+            'opts' => array(
+               '' => array(
+                       'level' => -1,
+                                       'name' => '-- All --'
+                               )
+                       ) + $this->_getCategories()
+        );
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'recordInfoHdr',
+            'display' => "Find $pluralType",
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'name',
+            'display' => "$singularType Name"
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'email',
+            'display' => "$singularType Email"
+        );
+        if ($ctrlCtyDirective->getContent()) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'city_id',
+                'display' => 'City',
+                'opts'    => $this->getCities(),
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => false,
+                'name'    => 'city',
+                'display' => 'City',
+            );
+        }
+               $e[] = array(
+            'type' => 'select',
+            'req' => false,
+            'name' => 'state',
+            'display' => 'State',
+            'opts' => $states
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'zip',
+            'display' => 'Zip'
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Search'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(Config_Container $c)
+    {
+        $this->configureElements($c);
+        $this->configureRules();
+        $this->configureFilters();
+        $this->configureConstants();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+        $r = array();
+               $r[] = array(
+            'element' => 'member_contact_email',
+            'message' => 'ERROR: Invalid Email Address!',
+            'type' => 'email',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'category',
+            'message' => 'ERROR: Invalid Category!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'state_id',
+            'message' => 'ERROR: Invalid State!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'zip',
+            'message' => 'ERROR: Invalid Zip!',
+            'type' => 'zip',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     _getCategories()
+
+    /**
+     * get all the categories available in alpha order
+     *
+     * @return array alpha order of categories available in the DB
+     * @access private
+     */
+       private function _getCategories()
+       {
+               $categories = Toolkit_Common::getHierarchicalTreeStructure(
+                       $this->dbh,
+            'category',
+            'category_id',
+            'parent_id',
+                       'name'
+        );
+               //  Get only the active categories from
+               //  the nav structure for our select list.
+               $sql = "
+                       SELECT category_id, name
+                         FROM category
+                        WHERE category_id = :id";
+
+               $stmt = $this->dbh->prepare($sql);
+
+               foreach ($categories as $k => $v) {
+                       unset($row, $category);
+                       $stmt->bindParam(':id', $k, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       //  If we actually retrieved a row, add it to the select list
+                       //  after we clean it up.
+                       if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $pages[$k] = array(
+                                       'level' => $v - 1,
+                                       'name' => $row['name']
+                               );
+                       }
+               }
+
+               return $pages;
+       }
+
+       //      }}}
+       //      {{{ getCities()
+
+       /**
+        * Configure the cities for member stored in the database into an array
+        *
+     * @return array the cities
+        * @access protected
+        */
+       protected function getCities()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM city
+                                ORDER BY city_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $cities[$row['city_id']] = $row['city_name'];
+                       }
+                       if (!empty($cities)) {
+                               $cities = array('' => '-- Select --') + $cities;
+                       } else {
+                               $cities = array('' => '-- No Cities Created Yet -- ');
+                       }
+                       return $cities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     _getStates()
+
+    /**
+     * get all the statis available in alpha order
+     *
+     * @return array alpha order of states available in the DB
+     * @access private
+     */
+       private function _getStates()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM state
+                 ORDER BY state_name";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute();
+                       $stmt->bindColumn('state_id', $cid);
+                       $stmt->bindColumn('state_name', $name);
+
+                       $states = array('' => '-- Select --');
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $states[$cid] = $name;
+                       }
+
+                       return $states;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $tpl = '<tr align="center"><td colspan="2">{element}</td></tr>';
+               $renderer->setElementTemplate($tpl, 'submit');
+       }
+
+    //  @codeCoverageIgnoreEnd
+       //      }}}
+
+       //      {{{     toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+        * @access protected
+        * @return string $output The Form to be rendered or success msg.
+        */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       $output = parent::toHTML();
+               } elseif ($this->isSubmitted()) {
+                       $output = $this->errorMsg;
+                       $output .= parent::toHTML();
+               } else {
+                       $output = parent::toHTML();
+               }
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Admin/SettingsController.php b/Toolkit/Members/Admin/SettingsController.php
new file mode 100644 (file)
index 0000000..2b2d70e
--- /dev/null
@@ -0,0 +1,77 @@
+<?php
+/**
+ * SettingsController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_SettingsController
+ * 
+ * Description of Toolkit_Members_Admin_SettingsController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Admin_SettingsController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+    /**
+     * Main action for controller. Runs admin template, list out all regions
+     * 
+     * @return string
+     * @access public
+     */
+       public function indexAction()
+       {
+               $settingsControllerObject = new stdClass();
+               $dom = new DOMDocument();
+               $dom->loadHTML($this->registry->controllerObject->nav);
+
+               $uls = $dom->getElementsByTagName('ul');
+               $ul = $uls->item(1);
+               $ul->setAttribute('class', 'settings');
+
+               $anchors = $ul->getElementsByTagName('a');
+               foreach ($anchors as $anchor) {
+                       $anchor->removeAttribute('class');
+               }
+               $settingsControllerObject->nav = substr(
+                       $dom->saveXML($dom->getElementsByTagName('ul')->item(1)),
+                       0
+               );
+
+               $this->registry->tEngine->compile('settings.html');
+               $this->registry->controllerObject->content =
+                       $this->registry->tEngine->bufferedOutputObject($settingsControllerObject);
+
+               $this->registry->controllerObject->topScripts
+                       = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $this->registry->controllerObject->bottomScripts
+                       = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $this->registry->controllerObject->styles
+                       = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+               $this->registry->tEngine->compile('admin.tpl');
+               return $this->registry->tEngine->bufferedOutputObject(
+                       $this->registry->controllerObject
+               );
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Auth.php b/Toolkit/Members/Auth.php
new file mode 100644 (file)
index 0000000..f9c1962
--- /dev/null
@@ -0,0 +1,736 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Member Authentication
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Auth.php,v 1.22 2010/08/10 18:08:44 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm
+ */
+
+require_once 'Auth.php';
+
+/**
+ * Methods for the memberdb authentication system
+ *
+ * Handles Cookie and session generation, id challenges and security for
+ * the memberdb application
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm
+ */
+class Toolkit_Members_Auth extends Auth
+{
+       //      {{{     properties
+
+    /**
+     * Maximum idle time
+        *
+        * If more seconds pass before a new page request, then the user
+        * will have to re-authenticate back into the application.
+        * 1800 = 30 min
+        * 3600 = 1 hr
+        *
+     * @var    integer
+     * @access protected
+     */
+       protected $idleTime = 1800;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * Sets up the storage driver
+     *
+     * @param Config_Container              $c             Configuration object
+     * @param Toolkit_Members_AuthContainer $storageDriver storage driver
+     * @param string                        $loginFunction (optional)Name of the function
+     *                                                     that creates the login form
+     * @param boolean                       $showLogin     (optional)Should the login form
+     *                                                     be displayed if neccessary?
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+        Config_Container $c,
+        Toolkit_Members_AuthContainer $storageDriver,
+        $loginFunction = '',
+        $showLogin = true
+    ) {
+        $this->config = $c;
+
+               parent::Auth($storageDriver, '', $loginFunction, $showLogin);
+       }
+
+       //      }}}
+
+       //      {{{     loginForm()
+
+    /**
+     * Function to set up the regular login form
+     *
+     * @param unknown $uname  Last attempted username
+     * @param unknown $status The authorization status
+     * @param unknown &$auth  The authentication object
+        *
+     * @return void
+     * @access public
+     */
+       protected function loginForm($uname = null, $status = null, &$auth = null)
+       {
+               $login = new LoginForm(
+                       'member_login',
+            'post',
+            BASE_URL . 'members-only-area/'
+               );
+
+        $login->setDbh(Toolkit_Database::getInstance());
+        $login->configureForm($auth->config);
+        echo $login->toHtml();
+       }
+
+       //      }}}
+
+       //      {{{     passwordForm()
+
+    /**
+     * Function to set up the forgot password form
+     *
+     * @return void
+     * @access public
+     */
+       protected function passwordForm()
+       {
+               $pword = new PasswordForm('member_password');
+        $pword->setDbh(Toolkit_Database::getInstance());
+        $pword->configureForm();
+               echo $pword->toHtml();
+       }
+
+       //      }}}
+
+       //      {{{     setIdle()
+
+    /**
+     * Set the maximum idle time
+     *
+     * @param integer $time time in seconds
+     * @param boolean $add  (optional)add time to current maximum idle time or not
+        *
+     * @return void
+     * @access public
+     */
+       public function setIdle($time = null, $add = false)
+       {
+               $time = is_null($time) ? $this->idleTime : $time;
+               parent::setIdle($time, $add);
+       }
+
+       //      }}}
+}
+
+/**
+ * Handles rendering and validating the member login form
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_FormBuilder
+ */
+class LoginForm extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Custom rules to check for when validating the form
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Where to perform validation
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $validationType = 'client';
+
+       //      }}}
+
+       //      {{{     configureElements()
+
+    /**
+     * Sets up the elements to be configured for use with the form
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureElements(Config_Container $c)
+       {
+        $e = array();
+
+        //  get reference to [listing type] section of config file
+        $config =& $c->getItem('section', 'listing type');
+        $singularDirective =& $config->getItem('directive', 'singular');
+        $singularType = $singularDirective->getContent();
+
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'formHdr',
+            'display' => "$singularType Login"
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'username',
+            'display' => 'Username'
+        );
+               $e[] = array(
+            'type' => 'password',
+            'req' => true,
+            'name' => 'password',
+            'display' => 'Password'
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'doLogin',
+            'display' => 'Login now',
+            'opts' => array('id' => 'doLogin')
+        );
+               $e[] = array(
+            'type' => 'link',
+            'req' => false,
+            'name' => 'forgot',
+            'display' => 'Forgot your password? Click',
+            'opts' => BASE_URL . 'index.php?catid='.MEMBERS_CATEGORY.'&forgot=',
+            'att' => 'here'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Sets up the filters to be used with the form when submitted
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper method to setup form
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(Config_Container $c)
+    {
+        $this->configureElements($c);
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{     configureRules()
+
+    /**
+     * Sets up required rules and extra defined rules for the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureRules()
+       {
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+    //  {{{ setDbh()
+
+    /**
+     * set the pdo to use for db calls
+     *
+     * @param PDO $pdo PHP Data Object to use
+     *
+     * @return void
+     * @access public
+     */
+    public function setDbh(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+
+    //  }}}
+       //      {{{     setupRenderers()
+
+    /**
+     * Inject custom renderers into the forms elements for custom display
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="form-warning-inside">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate('<tr><td colspan="2" class="member-login-forgot">{label} {element}</td></tr>', 'forgot');
+               $renderer->setElementTemplate('<tr><td colspan="2" align="center">{element}</td></tr>', 'doLogin');
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Returns an HTML version of the form
+     *
+     * @return string HTML version of the form
+     * @access public
+     */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       header('Location: ' . BASE_URL . 'memberdb/index.php');
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHtml();
+               } else {
+                       if ($_GET['status']) {
+                               switch ($_GET['status']) {
+                               case -1 :
+                                       $error = 'Your session has exceeded the maximum idle time';
+                                       break;
+
+                               case -2 :
+                                       $error = 'Your session has expired.';
+                                       break;
+
+                               case -3 :
+                                       $error = 'Invalid username or password.';
+                                       break;
+
+                               case -4 :
+                                       //      This is primarily used for Development.
+                                       //      Users should never be presented with this error.
+                                       $error = 'Invalid Container';
+                                       break;
+
+                               case -5 :
+                                       //      This is only thrown if the advanced security system
+                                       //      has detected a breach into the system.
+                                       $error = 'The system has encountered an error. Reference code: -5';
+                                       break;
+                               }
+                               $output = "<div id=\"form-warning-top\">$error</div>";
+                       }
+                       $output .= parent::toHtml();
+               }
+
+               return $output;
+       }
+
+       //      }}}
+}
+
+/**
+ * Handles rendering and validating the member password form
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_FormBuilder
+ */
+class PasswordForm extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Table to query when gathering information
+        *
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'member';
+
+    /**
+     * Custom defined rules to validate against when the form is submitted
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Where to perform validation
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $validationType = 'client';
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param string  $formName    Form's name
+     * @param string  $method      (optional)Form's method defaults to 'POST'
+     * @param string  $action      (optional)Form's action
+     * @param string  $target      (optional)Form's target
+     * @param mixed   $attributes  (optional)Extra attributes for the <form> tag
+     * @param boolean $trackSubmit (optional)Whether to track if the form
+        *                                                         was submitted by adding a special hidden field
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               $this->template = dirname(__FILE__) . '/templates/currentTables/';
+       }
+
+       //      }}}
+
+       //      {{{     checkAddressExists()
+
+    /**
+     * Checks to see if the email address exists before allowing an email to go out
+     *
+     * @param string $value submitted email address
+        *
+     * @return boolean If the email address exists or not
+     * @access public
+     */
+       public function checkAddressExists($value)
+       {
+               try {
+                       $sql = "
+                SELECT count(*) AS total
+                  FROM {$this->tableName}
+                 WHERE member_contact_email = :mce";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mce', $value, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $stmt->bindColumn('total', $exists);
+                       $stmt->fetch();
+
+                       return (bool) $exists;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     configureElements()
+
+    /**
+     * Sets up the elements to be configured for use with the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureElements()
+       {
+        $e = array();
+
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'formHdr',
+            'display' => 'Email Reminder'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'email',
+            'display' => 'Your Member Contact Email Address'
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Send'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Sets up the filters to be used with the form when submitted
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper method to setup form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{     configureRules()
+
+    /**
+     * Sets up required rules and extra defined rules for the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureRules()
+       {
+        $r = array();
+
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Invalid Email Format!',
+            'type' => 'email',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Cannot locate email address!',
+            'type' => 'callback',
+            'format' => array(&$this,
+            'checkAddressExists'),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+    //  {{{ setDbh()
+
+    /**
+     * set the pdo to use for db calls
+     *
+     * @param PDO $pdo PHP Data Object to use
+     *
+     * @return void
+     * @access public
+     */
+    public function setDbh(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+
+    //  }}}
+       //      {{{     setupRenderers()
+
+    /**
+     * Inject custom renderers into the forms elements for custom display
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="form-warning-inside">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate('<tr><td colspan="2" align="center">{element}</td></tr>', 'submit');
+       }
+
+       //      }}}
+
+       //      {{{     processData()
+
+    /**
+     * Processes the data submitted by the form
+     *
+        * Gets the login credentials for the matching email address and mails
+        * them to that email address
+     *
+     * @param array $values submitted form values
+        *
+     * @return boolean Result of mail
+     * @access protected
+     */
+       protected function processData($values)
+       {
+               try {
+                       $sql = "
+                SELECT member_login, member_passwd
+                  FROM {$this->tableName}
+                 WHERE member_contact_email = :mce";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mce', $values['email'], PDO::PARAM_STR);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handlError($e);
+               }
+
+               $htmlMsg
+                       = "Here is your " . SITENAME . " password:<br><br>" .
+                         "Login: {$row['member_login']}<br>" .
+                         "Email: {$values['email']}<br>" .
+                         "Password: {$row['member_passwd']}<br><br>";
+
+               $msg
+                       = "Here is your " . SITENAME . " password:\n\n" .
+                         "Login: {$row['member_login']}\n" .
+                         "Email: {$values['email']}\n" .
+                         "Password: {$row['member_passwd']}";
+
+               $mimeMail = new Mail_mime("\n");
+               $mimeMail->setHTMLBody($htmlMsg);
+               $mimeMail->setTXTBody($msg);
+
+               $body = $mimeMail->get();
+               $hdrs = $mimeMail->headers(
+                       array(
+                               'From' => DO_NOT_REPLY_EMAIL,
+                               'Subject' => 'Your ' . htmlspecialchars_decode(SITENAME) . ' Password',
+                               'Reply-To' => SITENAME . '<' . MEMBER_FORGOT_PASSWORD_EMAIL_REPLY_TO . '>'
+                       )
+               );
+
+               $mail =& Mail::factory('mail');
+
+               $res = $mail->send($values['email'], $hdrs, $body);
+
+               return PEAR::isError($res) ?
+                               Toolkit_Common::handleError($res) :
+                               $res;
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Returns an HTML version of the form
+     *
+     * @return string HTML version of the form
+     * @access public
+     */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       if ($this->process(array(&$this, 'processData'))) {
+                               $url    = BASE_URL . 'index.php?catid=' . MEMBERS_CATEGORY;
+                               $e      =& $this->getElement('email');
+                               $email  = $e->getValue();
+                               $output
+                    = "<p>Your Login Information has been sent to $email</p>" .
+                                         "<p>Continue to <a href=\"$url\">Member Login</a></p>";
+                       } else {
+                               $output = '<p>Email address not found.</p>';
+                       }
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHtml();
+               } else {
+                       $output .= parent::toHtml();
+               }
+
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/AuthContainer.php b/Toolkit/Members/AuthContainer.php
new file mode 100644 (file)
index 0000000..d5a7649
--- /dev/null
@@ -0,0 +1,203 @@
+<?php
+
+/**
+ * Authentication container for members only area
+ *
+ * Custom container which allows us to utilize our PDO Singleton which
+ * takes advantage of schema based partitioning of our tables
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id: AuthContainer.php,v 1.3 2010/06/22 11:45:34 jamie Exp $
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Authentication container for members only area
+ *
+ * Custom container which allows us to utilize our PDO Singleton which
+ * takes advantage of schema based partitioning of our tables
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_AuthContainer extends Auth_Container
+{
+       //      {{{     properties
+
+    /**
+     * Database handler
+     * @var    PDO
+     * @access private
+     */
+       private $_dbh;
+
+       /**
+        * Addition options for the storage container
+        * @var array
+        * @access private
+        */
+       private $_options = array();
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param PDO   $dbh     Database handler
+     * @param array $options Addition options for the storage container
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(PDO $dbh, array $options = null)
+       {
+               $this->_dbh = $dbh;
+               $this->_setDefaults();
+               if (is_array($options)) {
+                       $this->_parseOptions($options);
+               }
+       }
+
+       //      }}}
+       //      {{{     _setDefaults()
+
+       /**
+        * Set some default options
+        *
+        * @access private
+        * @return void
+        */
+       private function _setDefaults()
+       {
+               $this->_options['table']       = 'member';
+               $this->_options['usernamecol'] = 'member_login';
+               $this->_options['passwordcol'] = 'member_passwd';
+               $this->_options['db_fields']   = '';
+               $this->_options['cryptType']   = 'md5';
+               $this->_options['db_where']    = '';
+       }
+
+       //      }}}
+       //      {{{     _parseOptions()
+
+       /**
+        * Parse options passed to the container class
+        *
+        * @param array $array options for class
+        *
+        * @access private
+        * @return void
+        */
+       private function _parseOptions(array $array)
+       {
+               foreach ($array as $key => $value) {
+                       if (isset($this->_options[$key])) {
+                               $this->_options[$key] = $value;
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     fetchData()
+
+    /**
+     * Get the user information from the database
+     *
+     * @param string $username username to authenticate
+     * @param string $password password to authenticate against username
+        *
+     * @return boolean If the user was authenticated or not
+     * @access public
+     * @throws Toolkit_Members_Exception upon error querying DB for user
+     */
+       public function fetchData($username, $password)
+       {
+               if (   is_string($this->_options['db_fields'])
+                       && strstr($this->_options['db_fields'], '*')
+               ) {
+                       $sqlFrom = '*';
+               } else {
+                       $sqlFrom  = $this->_options['usernamecol'];
+                       $sqlFrom .= ', ' . $this->_options['passwordcol'];
+
+                       if (strlen($fields = $this->_getDBFields()) > 0) {
+                               $sqlFrom .= ", $fields";
+                       }
+
+               }
+
+               $pword = ($this->_options['cryptType'] == 'md5') ? 'MD5(:pword)' : ':pword';
+
+               $sql = "
+            SELECT $sqlFrom
+              FROM {$this->_options['table']}
+             WHERE {$this->_options['usernamecol']} = :uname
+               AND {$this->_options['passwordcol']} = $pword";
+
+
+               //      check if there is an optional parameter db_where
+               if ($this->_options['db_where'] != '') {
+                       //      There is one, so add it to the query
+                       $sql .= " AND {$this->_options['db_where']}";
+               }
+
+               try {
+                       $stmt = $this->_dbh->prepare($sql);
+                       $stmt->bindParam(':uname', $username, PDO::PARAM_STR);
+                       $stmt->bindParam(':pword', $password, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       if ($row !== false) {
+                               foreach ($row as $key => $value) {
+                                       $this->_auth_obj->setAuthData($key, $value);
+                               }
+                               return true;
+                       }
+
+                       return false;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               "Error validating user `$username` - `$password`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     _getDBFields()
+
+       /**
+        * Get extra db fields to fetch and set in the auth data
+        *
+        * @return array comma separated string of extra db fields for a SQL query
+        * @access private
+        */
+       private function _getDBFields()
+       {
+               if (isset($this->_options['db_fields'])) {
+                       if (is_array($this->_options['db_fields'])) {
+                               return implode(', ', $this->_options['db_fields']);
+                       }
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Auxiliary.php b/Toolkit/Members/Auxiliary.php
new file mode 100644 (file)
index 0000000..a496b80
--- /dev/null
@@ -0,0 +1,404 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: Auxiliary.php,v 1.18 2010/08/09 17:57:37 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Base class used for building forms to accompany the members database
+ *
+ * This class handles all common functions that are to be used in
+ * the auxiliary forms used to assist in the members DB.
+ * (categories, amenities, regions, etc...).
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Auxiliary.php,v 1.18 2010/08/09 17:57:37 jamie Exp $
+ * @see       Toolkit_Members, member_admin
+ */
+abstract class Toolkit_Members_Auxiliary
+    extends Toolkit_FormBuilder implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * Primary table used for database calls
+        *
+        * @var         String
+        * @access      Public
+        */
+       public $tableName;
+
+       /**
+        * Array of primary table meta data
+        *
+        * This array will hold the column data types for the fields
+        * that will be manipulated in the database.
+        *
+        * @var         Array
+        * @access      Public
+        */
+       public $tableMetaData;
+
+       /**
+        * The name of the template used for the form
+        *
+        * @var         String
+        * @access      Protected
+        */
+       protected $formTemplate;
+
+       /**
+        * The object to use inside the form
+        *
+        * This object which is to be populated by the $this object
+        * is used inside the templates and allows access back into the
+        * calling class to call publicly available functions
+        *
+        * @var         String
+        * @access      Protected
+        */
+       protected $view;
+
+    /**
+     * rules to use with the form
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Setup options to use for rendering the template engine
+     * @var    array
+     * @access protected
+     */
+       protected $flexyOptions = array();
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        */
+       public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Configure the default values for the form
+        *
+        * Since each form is different, you will need to redefine this
+        * method inside of each subclass and create your own rules
+        * based on your forms elements.
+        *
+        * @return void
+        * @access public
+        */
+       abstract protected function configureDefaults();
+
+       //      }}}
+       //      {{{ configureFilters()
+
+       /**
+        * Defines all filters used on form elements when submitted
+        *
+        * Most times this function won't need to be overridden.
+        *
+        * @return void
+        * @access public
+        */
+       protected function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+
+       //      {{{ getSetParameters()
+
+       /**
+     * get a string of sql query parameters
+     *
+     * @param array $values parameters to include
+     *
+     * @return string sql query parameters
+        * @access protected
+        */
+       protected function getSetParameters($values)
+       {
+               $params = array_keys($values);
+               $length = count($params);
+               for ($i = 0; $i < $length; ++$i) {
+                       $bindParams .= "{$params[$i]} = :{$params[$i]}";
+            if ($i < ($length - 1)) {
+                $bindParams .= ', ';
+            }
+               }
+               return $bindParams;
+       }
+
+       //      }}}
+       //      {{{ getDataType()
+
+       /**
+     * Get the data type of the element
+     *
+     * @param string $k element name
+     *
+     * @return element type in the DB
+        * @access protected
+        */
+       protected function getDataType($k)
+       {
+               $metaData = $this->tableMetaData[$k];
+               if ($metaData == 'integer') {
+                       return PDO::PARAM_INT;
+               } else if ($metaData == 'boolean') {
+                       return PDO::PARAM_BOOL;
+               } elseif ($metaData == 'double precision') {
+                       return null;
+               } else {
+                       return PDO::PARAM_STR;
+               }
+       }
+
+       //      }}}
+
+       //      {{{ isEdit()
+
+       /**
+        * Determines if we are editing an object or not
+        *
+        * If we are ever editing an object, member, category, etc...
+        * There will be the objects DB ID passed along in the url under the
+        * id key.  If we can find this then we know we're editing, if not
+        * then we are adding.
+        *
+        * @return boolean if the key id is set in the $_GET array
+        * @access public
+        */
+       public function isEdit()
+       {
+               return isset($_GET['id']);
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+    /**
+     * clean unneeded form elements out of the submitted values array
+     *
+     * @param array $values QuickForm submitted elements
+     *
+     * @return boolean Result of insert/update functions
+     * @access public
+     */
+       public function processData($values)
+       {
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       case 'MAX_FILE_SIZE' :
+                               unset($values[$k]);
+                               break;
+
+                       default :
+                if (substr($k, -4) == '_rmv') {
+                                       unset($values[$k]);
+                               }
+                               break;
+                       }
+               }
+
+        $function = is_numeric($_GET['id']) ? 'updateData' : 'insertData';
+        return $this->$function($values);
+       }
+
+       //      }}}
+
+       //      {{{ setupElements()
+
+       /**
+        * Add the form elements defined in your class to a QuickForm
+        *
+        * Handles adding singleton elements as well as grouped elements.
+        * If added elements fail to correctly add to the form, the script
+        * should die gracefully, telling the user there was a problem.
+        *
+     * @param array $elements element definitions to setup
+     *
+        * @return void
+        * @throws HTML_QuickForm_Error error raised from QuickForm class.
+        * @access protected
+        */
+       protected function setupElements($elements)
+       {
+               $this->formElements = $elements;
+               foreach ($elements as $e) {
+                       if ($e['type'] != 'group') {
+                               try {
+                                       $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']);
+                               } catch (HTML_QuickForm_Error $e) {
+                                       Toolkit_Common::dieGracefully(null, $e);
+                               }
+                               if ($e['type'] == 'advmultiselect') {
+                                       $source->setLabel($e['labels']);
+                               }
+                               if ($e['name'] == 'categories') {
+                                       $res = $source->loadArray($this->categories);
+                                       if (PEAR::isError($res)) {
+                                               Toolkit_Common::dieGracefully(null, $res);
+                                       }
+                               }
+                               if ($e['type'] == 'header') {
+                                       $this->formHeaders[$e['display']] = $e;
+                               }
+                       } elseif (is_array($e['group'])) {
+                               unset($field);
+                               foreach ($e['group'] as $g) {
+                                       $field[] = HTML_QuickForm::createElement($g['type'], $g['name'], $g['display'], $g['opts'], $g['att'], $g['val']);
+                               }
+                               $source = $this->addGroup($field, $e['name'], $e['label'], $e['seperator'], $e['appendName']);
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ setupRenderers()
+
+       /**
+     * Set up the rendering engine templates
+     *
+     * @return void
+        * @access protected
+        */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+               $this->view->form = $renderer->toObject();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form for viewing
+        *
+        * This function validates the form if needed, and if it successfully
+        * validates attempts to insert or update the data record.
+        * If it is unsuccessful, it will return an error to the user
+        * informing them of what went wrong.
+        *
+        * @param string $listPage The page the header should redirect
+        *                                                 to on successful insert or update.
+        *
+        * @return string The compiled and filled form template.
+        * @access public
+        */
+       public function toHtml($listPage = 'index.php')
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+               $this->setupRenderers();
+
+               if ($this->validated) {
+                       $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+                       if ($processed) {
+                               header("Location: $listPage");
+                       } else {
+                $this->validated = false;
+                               $errorMsg = "There was an unexpected error. Please try again later.";
+                       }
+               }
+
+               return $errorMsg . $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+       //      {{{ validated()
+
+       /**
+        * Returns form message from validation attempts
+        *
+     * @return void
+        * @access public
+        */
+       public function validated()
+       {
+               if ($this->validated) {
+                       return $this->successMsg;
+               } elseif ($this->isSubmitted()) {
+                       return $this->errorMsg;
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Billing/AdminNavigation.php b/Toolkit/Members/Billing/AdminNavigation.php
new file mode 100644 (file)
index 0000000..bbb506b
--- /dev/null
@@ -0,0 +1,143 @@
+<?php
+/**
+ * AdminNavigation.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Billing_AdminNavigation
+ * 
+ * Description of Toolkit_Members_Billing_AdminNavigation
+ * 
+ * @category  Toolkit
+ * @package   Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Billing_AdminNavigation
+{
+    /**
+     * Description of getNavigationArray
+     * 
+     * @param Config_Container $c Description of $c
+     * 
+     * @return string 
+     * @access public
+     */
+    public function getNavigationArray(Config_Container $c)
+    {
+        $nav = array(
+            'Title'  => 'Billing',
+            'url'    => BASE_URL . 'admin/members.php?rt=Billing',
+            'desc'   => 'Billing Module',
+            'sub'    => array(
+                'PaymentType' => array(
+                    'Title'  => 'Payment Types',
+                    'url'    => BASE_URL
+                        . 'admin/members.php?rt=Billing&ac=PaymentType',
+                    'desc'   => 'Payment Types'
+                ),
+                'EditPaymentType' => array(
+                    'Title'   => 'Add Payment Type',
+                    'url'     => BASE_URL
+                        . 'admin/members.php?rt=Billing&ac=EditPaymentType',
+                    'desc'    => 'Add a Payment Type'
+                ),
+                'Invoicing' => array(
+                    'Title'   => 'Invoicing',
+                    'url'     => BASE_URL . 'admin/members.php?rt=Invoicing',
+                    'desc'    => 'Invoicing',
+                    'sub'     => array(
+                        'createInvoices' => array(
+                            'Title'  => 'Create Invoices',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Invoicing&ac=createInvoices',
+                            'desc'   => 'Create Invoices'
+                        ),
+                        'printInvoices' => array(
+                            'Title'  => 'Print Invoices',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Invoicing&ac=printInvoices',
+                            'desc'   => 'Print Out Invoices'
+                        ),
+                        'createLabels' => array(
+                            'Title'  => 'Create Labels',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Invoicing&ac=createLabels',
+                            'desc'   => 'Create Mailing Labels'
+                        ),
+                        'sendEmail' => array(
+                            'Title'  => 'Send Email',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Invoicing&ac=sendEmail',
+                            'desc'   => 'Send Invoices by Email'
+                        )
+                    )
+                ),
+                'Reports' => array(
+                    'Title'   => 'Reports',
+                    'url'     => BASE_URL
+                        . 'admin/members.php?rt=Reports',
+                    'desc'    => 'Billing Reports',
+                    'sub'    => array(
+                        'openAccounts' => array(
+                            'Title'  => 'Open Accounts',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Reports&ac=openAccounts',
+                            'desc'   => 'Show All Open Accounts'
+                        ),
+                        'closedAccounts' => array(
+                            'Title'  => 'Closed Accounts',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Reports&ac=closedAccounts',
+                            'desc'   => 'Show All Closed Accounts'
+                        ),
+                        'accountByAge' => array(
+                            'Title'  => 'Accounts By Age',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Reports&ac=accountByAge',
+                            'desc'   => 'Show Accounts By Age'
+                        ),
+                        'searchReports' => array(
+                            'Title'  => 'Report Generator',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Reports&ac=searchReports',
+                            'desc'   => 'List All'
+                        ),
+                        'noAccounts' => array(
+                            'Title'  => 'No Accounts',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Reports&ac=noAccounts',
+                            'desc'   => 'show member without account data'
+                        ),
+                        'allAccounts' => array(
+                            'Title'  => 'All Accounts',
+                            'url'    => BASE_URL
+                                . 'admin/members.php?rt=Reports&ac=allAccounts',
+                            'desc'   => 'Show All Accounts'
+                        ),
+                    )
+                ),
+                'Payment' => array(
+                    'Title'  => 'Make Payment',
+                    'url'    => BASE_URL
+                        . 'admin/members.php?rt=Payment',
+                    'desc'   => 'scan or enter invoiceid for payment'
+                )
+            )
+        );
+        return $nav;
+    }
+}
diff --git a/Toolkit/Members/Billing/Auxiliary.php b/Toolkit/Members/Billing/Auxiliary.php
new file mode 100644 (file)
index 0000000..af792ba
--- /dev/null
@@ -0,0 +1,402 @@
+<?php
+
+/**
+ * Auxiliary.php
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Billing_Auxiliary
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+abstract class Toolkit_Members_Billing_Auxiliary
+    extends Toolkit_FormBuilder
+{
+
+    /**
+     * Base of the billing template directory
+     *  
+     * @var string
+     * @access protected
+     */
+    protected $templateBase = 'Toolkit/Members/Billing/';
+    /**
+     * The directory of the templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $templatesDir = 'templates';
+
+    /**
+     * The directory of the flexy-compiled templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $compiledDir = 'templates/compiled';
+
+    /**
+     * The name of the template used for the form
+     *
+     * @var string
+     * @access protected
+     */
+    protected $formTemplate;
+
+    /**
+     * The object to use inside the form
+     *
+     * This object which is to be populated by the $this object                
+     * is used inside the templates and allows access back into the
+     * calling class to call publicly available functions
+     *
+     * @var    string
+     * @access protected
+     */
+    protected $view;
+
+    /**
+     * Class constructor
+     *
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                              submitted by adding a special hidden field
+     * 
+     * @access public
+     */
+    public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        $this->registeredRules = array();
+
+        $options =& PEAR::getStaticProperty('HTML_Template_Flexy', 'options');
+        $options = array(
+            'templateDir'  => BASE . "{$this->templateBase}{$this->templatesDir}",
+            'compileDir'   => BASE . "{$this->templateBase}{$this->compiledDir}",
+            'forceCompile' => 1,
+            'debug'        => 0,
+            'locale'       => 'en',
+        );
+    }
+
+    /**
+     * Returns the BASE_URL
+     *
+     * This function is used inside the Flexy Templated forms
+     *
+     * @return string BASE_URL
+     * @access public
+     */
+    public function baseUrl()
+    {
+        return BASE_URL;
+    }
+
+    /**
+     * Set up the default values for the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureDefaults()
+    {
+        $d = array();
+
+        if (isset($_GET['id'])) {
+            $factory = new Toolkit_Members_Billing_Factory();
+            $dbObject = $factory->createDbObjectById(
+                $this->dbh,
+                $this->className,
+                $_GET['id']
+            );
+            if ($dbObject) {
+                $d = $dbObject->getPropertiesAsArray();
+            }
+        }
+
+        $this->setupDefaults($d);
+    }
+
+    /**
+     * Configures all form elements
+     *
+     * If you are subclassing this base class out, you will need to define
+     * all your forms elements in your new subclass.
+     *
+     * @return void
+     * @access protected
+     */
+    abstract protected function configureElements();
+
+    /**
+     * Defines all filters used on form elements when submitted
+     *
+     * Most times this function won't need to be overridden.
+     *
+     * @return void
+     * @access public
+     */
+    protected function configureFilters()
+    {
+        $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+
+        $this->setupFilters($filters);
+    }
+
+    /**
+     * Sets up the required / not-required rules for forms
+     *
+     * At the bare minimum, the required / not-required rules for form
+     * needs to be defined.  Since these rules are most easily defined
+     * while creating the element definitions themselves the base function
+     * is to call the setupRules function that will instantiate these
+     * rules in the quickform class.
+     *
+     * @return void
+     * @access public
+     */
+    protected function configureRules()
+    {
+        $this->setupRules();
+    }
+
+    /**
+     * if the id is set in _GET array
+     * 
+     * @return Boolean
+     */
+    public function isEdit()
+    {
+        return isset($_GET['id']);
+    }
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return array Return description (if any) ...
+     * @access protected
+     */
+    protected function processData($values)
+    {
+        foreach ($values as $k => $v) {
+            switch ($k) {
+            case 'uploaded_file_rmv' :
+                //    Don't remove this from the values array.
+                //    we will handle it later.
+                //    we need to have access to this value
+                //    in the insert/update functions.
+                break;
+
+            case 'MAX_FILE_SIZE' :
+                unset($values[$k]);
+                break;
+
+            default :
+                if (preg_match('/^.+_rmv$/', $k)) {
+                    unset($values[$k]);
+                }
+                break;
+            }
+        }
+        
+        if (isset($_GET['id'])) {
+            $values['id'] = $_GET['id'];
+        }
+        $factory = new Toolkit_Members_Billing_Factory();
+        $dbObject = $factory->createDBObjectByValues(
+            $this->className,
+            $values
+        );
+        $dbObject->save($this->dbh);
+        return true;
+    }
+
+    /**
+     * Add the form elements defined in your class to a QuickForm
+     *
+     * Handles adding singleton elements as well as grouped elements.
+     * If added elements fail to correctly add to the form, the script
+     * should die gracefully, telling the user there was a problem.
+     *
+     * @param array $elements form element definitions
+     *
+     * @throws HTML_QuickForm_Error error raised from QuickForm class.
+     * @return void
+     * @access protected
+     */
+    protected function setupElements($elements)
+    {
+        $this->formElements = $elements;
+        foreach ($elements as $e) {
+            if ($e['type'] != 'group') {
+                try {
+                    $source =& $this->addElement(
+                        $e['type'],
+                        $e['name'],
+                        $e['display'],
+                        $e['opts'],
+                        $e['att'],
+                        $e['val']
+                    );
+                } catch (HTML_QuickForm_Error $e) {
+                    Toolkit_Common::dieGracefully(null, $e);
+                }
+                if ($e['type'] == 'advmultiselect') {
+                    $source->setLabel($e['labels']);
+                }
+                if ($e['name'] == 'categories') {
+                    $res = $source->loadArray($this->categories);
+                    if (PEAR::isError($res)) {
+                        Toolkit_Common::dieGracefully(null, $res);
+                    }
+                }
+                if ($e['type'] == 'header') {
+                    $this->formHeaders[$e['display']] = $e;
+                }
+            } elseif (is_array($e['group'])) {
+                unset($field);
+                foreach ($e['group'] as $g) {
+                    $field[] =& HTML_QuickForm::createElement(
+                        $g['type'],
+                        $g['name'],
+                        $g['display'],
+                        $g['opts'],
+                        $g['att'],
+                        $g['val']
+                    );
+                }
+                $source =& $this->addGroup(
+                    $field,
+                    $e['name'],
+                    $e['label'],
+                    $e['seperator'],
+                    $e['appendName']
+                );
+            }
+        }
+    }
+
+    /**
+     * Sets up the rendering engine for the form
+     *
+     * @return void
+     * @access protected
+     */
+    protected function setupRenderers()
+    {
+        $renderer =& new HTML_QuickForm_Renderer_Object(true);
+
+        $this->accept($renderer);
+
+        $this->template =& new HTML_Template_Flexy($this->options);
+
+        //    Make the view a copy of the $this object
+        //    That way we have access to call functions in
+        //    this class from within the template.
+        $this->view = $this;
+        $this->view->form = $renderer->toObject();
+        $this->template->compile($this->formTemplate);
+    }
+
+    /**
+     * Renders the form for viewing
+     *
+     * This function validates the form if needed, and if it successfully
+     * validates attempts to insert or update the data record.
+     * If it is unsuccessful, it will return an error to the user
+     * informing them of what went wrong.
+     *
+     * @param string $listPage The page the header should redirect
+     *                           to on successful insert or update.
+     *
+     * @return string The compiled and filled form template.
+     * @access public
+     */
+    public function toHTML($listPage = 'index.php')
+    { 
+        if ($_POST['delete'] && is_numeric($_POST['id'])) {
+            $factory = new Toolkit_Members_Billing_Factory();
+            $dbObject = $factory->createDbObjectById(
+                $this->dbh,
+                $this->className,
+                $_POST['id']
+            );
+            $dbObject->delete($this->dbh);
+            header('Location: ' . $listPage);
+            exit;
+        }
+        
+        //    We need to validate (and freeze if needed)
+        //    before we render the form. That way the
+        //    template knows about any errors on the form.
+        $this->validated = $this->validate();
+        $this->setupRenderers();
+
+        if ($this->validated) {
+            $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+            if ($processed) {
+                header("Location: $listPage");
+            } else {
+                $errorMsg = "There was an unexpected error.
+                    Please try again later.";
+            }
+        }
+
+        return $errorMsg . $this->template->bufferedOutputObject($this->view);
+    }
+
+    /**
+     * Returns form message from validation attempts
+     *
+     * @return string validation message
+     * @access public
+     */
+    public function validated()
+    {
+        if ($this->validated) {
+            return $this->successMsg;
+        } elseif ($this->isSubmitted()) {
+            return $this->errorMsg;
+        }
+    }
+
+}
diff --git a/Toolkit/Members/Billing/Billing.php b/Toolkit/Members/Billing/Billing.php
new file mode 100644 (file)
index 0000000..87a1b6e
--- /dev/null
@@ -0,0 +1,473 @@
+<?php
+/**
+ * Billing.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_Billing
+ * 
+ * Member Billing Module Billing table class
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_Billing
+    extends Toolkit_Table
+{
+    /**
+     * Description of $tableName
+     * @var string 
+     * @access public
+     */
+    public $tableName = 'billing';
+   
+    /**
+     * Description of $id
+     * @var int 
+     * @access protected
+     */
+    protected $id;
+    
+    /**
+     * Description of $invoice_id
+     * @var int 
+     * @access protected
+     */
+    protected $invoice_id;
+    
+    /**
+     * Description of $transaction_time
+     * @var timestamp 
+     * @access protected
+     */    
+    protected $transaction_time;
+    
+    /**
+     * Description of $transaction_date
+     * @var date 
+     * @access protected
+     */    
+    protected $transaction_date;
+    
+    /**
+     * Description of $member_name
+     * @var string 
+     * @access protected
+     */    
+    protected $member_name;
+    
+    /**
+     * Description of $member_id
+     * @var int 
+     * @access protected
+     */    
+    protected $member_id;
+    
+    /**
+     * Description of $account_id
+     * @var int 
+     * @access protected
+     */    
+    protected $account_id;
+    
+    /**
+     * Description of $account_number
+     * @var string 
+     * @access protected
+     */    
+    protected $account_number;
+    
+    /**
+     * Description of $billing_type
+     * @var int 
+     * @access protected
+     */    
+    protected $billing_type;
+    
+    /**
+     * Description of $amount
+     * @var int 
+     * @access protected
+     */    
+    protected $amount;
+    
+    /**
+     * Description of $balance
+     * @var int 
+     * @access protected
+     */    
+    protected $balance;
+    
+    /**
+     * Description of $payment_method
+     * @var int 
+     * @access protected
+     */    
+    protected $payment_method;
+    
+    /**
+     * Description of $payment_data
+     * @var string 
+     * @access protected
+     */    
+    protected $payment_data;
+    
+    /**
+     * Description of $emailed
+     * @var boolean 
+     * @access protected
+     */    
+    protected $emailed;
+    
+    /**
+     * Description of $printed
+     * @var boolean 
+     * @access protected
+     */    
+    protected $printed;
+    
+    /**
+     * Description of $paid
+     * @var boolean 
+     * @access protected
+     */    
+    protected $paid;
+    
+    /**
+     * Description of $invoice
+     * @var string 
+     * @access protected
+     */    
+    protected $invoice;
+    
+    /**
+     * Description of $notes
+     * @var string 
+     * @access protected
+     */    
+    protected $notes;
+
+    /**
+     * return amount as float
+     *
+     * @return float
+     * @access public
+     */
+    public function getAmount()
+    {
+        return (float)$this->amount;
+    }
+
+    /**
+     * return balance as float
+     *
+     * @return float
+     * @access public
+     * 
+     */
+    public function getBalance()
+    {
+        return (float)$this->balance;
+    }
+    
+    /**
+     * Description of getInvoiceAsPdf
+     * 
+     * @param PDO $dbh Database handler
+     * 
+     * @return boolean|string
+     * @access public
+     */
+    public function getInvoiceAsPdf(PDO $dbh)
+    {
+        $memberId  = $this->getMember_id();
+        $invoiceId = $this->getInvoice_id();
+        $accountId = $this->getAccount_id();
+        // if there's an empty value in any of these return false
+        if (!$memberId || !$invoiceId || !$accountId) {
+            return false;
+        }
+        $pdf = new Toolkit_Members_Billing_InvoicePdf();
+        $pdfOut = $pdf->createPdfInvoice(
+            $dbh,
+            $memberId,
+            $invoiceId,
+            $accountId
+        );
+        return $pdfOut;
+    }
+
+    /**
+     * insert the object
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return Toolkit_Table
+     * @access public
+     */
+    public function insert(PDO $dbh)
+    {
+
+        try {
+            $values = get_object_vars($this);
+            unset($values['id'], $values['tableName']);
+            if ($values['invoice_id'] == null) {
+                unset($values['invoice_id']);
+            }
+            $sql = Toolkit_Common::createSQLInsert(
+                $this->tableName,
+                array_keys($values)
+            );
+            $sql .= ' RETURNING id, invoice_id';
+            $stmt = Toolkit_Common::prepareQuery(
+                $dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+            $stmt->execute();
+            $res = $stmt->fetch(PDO::FETCH_ASSOC);
+            $this->setId($res['id']);
+            $this->setInvoiceId($res['invoice_id']);
+            return $this;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    
+    /**
+     * Check to see if given an id that it is numeric
+     *
+     * @param Mixed $id account_id field
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function setAccountId($id)
+    {
+        if (isset($id) && !is_numeric($id)) {
+            throw new InvalidArgumentException('If account_id is given must be numeric');
+        }
+        $this->account_id = $id;
+        return $this;
+    }
+
+    /**
+     * Checking that the amount is a valid numeric value
+     *
+     * @param mixed $amount billing amount
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function setAmount($amount)
+    {
+        if (isset($amount) && !is_numeric($amount)) {
+            throw new InvalidArgumentException('If amount is given must be numeric');
+        }
+        $this->amount
+            = ($amount)
+            ? (float)$amount
+            : (float)'0.00';
+        return $this;
+    }
+
+    /**
+     * Checking that the amount is a valid numeric value
+     *
+     * @param mixed $balance balance
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function setBalance($balance)
+    {
+        if (isset($balance) && !is_numeric($balance)) {
+            throw new InvalidArgumentException(
+                'If balance is given must be numeric'
+            );
+        }
+        $this->balance
+            = ($balance)
+            ? (float)$balance
+            : (float)'0.00';
+        return $this;
+    }
+
+    /**
+     * Checking that billing type is between 1 and 5
+     *
+     * @param Mixed $billing_type integer of billing type
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function setBillingType($billing_type)
+    {
+        if (!isset($billing_type)) {
+            throw new InvalidArgumentException('Billing Type must not be null');
+        }
+        if (!in_array($billing_type, array(1,2,3,4,5))) {
+            throw new InvalidArgumentException(
+                'Billing Type must be a numeric value between 1 and 5'
+            );
+        }
+        $this->billing_type = $billing_type;
+        return $this;
+    }
+
+    /**
+     * Make sure this is a boolean value
+     *
+     * @param Mixed $emailed Emailed to the member
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     */
+    public function setEmailed($emailed)
+    {
+        $this->emailed = ($emailed);
+        return $this;
+    }
+    
+    /**
+     * Check to see if given an id that it is numeric
+     *
+     * @param Mixed $id invoice_id field
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function setInvoiceId($id)
+    {
+        if (isset($id) && !is_numeric($id)) {
+            throw new InvalidArgumentException('If invoice_id is given must be numeric');
+        }
+        $this->invoice_id = $id;
+        return $this;
+    }
+
+    /**
+     * Make sure this is a boolean value
+     *
+     * @param Mixed $paid Paid
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     */
+    public function setPaid($paid)
+    {
+        $this->paid = ($paid);
+        return $this;
+    }
+
+    /**
+     * Check that payment method is between 1 and 4
+     *
+     * @param Mixed $payment_method Payment method
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function setPaymentMethod($payment_method)
+    {
+        if (!isset($payment_method)) {
+            $this->payment_method = null;
+            return $this;
+        }
+        if (!in_array($payment_method, array(1,2,3,4))) {
+            throw new InvalidArgumentException(
+                'Payment Method must be a numeric value between 1 and 4'
+            );
+        }
+        $this->payment_method = $payment_method;
+        return $this;
+    }
+
+    /**
+     * Check to see if given an id that it is numeric
+     *
+     * @param Mixed $id member_id field
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function setMemberId($id)
+    {
+        if (isset($id) && !is_numeric($id)) {
+            throw new InvalidArgumentException('If member_id is given must be numeric');
+        }
+        $this->member_id = $id;
+        return $this;
+    }
+
+    /**
+     * force the value to be boolean
+     *
+     * @param mixed $printed Printed for member
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     */
+    public function setPrinted($printed)
+    {
+        $this->printed = ($printed);
+        return $this;
+    }
+
+    /**
+     * update the object
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return Toolkit_Table
+     * @access public
+     */
+    public function update(PDO $dbh)
+    {
+        try {
+            $values = get_object_vars($this);
+            $values['amount']
+                = ($values['amount'])
+                ? (float)$values['amount']
+                : (float)0.00;
+            if ($values['invoice_id'] == null) {
+                unset($values['invoice_id']);
+            }
+            unset($values['tableName']);
+            $sql = Toolkit_Common::createSQLUpdate(
+                $this->tableName,
+                array_keys($values),
+                array('id = :id')
+            );
+            $stmt = Toolkit_Common::processQuery(
+                $dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+            return $this;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
+
diff --git a/Toolkit/Members/Billing/Database/application.sql b/Toolkit/Members/Billing/Database/application.sql
new file mode 100644 (file)
index 0000000..aa14248
--- /dev/null
@@ -0,0 +1,8 @@
+--
+-- setup the members billing tables
+--
+
+\i ./tables/member.sql
+\i ./tables/billing.sql
+\i ./tables/payment_types.sql
+\i ./tables/member_account.sql
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/Database/tables/billing.sql b/Toolkit/Members/Billing/Database/tables/billing.sql
new file mode 100644 (file)
index 0000000..ba429d8
--- /dev/null
@@ -0,0 +1,27 @@
+CREATE SEQUENCE members.billing_inv_id_seq START WITH 1;
+
+CREATE TABLE members.billing (
+    id SERIAL UNIQUE,
+    invoice_id INTEGER DEFAULT nextval('members.billing_inv_id_seq'),
+    transaction_time TIMESTAMP(0) WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    transaction_date DATE DEFAULT CURRENT_DATE,
+    member_name TEXT,
+    member_id INTEGER,
+    account_id INTEGER,
+    account_number TEXT NOT NULL,
+    billing_type INTEGER NOT NULL,
+    amount numeric(11,2) NOT NULL,
+    balance numeric(11,2) NOT NULL,
+    payment_method INTEGER,
+    payment_data TEXT,
+    emailed BOOLEAN,
+    printed BOOLEAN,
+    paid BOOLEAN,
+    invoice TEXT,
+    notes TEXT,
+    PRIMARY KEY (id)
+);
+
+GRANT ALL ON members.billing TO nobody;
+GRANT ALL ON members.billing_id_seq TO nobody;
+GRANT ALL ON members.billing_inv_id_seq TO nobody;
diff --git a/Toolkit/Members/Billing/Database/tables/member.sql b/Toolkit/Members/Billing/Database/tables/member.sql
new file mode 100644 (file)
index 0000000..1d79171
--- /dev/null
@@ -0,0 +1,4 @@
+ALTER TABLE members.member ADD account_number TEXT;
+CREATE UNIQUE INDEX member_account_number_indx ON members.member(account_number);
+ALTER TABLE members.member ADD billing_contact TEXT;
+UPDATE members.member SET billing_contact = primary_contact_fname||' '||primary_contact_lname;
diff --git a/Toolkit/Members/Billing/Database/tables/member_account.sql b/Toolkit/Members/Billing/Database/tables/member_account.sql
new file mode 100644 (file)
index 0000000..7500df0
--- /dev/null
@@ -0,0 +1,18 @@
+DROP table members.member_account;
+
+CREATE TABLE members.member_account (
+ id SERIAL,
+ member_id INTEGER NOT NULL
+    REFERENCES members.member (member_id)
+    ON DELETE CASCADE,
+ payment_type INTEGER NOT NULL
+    REFERENCES members.payment_types (id)
+    ON DELETE CASCADE,
+ email_invoice BOOLEAN NOT NULL DEFAULT false,
+ usmail_invoice BOOLEAN NOT NULL DEFAULT false,
+ fax_invoice BOOLEAN NOT NULL DEFAULT false,
+ PRIMARY KEY (id)
+);
+
+GRANT ALL ON members.member_account TO nobody;
+GRANT ALL ON members.member_account_id_seq TO nobody;
diff --git a/Toolkit/Members/Billing/Database/tables/payment_types.sql b/Toolkit/Members/Billing/Database/tables/payment_types.sql
new file mode 100644 (file)
index 0000000..0d9157b
--- /dev/null
@@ -0,0 +1,13 @@
+CREATE TABLE members.payment_types (
+    id SERIAL UNIQUE,
+    name TEXT NOT NULL,
+    qcode INT,
+    category TEXT NOT NULL,
+    amount numeric(8,2) NOT NULL,
+    notes TEXT,
+    dynamic_amount BOOLEAN DEFAULT FALSE,
+    PRIMARY KEY (id)
+);
+
+GRANT ALL ON members.payment_types TO nobody;
+GRANT ALL ON members.payment_types_id_seq TO nobody;
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/EditBillingForm.php b/Toolkit/Members/Billing/EditBillingForm.php
new file mode 100644 (file)
index 0000000..41d809e
--- /dev/null
@@ -0,0 +1,319 @@
+<?php
+/**
+ * EditBillingForm.php
+ * 
+ * PHP version 5
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form for billing edit
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Billing_EditBillingForm
+    extends Toolkit_Members_Billing_Auxiliary
+{
+    /**
+     * class used for the database object
+     *
+     * @var    string
+     * @access public
+     */
+    public $className = 'Toolkit_Members_Billing_Billing';
+
+    /**
+     * template for edit form
+     *
+     * @var    string   
+     * @access protected
+     */
+    protected $formTemplate = 'editBilling.html';
+
+    /**
+     * Class constructor
+     *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                              submitted by adding a special hidden field
+     * 
+     * @access public
+     */
+    public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+    }
+    /**
+     * Set up the default values for the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureDefaults()
+    {
+        $d = array();
+        if (isset($_GET['invoice_id'])) {
+            $factory = new Toolkit_Members_Billing_Factory();
+            $dbObject = $factory->createDbObjectById(
+                $this->dbh,
+                $this->className,
+                $_GET['invoice_id']
+            );
+            if ($dbObject) {
+                $d = $dbObject->getPropertiesAsArray();
+            }
+            $d['id'] = $_REQUEST['id'];
+            $d['currentAmount'] = $dbObject->getAmount();
+        }
+
+        $this->setupDefaults($d);
+    }
+    /**
+     * Form element definitions
+     * 
+     * @return void     
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e = array();
+        //    All Grouped Elements are created here.
+
+        //    All Elements are created here.
+        //    This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'PaymentTypeInfoHdr',
+            'display' => 'Billing Invoice'
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'member_name',
+            'display' => 'Member Name'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'id'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'currentAmount'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'invoice_id'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'amount',
+            'display' => 'Amount'
+        );
+
+
+        $this->setupElements($e);
+    }
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    /**
+     * Form rule definitions
+     * 
+     * @return void     
+     * @access public
+     */
+    public function configureRules()
+    {
+        $r = array();
+
+        $r[] = array(
+            'element'    => 'amount',
+            'message'    => 'ERROR: Invalid amount!',
+            'type'       => 'numeric',
+            'format'     => null,
+            'validation' => $this->validationType,
+            'reset'      => true,
+            'force'      => false
+        );
+        
+        $this->setupRules($r);
+    }
+    
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return array Return description (if any) ...
+     * @access protected
+     */
+    protected function processData($values)
+    {
+        foreach ($values as $k => $v) {
+            switch ($k) {
+            case 'uploaded_file_rmv' :
+                //    Don't remove this from the values array.
+                //    we will handle it later.
+                //    we need to have access to this value
+                //    in the insert/update functions.
+                break;
+
+            case 'MAX_FILE_SIZE' :
+                unset($values[$k]);
+                break;
+
+            default :
+                if (preg_match('/^.+_rmv$/', $k)) {
+                    unset($values[$k]);
+                }
+                break;
+            }
+        }
+        // calculate the difference of the old amount and new one
+        // this will be used for reseting all the amount and balances for 
+        // the billing records for the invoic_id
+        $diffAmount = (float)$values['currentAmount'] - (float)$values['amount'];
+        try {
+            $sql = "
+              SELECT id
+                FROM billing
+               WHERE invoice_id = :invoice_id
+                 AND billing_type IN (1,2,3)
+            ORDER BY transaction_time";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':invoice_id',
+                $values['invoice_id'],
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $this->resetBillingAmounts($row['id'], $diffAmount);
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        
+        return true;
+    }
+    
+    /**
+     * If the function is called with an Amount then it is the first
+     * all others should have just a diff
+     *
+     * @param int $billingId  Id of the billing record
+     * @param int $diffAmount Difference in new amount   
+     * 
+     * @return void 
+     */
+    public function resetBillingAmounts($billingId, $diffAmount)
+    {
+        $factory = new Toolkit_Members_Billing_Factory();
+        $billing = $factory->createDBObjectById(
+            $this->dbh,
+            $this->className,
+            $billingId
+        );
+        $currentAmount  = $billing->getAmount();
+        $currentBalance = $billing->getBalance();
+        if ($billing->getBilling_type() == 1) {
+            $newAmount  = (float)$currentAmount - $diffAmount;
+            $billing->setAmount($newAmount);
+        }
+        
+        $newBalance = (float)$currentBalance - $diffAmount;
+        $billing->setBalance($newBalance);
+        if ($newBalance == (float)'0.00') {
+            $billing->setPaid(true);
+        } else {
+            $billing->setPaid(false);
+        }
+        $billing->save($this->dbh);
+        // need to get original invoice
+        $statement = new Toolkit_Members_Billing_Statement();
+        $originalInvoice = $statement->getOriginalInvoice(
+            $this->dbh,
+            $billing->getMember_id(),
+            $billing->getInvoice_id()
+        );
+        if ($originalInvoice) {
+            if ($originalInvoice->getId() != $billing->getId()) {
+                $invoiceId = $originalInvoice->getInvoice_id();
+                if ($newBalance == (float)'0.00') {
+                    $originalInvoice
+                        ->setPaid(true)
+                        ->save($this->dbh);
+                }
+            }
+        }        
+        $billing->save($this->dbh);
+    }
+
+    /**
+     * Renders the form for viewing
+     *
+     * This function validates the form if needed, and if it successfully
+     * validates attempts to insert or update the data record.
+     * If it is unsuccessful, it will return an error to the user
+     * informing them of what went wrong.
+     *
+     * @return string The compiled and filled form template.
+     * @access public
+     */
+    public function toHtml()
+    {
+        $listPage = BASE_URL . 'admin/members.php?rt=Members&ac=editMember&tab=invoices&id='
+            . $_REQUEST['id'];
+        return parent::toHtml($listPage);
+    }
+}
diff --git a/Toolkit/Members/Billing/EditMemberAccount.php b/Toolkit/Members/Billing/EditMemberAccount.php
new file mode 100644 (file)
index 0000000..06e2f9e
--- /dev/null
@@ -0,0 +1,831 @@
+<?php
+
+/**
+ * EditMemberAccount.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberAccount.php,v 1.1 2011/03/25 20:18:28 matrix Exp $
+ * @link     http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handle associating contacts along with member records
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the billing. Form is not rendered until the user is added into
+ * the Database.
+ *
+ * @category  Toolkit
+ * @package   Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2008 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_Members
+ */
+class Toolkit_Members_Billing_EditMemberAccount
+    extends Toolkit_Members_EditMemberInfo
+    implements Toolkit_Form
+{
+    
+    /**
+     * The table name in the database used to store the data of the files
+     *
+     * @var string
+     * @access public
+     */
+    public $tableName = 'member';
+
+    /**
+     * The template used to render the form
+     *
+     * @var string
+     * @access protected
+     */
+    protected $formTemplate = 'editBilling.tpl';
+
+    /**
+     * Message to return if the form successfully submits
+     *
+     * @var string
+     * @access protected
+     */
+    protected $successMsg = '
+        <div id="form-success-top">
+            You successfully updated your Billing Info.
+        </div>';
+
+    /**
+     * Description for $memberStatements
+     * 
+     * @var string
+     * @access public
+     */
+    public $memberStatements = '';
+    /**
+     * Primary account id
+     *
+     * @var integer
+     * @access protected
+     */
+    protected $primaryAccountId = null;
+    /**
+     * secondary account number
+     *
+     * @var integer
+     * @access protected
+     */
+    protected $secondaryAccountId = null;
+
+    /**
+     * Class constructor
+     *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                              submitted by adding a special hidden field
+     *                            
+     * @access public
+     * @see    Toolkit_Members_EditMemberInfo
+     */
+    public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        // Member config
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/config.ini',
+            'IniFile'
+        );
+        $this->config = $root;
+        // Billing config
+        $config2 = new Config();
+        $root2 = $config2->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $this->config2 = $root2;
+    }
+
+    /**
+     * Validate date input
+     * 
+     * allows for empty dates to be valid
+     *
+     * @param array $date date group from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+    public function checkDate($date)
+    {
+        return strtotime($date);
+    }
+
+    /**
+     * Makes sure there are no duplicate account numbers already in the table
+     * 
+     * @param string $data Data
+     * 
+     * @return boolean|mixed
+     * @access public
+     */
+    public function checkAccountNumber($data)
+       {
+               try {
+                       //      If we're editing a member, they
+                       //      can save that account_number as its
+                       //      own. so don't include that 
+                       //      member in the check.
+                       if (is_numeric($_GET['id'])) {
+                               $and = "AND member_id != :id";
+                       }
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM member
+                                WHERE account_number = :account_number
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':account_number', $data, PDO::PARAM_STR);
+                       if (is_numeric($_GET['id'])) {
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $valid);
+                       $stmt->fetch();
+
+                       return !(bool) $valid;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+    
+    /**
+     * Description of hasInfo
+     * 
+     * @return boolean
+     * @access public
+     */
+    public function hasInfo()
+    {
+        return (bool)$this->primaryAccountId;
+    }
+    
+    /**
+     * Sets the defaults for elements in the form.
+     *
+     * @return void
+     * @access public
+     */
+    public function configureDefaults()
+    {
+        $d = array();
+        $memberData = $this->getMemberData($_GET['id']);
+        $d['account_number']  = $memberData['account_number'];
+        $d['billing_contact'] = $memberData['billing_contact'];
+        if ($this->primaryAccountId) {
+            $account1 = Toolkit_Members_Billing_Factory::createDbObjectById(
+                $this->dbh,
+                'Toolkit_Members_Billing_MemberAccount',
+                $this->primaryAccountId
+            );
+            
+            $d['account1_id']     = $account1->getId();
+            $d['payment_type1']   = $account1->getPayment_type();
+            $email_invoice
+                = ($account1->getEmail_invoice())
+                ? 'email_invoice'
+                : null;
+            $usmail_invoice
+                = ($account1->getUsmail_invoice())
+                ? 'usmail_invoice'
+                : null;
+            $fax_invoice
+                = ($account1->getFax_invoice())
+                ? 'fax_invoice'
+                : null;
+            $d['invoice_method1'] = array(
+                'email_invoice'  => $email_invoice,
+                'usmail_invoice' => $usmail_invoice,
+                'fax_invoice'    => $fax_invoice
+            );
+        }
+
+        if ($this->secondaryAccountId) {
+            $account2 = Toolkit_Members_Billing_Factory::createDbObjectById(
+                $this->dbh,
+                'Toolkit_Members_Billing_MemberAccount',
+                $this->secondaryAccountId
+            );
+            $d['account2_id']     = $account2->getId();
+            $d['payment_type2']   = $account2->getPayment_type();
+            $email_invoice
+                = ($account2->getEmail_invoice())
+                ? 'email_invoice'
+                : null;
+            $usmail_invoice
+                = ($account2->getUsmail_invoice())
+                ? 'usmail_invoice'
+                : null;
+            $fax_invoice
+                = ($account2->getFax_invoice())
+                ? 'fax_invoice'
+                : null;
+            $d['invoice_method2'] = array(
+                'email_invoice'  => $email_invoice,
+                'usmail_invoice' => $usmail_invoice,
+                'fax_invoice'    => $fax_invoice
+            );
+        }
+        $d['member_id'] = $_GET['id'];
+        $this->setupDefaults($d);
+    }
+
+    /**
+     * Setup the elements to use on the form.
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e          = array();
+        //    All Grouped Elements are created here.
+        $paymentTypes   = $this->getPaymentTypes();
+
+        //    All Elements are created here.
+        //    This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'infoHdr',
+            'display' => 'Account Information'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'member_id'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'account1_id'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'account_number',
+            'display' => 'Account Number',
+            'opts'    => array('class' => 'text')
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'billing_contact',
+            'display' => 'Billing Contact',
+            'opts'    => array('class' => 'text')
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'infoHdr',
+            'display' => 'Primary Billing information'
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => true,
+            'name'    => 'payment_type1',
+            'display' => 'Payment Type',
+            'opts'    => array('' => '') + $paymentTypes
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => true,
+            'name'    => 'invoice_method1',
+            'display' => 'Invoice Delivery Methods',
+            'opts'    => array(
+                'email_invoice'  => 'By Email',
+                'usmail_invoice' => 'By US Mail',
+                'fax_invoice'    => 'By Fax'
+            ),
+            'att'     => array('multiple' => 'multiple')
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'infoHdr',
+            'display' => 'Secondary Billing information'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'account2_id'
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'payment_type2',
+            'display' => 'Payment Type',
+            'opts'    => array('' => '') + $paymentTypes
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'invoice_method2',
+            'display' => 'Invoice Delivery Methods',
+            'opts'    => array(
+                'email_invoice'  => 'By Email',
+                'usmail_invoice' => 'By US Mail',
+                'fax_invoice'    => 'By Fax'
+            ),
+            'att'     => array('multiple' => 'multiple')
+        );
+    
+        $this->setupElements($e);
+    }
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    /**
+     * Sets up all the rules to be used when the form is validated.
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules()
+    {
+        //  form rules
+        $r = array();
+        $this->registeredRules = array();
+        $r[] = array(
+            'element' => 'amount',
+            'message' => 'ERROR: Must be a number!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element'    => 'transaction_date',
+            'message'    => 'ERROR: Invalid date!',
+            'type'       => 'callback',
+            'format'     => array(&$this, 'checkDate'),
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $r[] = array(
+            'element'    => 'account_number',
+            'message'    => 'ERROR: Sorry, but this Account Number has already been used for a different Member!',
+            'type'       => 'callback',
+            'format'     => array(&$this, 'checkAccountNumber'),
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $this->setupRules($r);
+    }
+
+    /**
+     * Get the billing types from the config object
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getBillingTypes()
+    {
+        return $this->config2
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'billingType')
+            ->getContent();
+    }
+
+    /**
+     * Description of setJscalScripts
+     * 
+     * @return void
+     * @access public 
+     */
+    public function setJscalScripts()
+    {
+        $this->jsCalScripts = '
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/utils.js"></script>
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/calendar.js"></script>
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/calendar-en.js"></script>
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/calendar-setup.js"></script>
+';
+    }
+
+    /**
+     * Description of setPrimaryAccountId()
+     * 
+     * @param int $id Primary account ID
+     * 
+     * @return void
+     * @access public
+     * @throws InvalidArgumentException 
+     */
+    public function setPrimaryAccountId($id)
+    {
+        if (!is_numeric($id)) {
+            throw new InvalidArgumentException('Id must be an integer');
+        }
+        $this->primaryAccountId = $id;
+    }
+    
+    /**
+     * Description of setSecondaryAccountId()
+     * 
+     * @param int $id Secondary Account ID
+     * 
+     * @return void
+     * @access public
+     */
+    public function setSecondaryAccountId($id)
+    {
+        if (!is_numeric($id)) {
+            $this->secondaryAccountId = null;
+        }
+        $this->secondaryAccountId = $id;
+    }
+    // {{{ toHTML()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+        * @return      string  The rendered form
+        * @access      public
+        */
+       public function toHTML()
+       {
+        if ($_REQUEST['delete']) {
+            $this->deleteBillingInfo();
+            exit;
+        }
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+               if ($this->validated) {
+                       $processed = $this->process(array(&$this, 'processData'), $this->mergeFiles);
+               }
+
+               //      ProcessData handles settingup the lat/lon coordinates if they were not entered
+               //      into the form.  these values ar calculated and then inserted into the forms
+               //      element values.  So we need to process the data first and then render the form.
+               $this->setupRenderers();
+
+               return $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+    /**
+     * Delete the member accounts the member account_number and any billing data 
+     * related to the member
+     * 
+     * @return void
+     * @access protected
+     */
+    protected function deleteBillingInfo()
+    {
+        try {
+            // delete the member_accounts
+            $sql = "
+            DELETE FROM member_account
+             WHERE member_id = :member_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $_GET['id'],
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            
+            // empty the account_number in member record
+            $sql = "
+            UPDATE member
+               SET account_number = null
+             WHERE member_id = :member_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $_GET['id'],
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            
+            // delete any billing data for this member
+            $sql = "
+            DELETE FROM billing
+             WHERE member_id = :member_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $_GET['id'],
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        // return page to jump to
+        $listPage = BASE_URL .
+            "admin/members.php?cat=2&subCat=2&tab=7&id={$_GET['id']}&formSubmitGood=1";
+        header('Location: '.$listPage);
+    }
+    /**
+     * From the member_id get the member name
+     *
+     * @param integer $id Member_id field
+     *
+     * @return string
+     * @access protected
+     */
+    protected function getMemberData($id)
+    {
+        try {
+            $sql = "
+            SELECT *
+              FROM member
+             WHERE member_id = :member_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * grab from the config object the payment methods
+     * take out for this client the credit card one they only do cash or check
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentMethods()
+    {
+        $types = $this->config2
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'paymentMethod')
+            ->getContent();
+        unset($types[2]);
+        return $types;
+    }
+
+    /**
+     * Get a prorated price for this memebr based on the date field from
+     * the form (billing) submit
+     *
+     * @param array $values Form values
+     *
+     * @return float
+     * @access protected
+     * @throws Exception
+     */
+    protected function getProRatedPrice($values)
+    {
+        $invoice         = new Toolkit_Members_Billing_Invoices();
+        $nextInvoiceDate = $invoice->getNextInvoiceDate();
+        $invDate = new Date(
+            date('c', $nextInvoiceDate)
+        );
+        $paymentType = Toolkit_Members_Billing_Factory::createDbObjectById(
+            $this->dbh,
+            'Toolkit_Members_Billing_PaymentTypes',
+            $values['payment_type']
+        );
+        if (!($paymentType instanceof Toolkit_Members_Billing_PaymentTypes)) {
+            throw new Exception(
+                'Payment Type is not an instance of
+                Toolkit_Members_Billing_PaymentTypes'
+            );
+        }
+        $transactionDate = new Date(
+            date('c', strtotime($values['transaction_date']))
+        );
+        $cDate = Date::compare($invDate, $transactionDate);
+        if ($cDate == 0) {
+            return (float)$paymentType->getAmount();
+        } else if ($cDate == -1) {
+            // pro-rated for next year
+            // increase the invoice date by one year
+            $timestamp = $invDate->getTime();
+            $nextYear  = strtotime('+ 1 year', $timestamp);
+            if ($nextYear) {
+                $invDate = new Date($nextYear);
+            }
+        }
+        $span = new Date_Span();
+        $span->setFromDateDiff($transactionDate, $invDate);
+        $days = round($span->toDays());  
+        $dailyPrice = (float)($paymentType->getAmount() / 365);
+        return (float)round(($days * $dailyPrice), 2);
+    }
+
+    /**
+     * build the $this->memberStatements string with the rows of billing table
+     * records and a line with balance due at end
+     *
+     * @return void
+     * @access protected
+     */
+    protected function getStatements()
+    {
+        $statement = new Toolkit_Members_Billing_Statement();
+        $this->memberStatements = $statement->createMemberStatements(
+            $this->dbh,
+            $_REQUEST['id']
+        );
+    }
+
+    /**
+     * Get all payment types for a select list
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentTypes()
+    {
+        $paymentTypes = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM payment_types
+            ORDER BY name";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $paymentTypes[$row['id']] = $row['name'] . ' ($'.$row['amount'].')';
+            }
+            return $paymentTypes;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param unknown $sec Parameter description (if any) ...
+     *
+     * @return unknown Return description (if any) ...
+     * @access public 
+     */
+    public function isForm($sec)
+    {
+        return !$sec;
+    }
+
+    /**
+     * Short description for processData()
+     * 
+     * Long description (if any) ...
+     * 
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return boolean     
+     * @access protected
+     */
+    public function processData($values)
+    {
+        if (   $values['account_number'] && $values['member_id']) {
+            $sql = "
+            UPDATE member
+               SET account_number = :account_number,
+                   billing_contact = :billing_contact
+             WHERE member_id = :member_id"; 
+            try {
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(
+                    ':account_number',
+                    $values['account_number'],
+                    PDO::PARAM_INT
+                );
+                $stmt->bindParam(
+                    ':billing_contact',
+                    $values['billing_contact'],
+                    PDO::PARAM_INT
+                );
+                $stmt->bindParam(
+                    ':member_id',
+                    $values['member_id'],
+                    PDO::PARAM_INT
+                );
+                $stmt->execute();
+            } catch(PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+        }
+        if (is_numeric($values['account1_id'])) {
+            $account = Toolkit_Members_Billing_Factory::createDbObjectById(
+                $this->dbh,
+                'Toolkit_Members_Billing_MemberAccount',
+                $values['account1_id']
+            );
+            $account->setPayment_type($values['payment_type1'])
+                ->setEmailInvoice(in_array('email_invoice', $values['invoice_method1']))
+                ->setUsmailInvoice(in_array('usmail_invoice', $values['invoice_method1']))
+                ->setFaxInvoice(in_array('fax_invoice', $values['invoice_method1']))
+                ->save($this->dbh);
+        } else {
+            $account1Values = array(
+                'member_id' => $values['member_id'],
+                'payment_type' => $values['payment_type1'],
+                'email_invoice' => in_array('email_invoice', $values['invoice_method1']),
+                'usmail_invoice' => in_array('usmail_invoice', $values['invoice_method1']),
+                'fax_invoice' => in_array('fax_invoice', $values['invoice_method1'])
+            );
+            $account = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_MemberAccount',
+                $account1Values
+            )->save($this->dbh);
+        }
+        if (is_numeric($values['account2_id'])) {
+            $account2 = Toolkit_Members_Billing_Factory::createDbObjectById(
+                $this->dbh,
+                'Toolkit_Members_Billing_MemberAccount',
+                $values['account2_id']
+            );
+            if (   $values['payment_type2']
+                && !empty($values['invoice_method2'])
+            ) {
+                $account2->setPayment_type($values['payment_type2'])
+                ->setEmailInvoice(in_array('email_invoice', $values['invoice_method2']))
+                ->setUsmailInvoice(in_array('usmail_invoice', $values['invoice_method2']))
+                ->setFaxInvoice(in_array('fax_invoice', $values['invoice_method2']))
+                ->save($this->dbh);
+            } else {
+                // delete record if there's no data
+                $account2->delete($this->dbh);
+            }
+        } else {
+            if (   $values['payment_type2']
+                && !empty($values['invoice_method2'])
+            ) {
+                $account2Values = array(
+                    'member_id' => $values['member_id'],
+                    'payment_type' => $values['payment_type2'],
+                    'email_invoice' => in_array('email_invoice', $values['invoice_method2']),
+                    'usmail_invoice' => in_array('usmail_invoice', $values['invoice_method2']),
+                    'fax_invoice' => in_array('fax_invoice', $values['invoice_method2'])
+                );
+                $account2 = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                    'Toolkit_Members_Billing_MemberAccount',
+                    $account2Values
+                )->save($this->dbh);
+            }
+        }
+        // return page to jump to
+        $listPage = BASE_URL .
+            "admin/members.php?rt=Members&ac=editMember&tab=billingInfo&id={$_GET['id']}&formSubmitGood=1";
+        header('Location: '.$listPage);
+        return true;
+    }
+}
diff --git a/Toolkit/Members/Billing/EditMemberPayment.php b/Toolkit/Members/Billing/EditMemberPayment.php
new file mode 100644 (file)
index 0000000..31e7971
--- /dev/null
@@ -0,0 +1,918 @@
+<?php
+
+/**
+ * EditMemberBilling.php
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberPayment.php,v 1.2 2011/04/01 18:08:11 matrix Exp $
+ * @link     http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handle associating contacts along with member records
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the billing. Form is not rendered until the user is added into
+ * the Database.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2008 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_Members
+ */
+class Toolkit_Members_Billing_EditMemberPayment
+    extends Toolkit_Members_EditMemberInfo
+    implements Toolkit_Form
+{
+    
+    /**
+     * The table name in the database used to store the data of the files
+     *
+     * @var string
+     * @access public
+     */
+    public $tableName = 'member';
+
+    /**
+     * The template used to render the form
+     *
+     * @var string
+     * @access protected
+     */
+    protected $formTemplate = 'editBilling.tpl';
+
+    /**
+     * Message to return if the form successfully submits
+     *
+     * @var string
+     * @access protected
+     */
+    protected $successMsg = '
+        <div id="form-success-top">
+            You successfully updated your Billing Info.
+        </div>';
+
+    /**
+     * Description of $memberStatements
+     * 
+     * @var string
+     * @access public 
+     */
+    public $memberStatements = '';
+
+    /**
+     * Class constructor
+     *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                              submitted by adding a special hidden field
+     *                            
+     * @access public
+     * @see    Toolkit_Members_EditMemberInfo
+     */
+    public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        // Member config
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/config.ini',
+            'IniFile'
+        );
+        $this->config = $root;
+        // Billing config
+        $config2 = new Config();
+        $root2 = $config2->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $this->config2 = $root2;
+    }
+
+    /**
+     * Description of addAdjustment()
+     * 
+     * @param array $values Values array
+     * 
+     * @return void
+     * @access protected
+     */
+    protected function addAdjustment($values)
+    {
+        $statement = new Toolkit_Members_Billing_Statement();
+        $balanceDue = (float)$statement->getBalanceDue(
+            $this->dbh,
+            $_GET['id'],
+            $values['account_id']
+        );
+        $balance = (float)($balanceDue + (float)$values['amount']);
+        $paid
+            = ($balance == (float)'0.00')
+            ? true
+            : false;
+        // need to get the original invoice id
+        $originalInvoice = $statement->getOriginalInvoice(
+            $this->dbh,
+            $_GET['id'],
+            $values['account_id']
+        );
+        $invoiceId = $originalInvoice->getInvoice_id();
+        if ($values['amount']) {
+            $invoice = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_Billing',
+                array(
+                    'member_name'      => $values['member_name'],
+                    'invoice_id'       => $invoiceId,
+                    'member_id'        => $_GET['id'],
+                    'transaction_date' => date('m/d/Y'),
+                    'transaction_time' => date('m/d/Y H:i:s'),
+                    'account_number'   => $values['account_number'],
+                    'account_id'       => $values['account_id'],
+                    'billing_type'     => 3,
+                    'emailed'          => 0,
+                    'printed'          => 0,
+                    'amount'           => (float)$values['amount'],
+                    'balance'          => $balance,
+                    'paid'             => $paid,
+                    'payment_method'   => $values['payment_method'],
+                    'payment_data'     => $values['payment_data']
+                )
+            )->save($this->dbh);
+        }
+    }
+
+    /**
+     * Description of addComment()
+     * 
+     * @param array $values Values array
+     * 
+     * @return void
+     * @access protected
+     */
+    protected function addComment($values)
+    {
+        if ($values['notes']) {
+            $statement = new Toolkit_Members_Billing_Statement();
+            $balanceDue = (float)$statement->getBalanceDue(
+                $this->dbh,
+                $_GET['id'],
+                $values['account_id']
+            );
+            $invoice = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_Billing',
+                array(
+                    'member_name'      => $this->memberData[0]['member_name'],
+                    'invoice_id'       => 0,
+                    'member_id'        => $_GET['id'],
+                    'transaction_date' => date('m/d/Y'),
+                    'transaction_time' => date('m/d/Y H:i:s'),
+                    'account_id'       => $values['account_id'],
+                    'account_number'   => $this->memberData[0]['account_number'],
+                    'billing_type'     => 4,
+                    'emailed'          => 0,
+                    'printed'          => 0,
+                    'notes'            => $values['notes'],
+                    'amount'           => '0.00',
+                    'balance'          => (float)$balanceDue,
+                )
+            )->save($this->dbh);
+        }
+    }
+
+    /**
+     * Description of addInvoice()
+     * 
+     * @param array   $mData          Member Data
+     * @param date    $date           Invoice Date
+     * @param boolean $dynamic_amount The dynamic amount to use
+     * 
+     * @return void
+     * @access public
+     */
+    protected function addInvoice(
+        $mData,
+        $date,
+        $dynamic_amount
+    ) {
+        if ($date) {
+            $date = str_replace('-', '/', $date);
+            $date = str_replace('.', '/', $date);
+            $amount = $this->getProRatedPrice(
+                $mData,
+                $date,
+                $dynamic_amount
+            );
+            $transactionDate = date(
+                'm/d/Y',
+                strtotime($date)
+            );
+            $invoice = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_Billing',
+                array(
+                    'member_name'      => $mData['member_name'],
+                    'invoice_id'       => null,
+                    'member_id'        => $mData['member_id'],
+                    'transaction_date' => $transactionDate,
+                    'transaction_time' => date('m/d/Y H:i:s'),
+                    'account_id'       => $mData['account_id'],
+                    'account_number'   => $mData['account_number'],
+                    'billing_type'     => 1,
+                    'amount'           => (float)$amount,
+                    'emailed'          => 0,
+                    'printed'          => 0,
+                    'notes'            => '',
+                    'paid'             => false,
+                    'balance'          => (float)($balanceDue + (float)$amount)
+                )
+            );
+            $invoice->save($this->dbh);
+            
+            //$invoicesobj = new Toolkit_Members_Billing_Invoices();
+            //$pdf = new Toolkit_Members_Billing_InvoicePdf();
+            //$pdfInvoice = $pdf->createPdfInvoice(
+            //    $this->dbh,
+            //   $mData['member_id'],
+            //    $invoice->getInvoice_id(),
+            //    $mData['account_id']
+            //);
+            //
+            //$invoice->setInvoice(base64_encode($pdfInvoice));
+            //$invoice->save($this->dbh);
+        }
+    }
+
+    /**
+     * Description of addPayment()
+     * 
+     * @param array $values Values array
+     * 
+     * @return void
+     * @access protected
+     */
+    protected function addPayment($values)
+    {
+        $statement = new Toolkit_Members_Billing_Statement();
+        $balanceDue = (float)$statement->getBalanceDue(
+            $this->dbh,
+            $_GET['id'],
+            $values['account_id']
+        );
+        if ($values['amount']) {
+            $balanceDue = (float)($balanceDue - (float)$values['amount']);
+            $paid
+                = ($balanceDue == (float)'0.00')
+                ? true
+                : false;
+            // need to get the original invoice id
+            $originalInvoice = $statement->getOriginalInvoice(
+                $this->dbh,
+                $_GET['id'],
+                $values['account_id']
+            );
+            $invoiceId = $originalInvoice->getInvoice_id();
+            if ($paid) {
+                $originalInvoice
+                    ->setPaid(true)
+                    ->save($this->dbh);
+                
+            }
+            $invoice = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_Billing',
+                array(
+                    'member_name'      => $values['member_name'],
+                    'invoice_id'       => $invoiceId,
+                    'member_id'        => $_GET['id'],
+                    'transaction_date' => date('m/d/Y'),
+                    'transaction_time' => date('m/d/Y H:i:s'),
+                    'account_number'   => $values['account_number'],
+                    'account_id'       => $values['account_id'],
+                    'billing_type'     => 2,
+                    'emailed'          => 0,
+                    'printed'          => 0,
+                    'amount'           => (float)$values['amount'],
+                    'balance'          => $balanceDue,
+                    'paid'             => $paid,
+                    'payment_method'   => $values['payment_method'],
+                    'payment_data'     => $values['payment_data']
+                )
+            )->save($this->dbh);
+        }
+    }
+
+    /**
+     * Validate date input
+     * 
+     * allows for empty dates to be valid
+     *
+     * @param array $date date group from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+    public function checkDate($date)
+    {
+        return strtotime($date);
+    }
+    
+    /**
+     * Description of checkForReqAmount()
+     * 
+     * @param array $values Values array
+     * 
+     * @return boolean 
+     * @access public
+     */
+    public function checkForReqAmount($values)
+    {
+        $member_account_id = $values[0];
+        $dueAmount         = $values[1];
+        $memberAccount
+            = Toolkit_Members_Billing_Factory::createDbObjectById(
+                $this->dbh,
+                'Toolkit_Members_Billing_MemberAccount',
+                $member_account_id
+            );
+        $paymentType
+            = Toolkit_Members_Billing_Factory::createDbObjectById(
+                $this->dbh,
+                'Toolkit_Members_Billing_PaymentTypes',
+                $memberAccount->getPayment_type()
+            );
+        if (   $paymentType->getDynamic_amount() == true
+            && !is_numeric($dueAmount)
+        ) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Sets the defaults for elements in the form.
+     *
+     * @return void
+     * @access public
+     */
+    public function configureDefaults()
+    {
+        $d = array();
+        $this->setupDefaults($d);
+    }
+
+    /**
+     * Setup the elements to use on the form.
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements()
+    {
+        $paymentForm = array();
+        $invoiceForm = array();
+        // set element array
+        $e = array();
+        // set invoice object
+        $invoice    = new Toolkit_Members_Billing_Invoices();
+        $memberData = $this->getMemberData($_REQUEST['id']);
+        //    All Grouped Elements are created here.
+        $paymentMethods = $this->getPaymentMethods();
+        $paymentMethods['5'] = 'Adjustment';
+        if (!empty($memberData)) {
+            foreach ($memberData as $mData) {
+                $hasInvoice = $invoice->hasInvoice($this->dbh, $mData);
+                if ($hasInvoice) {
+                    $paymentForm[] = $mData;
+                } else {
+                    $invoiceForm[] = $mData;
+                }
+            }
+            
+            if (!empty($invoiceForm)) {
+                $this->setJscalScripts();
+                $invAccounts = array('' => '-- Select --');
+                foreach ($invoiceForm as $memberInv) {
+                    $memberAccount
+                        = Toolkit_Members_Billing_Factory::createDbObjectById(
+                            $this->dbh,
+                            'Toolkit_Members_Billing_MemberAccount',
+                            $memberInv['account_id']
+                        );
+                    $payment_type
+                        = Toolkit_Members_Billing_Factory::createDbObjectById(
+                            $this->dbh,
+                            'Toolkit_Members_Billing_PaymentTypes',
+                            $memberAccount->getPayment_type()
+                        );
+                    if (   $payment_type->getDynamic_amount() == false
+                        && (int)$payment_type->getAmount() > 0
+                    ) {
+                        $invAccounts[$memberAccount->getId()] = $payment_type->getName();
+                    } else if ($payment_type->getDynamic_amount() == true) {
+                        $invAccounts[$memberAccount->getId()] = $payment_type->getName();     
+                    }
+                    
+                }
+                if (count($invAccounts) > 1) {
+                    $e[] = array(
+                        'type'    => 'header',
+                        'req'     => false,
+                        'name'    => 'invoiceHdr',
+                        'display' => 'Create Invoice (Pro Rated to Invoice Date)'
+                    );
+                    $e[] = array(
+                        'type'    => 'select',
+                        'req'     => false,
+                        'name'    => 'inv_account_id',
+                        'display' => 'Payment Type',
+                        'opts'    => $invAccounts,
+                        'att'     => array('id' => 'inv_account_id')
+                    );
+                    $e[] = array(
+                        'type'    => 'text',
+                        'req'     => (($accountNumber == 1)?true:false),
+                        'name'    => 'transaction_date',
+                        'display' => 'Invoice Date',
+                        'opts'    => array(
+                            'size'=>'10',
+                            'id' => 'transDate')
+                    );
+                    $e[] = array(
+                    'type'    => 'text',
+                    'req'     => false,
+                    'name'    => 'dynamic_amount',
+                    'display' => 'Dynamic Amount Only',
+                    'opts'    => array('size' => 6)
+                    );
+                }
+            }
+            if (!empty($paymentForm)) {
+                $paymentAccounts = array();
+                foreach ($paymentForm as $memberInv) {
+                    $memberAccount
+                        = Toolkit_Members_Billing_Factory::createDbObjectById(
+                            $this->dbh,
+                            'Toolkit_Members_Billing_MemberAccount',
+                            $memberInv['account_id']
+                        );
+                    $payment_type
+                        = Toolkit_Members_Billing_Factory::createDbObjectById(
+                            $this->dbh,
+                            'Toolkit_Members_Billing_PaymentTypes',
+                            $memberAccount->getPayment_type()
+                        );
+                    $paymentAccounts[$memberAccount->getId()] = $payment_type->getName();
+                }
+                $e[] = array(
+                    'type'    => 'header',
+                    'req'     => false,
+                    'name'    => 'paymentHdr',
+                    'display' => 'Make A Payment'
+                );
+                $e[] = array(
+                    'type'    => 'select',
+                    'req'     => false,
+                    'name'    => 'account_id',
+                    'display' => 'Payment Type',
+                    'opts'    => $paymentAccounts
+                );
+                $e[] = array(
+                    'type'    => 'text',
+                    'req'     => false,
+                    'name'    => 'amount',
+                    'display' => 'Amount',
+                    'opts'    => array('size' => 6)
+                );
+                $e[] = array(
+                    'type'    => 'select',
+                    'req'     => false,
+                    'name'    => 'payment_method',
+                    'display' => 'Payment Method',
+                    'opts'    => $paymentMethods
+                );
+                $e[] = array(
+                    'type'    => 'text',
+                    'req'     => false,
+                    'name'    => 'payment_data',
+                    'display' => 'Payment Details',
+                    'opts'    => array('class' => 'text')
+                );
+
+                $e[] = array(
+                    'type'    => 'header',
+                    'req'     => false,
+                    'name'    => 'paymentHdr',
+                    'display' => 'Add Comment'
+                );
+                $e[] = array(
+                    'type'    => 'textarea',
+                    'req'     => false,
+                    'name'    => 'notes',
+                    'display' => 'Comment',
+                    'opts'    => array('class' => 'text')
+                );
+            }
+        }
+        //    All Elements are created here.
+        //    This includes group element definitions.
+        $this->setupElements($e);
+    }
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+        $this->getStatements();
+    }
+
+    /**
+     * Sets up all the rules to be used when the form is validated.
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules()
+    {
+        //  form rules
+        $r = array();
+        $this->registeredRules = array();
+        $r[] = array(
+            'element' => 'dynamic_amount',
+            'message' => 'ERROR: Must be a number!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'amount',
+            'message' => 'ERROR: Must be a number!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element'    => 'transaction_date',
+            'message'    => 'ERROR: Invalid date!',
+            'type'       => 'callback',
+            'format'     => array(&$this, 'checkDate'),
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $r[] = array(
+            'element'    => array('inv_account_id', 'dynamic_amount'),
+            'message'    => 'ERROR: Amount Required for This Payment Type',
+            'type'       => 'callback',
+            'format'     => array(&$this, 'checkForReqAmount'),
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $this->setupRules($r);
+    }
+
+    /**
+     * create a transaction type from billing form submittion
+     * can be either payment,invoice or comment
+     * each is handled seperately
+     *
+     * @param array $values Form values
+     *
+     * @return void
+     * @access protected
+     */
+    protected function createTransactionRecord($values)
+    {
+        //var_dump($values);
+        //exit;
+        $statement = new Toolkit_Members_Billing_Statement();
+        $balanceDue = (float)$statement->getBalanceDue(
+            $this->dbh,
+            $_GET['id']
+        );
+        
+        var_dump($values);
+        var_dump($balanceDue);
+        exit;
+        if ($values['account_number'] && $values['id']) {         
+            // comment
+            
+        }
+    }
+
+    /**
+     * Get the billing types from the config object
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getBillingTypes()
+    {
+        return $this->config2
+            ->getItem('section', 'billing')
+            ->getItem('directive', 'billingType')
+            ->getContent();
+    }
+
+    /**
+     * Descriptinon for setJscalScripts()
+     * 
+     * @return void
+     * @access public 
+     */
+    public function setJscalScripts()
+    {
+        $this->jsCalScripts = '
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/utils.js"></script>
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/calendar.js"></script>
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/calendar-en.js"></script>
+<script type="text/javascript" src="http://app.gaslightmedia.com/libjs/Jscal/calendar-setup.js"></script>
+';
+    }
+    
+    /**
+     * From the member_id get the member name
+     *
+     * @param integer $id Member_id field
+     *
+     * @return string
+     * @access protected
+     */
+    protected function getMemberData($id)
+    {
+        if (!$this->memberData) {
+            try {
+                $sql = "
+                SELECT m.member_id,m.member_name,m.account_number,
+                       ma.id as account_id,ma.payment_type
+                  FROM member m, member_account ma
+                 WHERE m.active = 't'
+                   AND m.member_id = ma.member_id
+                   AND m.member_id = :member_id";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(
+                    ':member_id',
+                    $id,
+                    PDO::PARAM_INT
+                );
+                $stmt->execute();
+                $memberData = $stmt->fetchAll(PDO::FETCH_ASSOC);
+            } catch(PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+            $this->memberData = $memberData;
+        }
+        return $this->memberData;
+    }
+
+    /**
+     * grab from the config object the payment methods
+     * take out for this client the credit card one they only do cash or check
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentMethods()
+    {
+        $types = $this->config2
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'paymentMethod')
+            ->getContent();
+        unset($types[2]);
+        return $types;
+    }
+
+    /**
+     * Get a prorated price for this memebr based on the date field from
+     * the form (billing) submit
+     * 
+     * @param array  $mData          Member Data
+     * @param string $date           The date for pro rating
+     * @param string $dynamic_amount The dynamic amount to use
+     * 
+     * @return float
+     */
+    protected function getProRatedPrice($mData, $date, $dynamic_amount)
+    {
+        $invoice         = new Toolkit_Members_Billing_Invoices();
+        $nextInvoiceDate = $invoice->getNextInvoiceDate();
+        $invDate = new Date(
+            date('c', $nextInvoiceDate)
+        );
+        $paymentType = Toolkit_Members_Billing_Factory::createDbObjectById(
+            $this->dbh,
+            'Toolkit_Members_Billing_PaymentTypes',
+            $mData['payment_type']
+        );
+        if (!($paymentType instanceof Toolkit_Members_Billing_PaymentTypes)) {
+            throw new Exception(
+                'Payment Type is not an instance of
+                Toolkit_Members_Billing_PaymentTypes'
+            );
+        }
+        if (   $paymentType->getDynamic_amount() == true
+            && is_numeric($dynamic_amount)
+        ) {
+            return (float)$dynamic_amount;
+        }
+        $transactionDate = new Date(
+            date('c', strtotime($date))
+        );
+        $cDate = Date::compare($invDate, $transactionDate);
+        if ($cDate == 0) {
+            return (float)$paymentType->getAmount();
+        } else if ($cDate == -1) {
+            // pro-rated for next year
+            // increase the invoice date by one year
+            $timestamp = $invDate->getTime();
+            $nextYear  = strtotime('+ 1 year', $timestamp);
+            if ($nextYear) {
+                $invDate = new Date($nextYear);
+            }
+        } else if ($cDate == 1) {
+            return $paymentType->getAmount();
+        }
+        $span = new Date_Span();
+        $span->setFromDateDiff($transactionDate, $invDate);
+        $days = round($span->toDays());  
+        $dailyPrice = (float)($paymentType->getAmount() / 365);
+        return (float)round(($days * $dailyPrice), 2);
+    }
+
+    /**
+     * build the $this->memberStatements string with the rows of billing table
+     * records and a line with balance due at end
+     *
+     * @return void
+     * @access protected
+     */
+    protected function getStatements()
+    {
+        if (!$_REQUEST['full']) {
+            $urlFormat
+                = "members.php?rt=Members&ac=editMember&id=%d&tab=invoices&full=1";
+            $url = sprintf(
+                $urlFormat,
+                $_REQUEST['id']
+            );
+            $format = '<a href="%s">Show Full Report</a>';
+                $this->memberStatements = sprintf(
+                    $format,
+                    $url
+                );
+        }
+        $statement = new Toolkit_Members_Billing_Statement();
+        $this->memberStatements .= $statement->createMemberStatements(
+            $this->dbh,
+            $_REQUEST['id']
+        );
+    }
+
+    /**
+     * Get all payment types for a select list
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentTypes()
+    {
+        $paymentTypes = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM payment_types
+            ORDER BY name";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $paymentTypes[$row['id']] = $row['name'] . ' ($'.$row['amount'].')';
+            }
+            return $paymentTypes;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param unknown $sec Parameter description (if any) ...
+     *
+     * @return unknown Return description (if any) ...
+     * @access public 
+     */
+    public function isForm($sec)
+    {
+        return !$sec;
+    }
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return boolean 
+     * @access public
+     */
+    public function processData($values)
+    {
+        // section for creating invoices for member accounts
+        if ($values['transaction_date'] && $values['inv_account_id']) {
+            // need to find which mData to send to function based
+            // on the account_id
+            $mData
+                = ($this->memberData[0]['account_id'] == (int)$values['inv_account_id'])
+                ? $this->memberData[0]
+                : $this->memberData[1];
+            $this->addInvoice(
+                $mData,
+                $values['transaction_date'],
+                $values['dynamic_amount']
+            );
+        }
+        // section for adding payment or adjustments
+        if (   $values['account_id']
+            && $values['amount']
+            && $values['payment_method']
+        ) {
+            if ($values['payment_method'] == 5) {
+                // add adjustment
+                $adjustment = array(
+                    'account_id'     => $values['account_id'],
+                    'member_name'    => $this->memberData[0]['member_name'],
+                    'account_number' => $this->memberData[0]['account_number'],
+                    'amount'         => $values['amount'],
+                    'payment_method' => null,
+                    'payment_data'   => $values['payment_data']
+                );
+                $this->addAdjustment($adjustment);
+            } else {
+                $payment = array(
+                    'account_id'     => $values['account_id'],
+                    'member_name'    => $this->memberData[0]['member_name'],
+                    'account_number' => $this->memberData[0]['account_number'],
+                    'amount'         => $values['amount'],
+                    'payment_method' => $values['payment_method'],
+                    'payment_data'   => $values['payment_data']
+                );
+                $this->addPayment($payment);
+            }
+        }
+        
+        // section for adding notes
+        if ($values['notes']) {
+            $comment = array(
+                'account_id' => $values['account_id'],
+                'notes'      => $values['notes']
+            );
+            $this->addComment($comment);
+        }
+
+        // return page to jump to
+        $listPage = BASE_URL .
+            "admin/members.php?rt=Members&ac=editMember&tab=invoices&id={$_GET['id']}&formSubmitGood=1";
+        header('Location: '.$listPage);
+        return true;
+    }
+}
diff --git a/Toolkit/Members/Billing/EditPaymentType.php b/Toolkit/Members/Billing/EditPaymentType.php
new file mode 100644 (file)
index 0000000..973f5ca
--- /dev/null
@@ -0,0 +1,208 @@
+<?php
+
+/**
+ * Controls Amenity definitions for the member db
+ * 
+ * PHP version 5
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handles creating / editing amenities that the members will use
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Billing_EditPaymentType
+    extends Toolkit_Members_Billing_Auxiliary
+{
+    /**
+     * class used for the database object
+     *
+     * @var    string
+     * @access public
+     */
+    public $className = 'Toolkit_Members_Billing_PaymentTypes';
+
+    /**
+     * template for edit form
+     *
+     * @var    string   
+     * @access protected
+     */
+    protected $formTemplate = 'editPaymentTypes.html';
+
+    /**
+     * Class constructor
+     *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                              submitted by adding a special hidden field
+     * 
+     * @access public
+     */
+    public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+    }
+
+    /**
+     * Form element definitions
+     * 
+     * @return void     
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e = array();
+        //    All Grouped Elements are created here.
+
+        //    All Elements are created here.
+        //    This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'PaymentTypeInfoHdr',
+            'display' => 'Payment Type'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'id'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'name',
+            'display' => 'Name'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'qcode',
+            'display' => 'Code'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'category',
+            'display' => 'Category'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'amount',
+            'display' => 'Amount'
+        );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => true,
+                       'name'    => 'dynamic_amount',
+                       'display' => 'Dynamic Amount',
+            'opts'    => 'Ask for the amount on Invoice Forms',
+                       'val'     => array(0, 1),
+               );
+        $e[] = array(
+            'type'    => 'textarea',
+            'req'     => false,
+            'name'    => 'notes',
+            'display' => 'Notes'
+        );
+
+
+        $this->setupElements($e);
+    }
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    /**
+     * Form rule definitions
+     * 
+     * @return void     
+     * @access public
+     */
+    public function configureRules()
+    {
+        $r = array();
+
+        $r[] = array(
+            'element' => 'amount',
+            'message' => 'ERROR: Invalid amount!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'qcode',
+            'message' => 'ERROR: Invalid number!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+
+        $this->setupRules($r);
+    }
+
+    /**
+     * Renders the form for viewing
+     *
+     * This function validates the form if needed, and if it successfully
+     * validates attempts to insert or update the data record.
+     * If it is unsuccessful, it will return an error to the user
+     * informing them of what went wrong.
+     *
+     * @return string The compiled and filled form template.
+     * @access public
+     */
+    public function toHtml()
+    {
+        $listPage = BASE_URL . 'admin/members.php?rt=Billing';
+        return parent::toHtml($listPage);
+    }
+}
diff --git a/Toolkit/Members/Billing/EmailInvoices.php b/Toolkit/Members/Billing/EmailInvoices.php
new file mode 100644 (file)
index 0000000..a749ad5
--- /dev/null
@@ -0,0 +1,251 @@
+<?php
+/**
+ * EmailInvoices.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_EmailInvoices
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_EmailInvoices
+    extends Toolkit_Members_Billing_InvoiceAbstract
+    implements Toolkit_Members_Billing_IInvoice
+{
+    /**
+     * Subject line for email
+     * 
+     * @var string
+     * @access protected
+     */
+    protected $subject = 'UPTRA Membership Invoice';
+
+    /**
+     * Billing storage array
+     *
+     * @var array
+     * @access protected
+     */
+    protected $billings = array();
+
+    /**
+     * Template file to use
+     * 
+     * @var string
+     * @access protected
+     */
+    protected $template = 'sendEmailInvoice.html';
+
+    /**
+     * Base of the billing template directory
+     *  
+     * @var string
+     * @access protected
+     */
+    protected $templateBase = 'Toolkit/Members/Billing/';
+    
+    /**
+     * The directory of the templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $templatesDir = 'templates';
+
+    /**
+     * The directory of the flexy-compiled templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $compiledDir = 'templates/compiled';
+    
+    /**
+     * Flexy Template Options array
+     * 
+     * @var array
+     * @access protected
+     */
+    protected $flexyOptions = array();
+
+    /**
+     * class Constructor
+     *
+     * @return void
+     * @access public
+     */
+    public function  __construct() 
+    {
+        $this->flexyOptions = array(
+            'templateDir'  => BASE . "{$this->templateBase}{$this->templatesDir}",
+            'compileDir'   => BASE . "{$this->templateBase}{$this->compiledDir}",
+            'forceCompile' => 1,
+            'debug'        => 0,
+            'locale'       => 'en',
+        );
+    }
+    /**
+     * get all members with the email type set and send them their invoices
+     *
+     * @param PDO $dbh Database Connection
+     * @todo     generate email from template
+     *
+     * @return void
+     */
+    public function emailInvoices(PDO $dbh)
+    {
+        $memberIds = array();
+        // get all member id's that have billing setup
+        $inv            = new Toolkit_Members_Billing_Invoices();
+        $members        = $inv->getMembersWithAccounts(
+            $dbh,
+            array(
+                'usmail_invoice' => 0,
+                'email_invoice'  => 1,
+                'fax_invoice'    => 0
+            )
+        );
+        $this->billings = $this->getLastInvoices($dbh, $members, 'emailed');
+        if ($this->billings) {
+            foreach ($this->billings as $bill) {
+                $this->send($dbh, $bill, $inv);
+            }
+        }
+        return $this->billings;
+    }
+
+    /**
+     * with an existing billing object set the billing feild emailed
+     * to true (boolean) and save it
+     *
+     * @param PDO                             $dbh     Database Connection
+     * @param Toolkit_Members_Billing_Billing $billing Billing object
+     *
+     * @return void
+     */
+    public function markSentToMember(
+        PDO $dbh,
+        Toolkit_Members_Billing_Billing $billing
+    ) {
+        $billing
+            ->setEmailed(1) // set to true
+            ->save($dbh); // save the object to database
+    }
+
+    /**
+     * Send the email to the member
+     *
+     * @param PDO                              $dbh  Database Connection
+     * @param Toolkit_Members_Billing_Billing  $bill Billing Object
+     * @param Toolkit_Members_Billing_Invoices $inv  Invoices Object
+     *
+     * @return string|mixed
+     */
+    protected function send(
+        PDO $dbh,
+        Toolkit_Members_Billing_Billing $bill,
+        Toolkit_Members_Billing_Invoices $inv
+    ) {
+        // felxy template
+        $template = new HTML_Template_Flexy($this->flexyOptions);
+        // member data
+        $memberData = $inv->getMemberData($dbh, $bill->getMember_id());
+        // object to merge in template
+        $page              = new stdClass;
+        $page->member_name = $bill->getMember_name();
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $page->companyName = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyName')
+            ->getContent();
+        $page->companyName2 = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyName2')
+            ->getContent();
+        $page->companyAddr1 = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyAddr1')
+            ->getContent();
+        $page->companyCity = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyCity')
+            ->getContent();
+        $page->companyState = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyState')
+            ->getContent();
+        $page->companyZip = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyZip')
+            ->getContent();
+        $page->companyPhone = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyPhone')
+            ->getContent();
+        $page->companyUrl = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyUrl')
+            ->getContent();
+        switch ($_ENV['GLM_HOST_ID']) {
+        case 'PRODUCTION' :
+            $email = $memberData['member_contact_email'];
+            break;
+        default :        
+            $email = 'steve@localhost';
+            break;
+        }
+        $template->compile($this->template);
+               $htmlMsg = $template->bufferedOutputObject($page);
+
+        $mimeMail = new Mail_mime("\n");
+               $mimeMail->setFrom("Billing <".OWNER_EMAIL.">");
+               $mimeMail->setSubject($this->subject);
+               $mimeMail->setHTMLBody($htmlMsg);
+        $res = $mimeMail->addAttachment(
+            $bill->getInvoiceAsPdf($dbh),
+            'application/pdf',
+            'Invoice-' . $bill->getInvoice_id(),
+            false,
+            'base64'
+        );
+        if (PEAR::isError($res)) {
+            var_dump($res->getMessage());
+            Toolkit_Common::handleError($res);
+        }
+               $mimeMail->setTXTBody($msg);
+
+               $mail =& Mail::factory('mail');
+               $body = $mimeMail->get();
+
+        $setHeader['Reply-To'] = OWNER_EMAIL;
+
+               $headers = $mimeMail->headers($setHeader);
+
+               $res = $mail->send($email, $headers, $body);
+        // mark the billings sent to member
+        //$this->markSentToMember($dbh, $bill);
+               if (PEAR::isError($res)) {
+                       return Toolkit_Common::handleError($res);
+               } else {
+                       return $res;
+               }
+        
+    }
+
+}
diff --git a/Toolkit/Members/Billing/Factory.php b/Toolkit/Members/Billing/Factory.php
new file mode 100644 (file)
index 0000000..9cf5a5a
--- /dev/null
@@ -0,0 +1,97 @@
+<?php
+/**
+ * Factory.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Toolkit
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Create an object from string class name
+ * if passed values will also create the object and assign it values
+ *
+ * @category Toolkit
+ * @package  Toolkit
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_Factory
+{
+    /**
+     * Static function can be called to create billing object from an id
+     *
+     * @param PDO     $dbh       Database Connection
+     * @param string  $className Class name of object to create
+     * @param integer $id        id to use for record
+     *
+     * @return object
+     */
+    static function createDbObjectById(PDO $dbh, $className, $id)
+    {
+        if (!is_numeric($id)) {
+            throw new InvalidArgumentException('Id must be numeric');
+        }
+        switch ($className) {
+        case 'Toolkit_Members_Billing_PaymentTypes' :
+            $factory = new Toolkit_Members_Billing_PaymentTypes();
+            return $factory->fetchById($dbh, $id);
+            break;
+
+        case 'Toolkit_Members_Billing_Billing' :
+            $factory = new Toolkit_Members_Billing_Billing();
+            return $factory->fetchById($dbh, $id);
+            break;
+
+        case 'Toolkit_Members_Billing_MemberAccount' :
+            $factory = new Toolkit_Members_Billing_MemberAccount();
+            return $factory->fetchById($dbh, $id);
+            break;
+
+        default:
+            return null;
+            break;
+        }
+    }
+
+    /**
+     * Static function can be called to create billing object from an array
+     *
+     * @param string $className Class name of object to create
+     * @param array  $values    array of values for the object
+     *
+     * @return object
+     */
+    static function createDBObjectByValues($className, $values)
+    {
+        if (!is_array($values)) {
+            throw new InvalidArgumentException('Values must be Array');
+        }
+        switch ($className) {
+        case 'Toolkit_Members_Billing_PaymentTypes' :
+            $factory = new Toolkit_Members_Billing_PaymentTypes();
+            return $factory->createByValues($values);
+            break;
+
+        case 'Toolkit_Members_Billing_Billing' :
+            $factory = new Toolkit_Members_Billing_Billing();
+            return $factory->createByValues($values);
+            break;
+
+        case 'Toolkit_Members_Billing_MemberAccount' :
+            $factory = new Toolkit_Members_Billing_MemberAccount();
+            return $factory->createByValues($values);
+            break;
+
+        default:
+            return null;
+            break;
+        }
+    }
+
+}
diff --git a/Toolkit/Members/Billing/IInvoice.php b/Toolkit/Members/Billing/IInvoice.php
new file mode 100644 (file)
index 0000000..0363e47
--- /dev/null
@@ -0,0 +1,38 @@
+<?php
+/**
+ * IInvoices.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_IInvoices
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+interface Toolkit_Members_Billing_IInvoice
+{
+    /**
+     * function to mark all billing records sent as sentToMember
+     * 
+     * @param PDO                             $dbh     Database handler
+     * @param Toolkit_Members_Billing_Billing $billing Description of $billing
+     * 
+     * @return void
+     * @access public
+     */
+    function markSentToMember(
+        PDO $dbh,
+        Toolkit_Members_Billing_Billing $billing
+    );
+}
diff --git a/Toolkit/Members/Billing/InvoiceAbstract.php b/Toolkit/Members/Billing/InvoiceAbstract.php
new file mode 100644 (file)
index 0000000..38d619b
--- /dev/null
@@ -0,0 +1,104 @@
+<?php
+/**
+ * InvoiceAbstract.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_InvoiceAbstract
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+abstract class Toolkit_Members_Billing_InvoiceAbstract
+{
+    /**
+     * Get the last invoice from the array of members given
+     * creates Toolkit_Members_Billing_Billing object for each member.
+     * If the last one was already sent then don't create a billing object
+     * Furthur restrict this to the current billing invoice year
+     *
+     * @param PDO    $dbh     Database handler
+     * @param array  $members Members array
+     * @param string $type    Type
+     *
+     * @return array|boolean
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function getLastInvoices(
+        PDO $dbh,
+        $members,
+        $type = 'emailed'
+    ) {
+        if (   !is_array($members)
+            || empty($members)
+        ) {
+            throw new InvalidArgumentException('$members must be an array');
+        }
+        $billings  = array();
+        $inv       = new Toolkit_Members_Billing_Invoices();
+        $startDate = new Date($inv->getCurrentInvoiceDate());
+        $endDate   = new Date($inv->getNextInvoiceDate());
+        try {
+            if (is_array($members)) {
+                foreach ($members as $member) {
+                    $memberIds[] = $member['member_id'];
+                }
+            }
+            if (!is_array($memberIds)) {
+                return false;
+            }
+            $sql = "
+              SELECT id, member_id
+                FROM billing
+               WHERE member_id IN (".implode(',', $memberIds).")
+                 AND (".$type." != 't'
+                     OR ".$type." IS NULL)
+                 AND billing_type = 1
+                 AND transaction_date BETWEEN :beginDate AND :endDate
+                -- AND (invoice != '' OR invoice IS NOT NULL)
+                 AND (paid = false OR paid IS NULL) 
+            ORDER BY member_name, id DESC";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':beginDate', $startDate->format("%m/%d/%Y"));
+            $stmt->bindParam(':endDate', $endDate->format("%m/%d/%Y"));
+            $stmt->execute();
+            $curMemberId = 0;
+            
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                    //if ($curMemberId != $row['member_id']) {
+                    // only if the $type Field is not true
+                    $billing
+                        = Toolkit_Members_Billing_Factory::createDbObjectById(
+                            $dbh,
+                            'Toolkit_Members_Billing_Billing',
+                            $row['id']
+                        );
+                    //var_dump($billing);
+                    $callFunction = 'get' . ucfirst($type);
+                    $wasSent = $billing->$callFunction();
+                if (!$wasSent) {
+                    $billings[] = $billing;
+                }
+                //}
+                //$curMemberId = $row['member_id'];
+            }
+            return (!empty($billings))
+                ? $billings
+                : false;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/Members/Billing/InvoiceDate.php b/Toolkit/Members/Billing/InvoiceDate.php
new file mode 100644 (file)
index 0000000..550b64b
--- /dev/null
@@ -0,0 +1,68 @@
+<?php
+/**
+ * InvoiceDate.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_InvoiceDate
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_InvoiceDate
+{
+    /**
+     * Start date for current billing invoice year
+     * @var date
+     * @access protected
+     */
+    protected $startDate;
+    
+    /**
+     * End date for current billing invoice year
+     * @var date 
+     * @access protected
+     */
+    protected $endDate;
+
+    /**
+     * invoice date object contains the start and end dates for the current
+     * billing invoice year.
+     * Start and End dates are PEAR::Date objects
+     *
+     * @param Date $startDate Start date for current billing invoice year
+     * @param Date $endDate   End date for current billing invoice year
+     *
+     * @return void
+     */
+    public function  __construct(Date $startDate, Date $endDate) 
+    {
+        $this->startDate = $startDate;
+        $this->endDate   = $endDate;
+    }
+
+    /**
+     * Return the starting date formatted or raw object
+     *
+     * @param mixed $format date format if not given the object is returned
+     *
+     * @return mixed
+     */
+    public function getStartDate($format = null)
+    {
+        if ($format) {
+            return $this->startDate->format($format);
+        }
+    }
+}
diff --git a/Toolkit/Members/Billing/InvoiceFilterForm.php b/Toolkit/Members/Billing/InvoiceFilterForm.php
new file mode 100644 (file)
index 0000000..884b168
--- /dev/null
@@ -0,0 +1,410 @@
+<?php
+
+/**
+ * InvoiceFilterForm.php
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Members_Billing_InvoiceFilterForm
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Billing_InvoiceFilterForm
+    extends Toolkit_FormBuilder
+{
+
+    /**
+     * Base of the billing template directory
+     *  
+     * @var string
+     * @access protected
+     */
+    protected $templateBase = 'Toolkit/Members/Billing/';
+    /**
+     * The directory of the templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $templatesDir = 'templates';
+
+    /**
+     * The directory of the flexy-compiled templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $compiledDir = 'templates/compiled';
+
+    /**
+     * The name of the template used for the form
+     *
+     * @var string
+     * @access protected
+     */
+    protected $formTemplate = 'invoiceFilterForm.html';
+
+    /**
+     * The object to use inside the form
+     *
+     * This object which is to be populated by the $this object                
+     * is used inside the templates and allows access back into the
+     * calling class to call publicly available functions
+     *
+     * @var    string
+     * @access protected
+     */
+    protected $view;
+
+    /**
+     * Class constructor
+     *
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                              submitted by adding a special hidden field
+     * 
+     * @access public
+     */
+    public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        $this->registeredRules = array();
+        switch ($_REQUEST['ac']) {
+        case 'createInvoices' :
+            $this->task = 'Create Invoices';
+            break;
+        case 'printInvoices' :
+            $this->task = 'Print Invoices';
+            break;
+        case 'createLabels' :
+            $this->task = 'Create Labels';
+            break;
+        case 'sendEmail' :
+            $this->task = 'Email Invoices';
+            break;
+        }
+
+        $options =& PEAR::getStaticProperty('HTML_Template_Flexy', 'options');
+        $options = array(
+            'templateDir'  => BASE . "{$this->templateBase}{$this->templatesDir}",
+            'compileDir'   => BASE . "{$this->templateBase}{$this->compiledDir}",
+            'forceCompile' => 1,
+            'debug'        => 0,
+            'locale'       => 'en',
+        );
+    }
+
+    /**
+     * Returns the BASE_URL
+     *
+     * This function is used inside the Flexy Templated forms
+     *
+     * @return string BASE_URL
+     * @access public
+     */
+    public function baseUrl()
+    {
+        return BASE_URL;
+    }
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureConstants()
+       {
+               $constants = array(
+                       'cat'    => $_REQUEST['rt'],
+                       'subCat' => $_REQUEST['ac'],
+            'tab'    => $_REQUEST['tab'],
+            'search' => 1
+               );
+
+               $this->setupConstants($constants);
+       }
+
+    /**
+     * Form element definitions
+     * 
+     * @return void     
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e = array();
+        //    All Grouped Elements are created here.
+        $paymentTypes = $this->getPaymentTypes();
+        $counties     = $this->getCounties();  
+        
+        //    All Elements are created here.
+        //    This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'PaymentTypeInfoHdr',
+            'display' => 'Filters'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'search'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'rt'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'ac'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'tab'
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'payment_type',
+            'display' => 'Payment Types',
+            'opts'    => $paymentTypes,
+            'att'    => array('multiple','size'=>10)
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'county',
+            'display' => 'Regions',
+            'opts'    => $counties,
+            'att'    => array('multiple','size'=>10)
+        );
+        if ($_REQUEST['tab'] == '3') {
+            $e[] = array(
+                'type'    => 'advcheckbox',
+                'req'     => false,
+                'name'    => 'balance_due',
+                'display' => 'Only Payments Due',
+                'opts'    => 'Yes',
+                'val'     => array(0, 1)
+            );
+        }
+
+        $this->setupElements($e);
+    }
+
+    /**
+     * Defines all filters used on form elements when submitted
+     *
+     * Most times this function won't need to be overridden.
+     *
+     * @return void
+     * @access public
+     */
+    protected function configureFilters()
+    {
+        $filters[] = array('element' => '__ALL__', 'filter' => 'trim');
+
+        $this->setupFilters($filters);
+    }
+    
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+               $this->configureFilters();
+               $this->configureConstants();
+    }
+    
+    /**
+     * Sets up the required / not-required rules for forms
+     *
+     * At the bare minimum, the required / not-required rules for form
+     * needs to be defined.  Since these rules are most easily defined
+     * while creating the element definitions themselves the base function
+     * is to call the setupRules function that will instantiate these
+     * rules in the quickform class.
+     *
+     * @return void
+     * @access public
+     */
+    protected function configureRules()
+    {
+        $this->setupRules();
+    }
+
+    /**
+     * Description for getCounties()
+     * 
+     * @return array
+     * @access protected
+     */
+    protected function getCounties()
+    {
+        $counties = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM region
+            ORDER BY region_name";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $counties[$row['region_id']] = $row['region_name'];
+            }
+            return $counties;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    
+    /**
+     * Description of getPaymentTypes()
+     * 
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentTypes()
+    {
+        $paymentTypes = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM payment_types
+            ORDER BY name";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $paymentTypes[$row['id']] = $row['name'];
+            }
+            return $paymentTypes;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Short description for processData()
+     * 
+     * Long description (if any) ...
+     * 
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return boolean Return description (if any) ...
+     * @access protected
+     */
+    protected function processData($values)
+    {
+        var_dump($values);
+        exit;
+        return true;
+    }
+
+    /**
+     * Sets up the rendering engine for the form
+     *
+     * @return void
+     * @access protected
+     */
+    protected function setupRenderers()
+    {
+        $renderer =& new HTML_QuickForm_Renderer_Object(true);
+
+        $this->accept($renderer);
+
+        $this->template =& new HTML_Template_Flexy($this->options);
+
+        //    Make the view a copy of the $this object
+        //    That way we have access to call functions in
+        //    this class from within the template.
+        $this->view = $this;
+        $this->view->form = $renderer->toObject();
+        $this->template->compile($this->formTemplate);
+    }
+
+    /**
+     * Renders the form for viewing
+     *
+     * This function validates the form if needed, and if it successfully
+     * validates attempts to insert or update the data record.
+     * If it is unsuccessful, it will return an error to the user
+     * informing them of what went wrong.
+     *
+     * @param string $listPage The page the header should redirect
+     *                           to on successful insert or update.
+     *
+     * @return string The compiled and filled form template.
+     * @access public
+     */
+    public function toHTML($listPage = 'index.php')
+    { 
+        //    We need to validate (and freeze if needed)
+        //    before we render the form. That way the
+        //    template knows about any errors on the form.
+        $this->validated = $this->validate();
+        $this->setupRenderers();
+
+        //if ($this->validated) {            
+        //}
+
+        return $errorMsg . $this->template->bufferedOutputObject($this->view);
+    }
+
+    /**
+     * Returns form message from validation attempts
+     *
+     * @return string validation message
+     * @access public
+     */
+    public function validated()
+    {
+        if ($this->validated) {
+            return $this->successMsg;
+        } elseif ($this->isSubmitted()) {
+            return $this->errorMsg;
+        }
+    }
+
+}
diff --git a/Toolkit/Members/Billing/InvoicePdf.php b/Toolkit/Members/Billing/InvoicePdf.php
new file mode 100644 (file)
index 0000000..16785cc
--- /dev/null
@@ -0,0 +1,553 @@
+<?php
+/**
+ * InvoicePdf.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+require_once GLM_APP_BASE . 'pdf/pdf_lib_8/GlmPdf.php';
+/**
+ * Toolkit_Members_Billing_InvoicePdf
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_InvoicePdf
+    extends GlmPdf
+{
+    /**
+     * Class Constructor
+     * 
+     * @access public
+     */
+    public function  __construct()
+    {
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $this->config = $root;
+    }
+
+    /**
+     * Creates the array for forms then generates the string for a pdf
+     *
+     * @param PDO $dbh        Database Connection
+     * @param int $member_id  Member id
+     * @param int $invoice_id The invoice_id from the new invoice record
+     * @param int $account_id The Account ID.
+     *
+     * @return string
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function createPdfInvoice(
+        PDO $dbh,
+        $member_id,
+        $invoice_id,
+        $account_id
+    ) {
+        if (!is_numeric($member_id)) {
+            throw new InvalidArgumentException('member_id must be numeric');
+        }
+        if (!is_numeric($invoice_id)) {
+            throw new InvalidArgumentException('invoice_id must be numeric');
+        }
+        if (!is_numeric($account_id)) {
+            throw new InvalidArgumentException('account_id must be numeric');
+        }
+        // grab all billing data for this member
+        $items = array();
+        $stmt = new Toolkit_Members_Billing_Statement();
+        $transactions = $stmt->getMemberBillings(
+            $dbh,
+            $member_id,
+            $account_id
+        );
+        
+        $memberAccount = Toolkit_Members_Billing_Factory::createDbObjectById(
+            $dbh,
+            'Toolkit_Members_Billing_MemberAccount',
+            $account_id
+        );
+        if ($memberAccount) {
+            $payment_type_id = $memberAccount->getPayment_type();
+        }
+        if ($payment_type_id) {
+            $paymentType = Toolkit_Members_Billing_Factory::createDbObjectById(
+                $dbh,
+                'Toolkit_Members_Billing_PaymentTypes',
+                $payment_type_id
+            );
+            $payment_type_name = $paymentType->getName();
+        }
+        if (is_array($transactions) && !empty($transactions)) {
+            foreach ($transactions as $transaction) {
+                $items[] = array(
+                    'type'    => $transaction->getBilling_type(),
+                    'date'    => $transaction->getTransaction_date(),
+                    'descr'   => 'Membership Dues ' . $payment_type_name,// @todo needs to say which payment_type
+                    'amount'  => $transaction->getAmount(),
+                    'balance' => $transaction->getBalance()
+                );
+            }
+        }
+
+        $memberData = $this->getMemberData($dbh, $member_id);
+        $companyLogo = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyLogo')
+            ->getContent();
+        $companyLogoHeight = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyLogoHeight')
+            ->getContent();
+        $companyName = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyName')
+            ->getContent();
+        $companyName2 = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyName2')
+            ->getContent();
+        $companyAddr1 = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyAddr1')
+            ->getContent();
+        $companyAddr2 = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyAddr2')
+            ->getContent();
+        $companyCity = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyCity')
+            ->getContent();
+        $companyState = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyState')
+            ->getContent();
+        $companyZip = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyZip')
+            ->getContent();
+        $companyPhone = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyPhone')
+            ->getContent();
+        $companyEmail = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'companyEmail')
+            ->getContent();
+        if ($memberData['mailing_address']) {
+            $streetAddress = $memberData['mailing_address'];
+            $cityName
+                = ($memberData['mailing_city_id'])
+            ? $this->getCityName($dbh, $memberData['mailing_city_id'])
+            : '';
+            $stateName
+                = ($memberData['mailing_state_id'])
+            ? $this->getStateName($dbh, $memberData['mailing_state_id'])
+            : '';
+            $zipCode = $memberData['mailing_zip'];
+        } else {
+            $streetAddress = $memberData['street'];
+            $cityName
+                = ($memberData['city_id'])
+            ? $this->getCityName($dbh, $memberData['city_id'])
+            : '';
+            $stateName
+                = ($memberData['state_id'])
+            ? $this->getStateName($dbh, $memberData['state_id'])
+            : '';
+            $zipCode = $memberData['zip'];
+        }
+        $primaryContactName
+            = $memberData['billing_contact'];
+        // For the invoice date we need to use either one of three dates depending on what 
+        // day she is printing the invoice
+        // if she prints this invoice two weeks before Aug 1st or Sep 1st then 
+        // use either of them that are within two weeks otherwise use July 1st
+        // After July 18th use Aug 1st
+        // After Aug 18th use Sep 1st
+        // else use July 1st
+        $currentDateDay   = date('j');
+        $currentDateMonth = date('n');
+        if ($currentDateMonth > 8) {
+            $monthForInvDate = 9;
+        } else if ($currentDateMonth == 8) {
+            $monthForInvDate
+                = ($currentDateDay >= 18)
+                ? 9
+                : 8;
+        } else if ($currentDateMonth == 7) {
+            $monthForInvDate
+                = ($currentDateDay >= 18)
+                ? 8
+                : 7;
+        } else if ($currentDateMonth < 7) {
+            $monthForInvDate = 7;
+        }
+        $invDate = date('n/d/Y');
+        $test_data = array(
+            'company_logo'        => BASE . $companyLogo,
+            'company_logo_height' => $companyLogoHeight,
+            'company_name'        => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyName),
+            'company_name2'       => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyName2),
+            'company_addr1'       => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyAddr1),
+            'company_addr2'       => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyAddr2),
+            'company_city'        => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyCity),
+            'company_state'       => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyState),
+            'company_zip'         => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyZip),
+            'company_phone'       => $companyPhone,
+            'company_email'       => iconv('UTF-8', 'ISO-8859-1//IGNORE', $companyEmail),
+
+            'invoice_date'        => $invDate,
+            'invoice_number'      => $invoice_id,
+            'invoice_balance'     => $stmt->getBalanceDue(
+                $dbh,
+                $member_id,
+                $account_id
+            ),
+            'invoice_file_name'   => "invoice_{$invoice_id}.pdf",
+
+            'member_billing_no'   => $memberData['account_number'],
+            'member_name'         => iconv('UTF-8', 'ISO-8859-1//IGNORE', $memberData['member_name']),
+            'member_addr1'        => iconv('UTF-8', 'ISO-8859-1//IGNORE', $streetAddress),
+            'member_city'         => $cityName,
+            'member_state'        => $stateName,
+            'member_zip'          => $zipCode,
+            'member_contact_name' => iconv('UTF-8', 'ISO-8859-1//IGNORE', $primaryContactName),
+
+            'payment_terms'       => iconv('UTF-8', 'ISO-8859-1//IGNORE', 'Membership dues need to be paid by October 1st'),
+
+            'items'               => $items
+        );
+        return $this->glmPdfInvoice($test_data);
+    }
+
+    /**
+     * Get the city_name from the city table given an id
+     *
+     * @param PDO $dbh Database Connection
+     * @param int $id  City id
+     *
+     * @return string
+     * @access public
+     */
+    public function getCityName(PDO $dbh, $id)
+    {
+        if (!is_numeric($id)) {
+            throw new InvalidArgumentException('id must be numeric');
+        }
+        try {
+            $sql = "
+            SELECT city_name
+              FROM city
+             WHERE city_id = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':id',
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * From the member_id get the member name
+     *
+     * @param PDO     $dbh Database Connection
+     * @param integer $id  Member_id field
+     *
+     * @return string
+     * @access public
+     */
+    public function getMemberData(PDO $dbh, $id)
+    {
+        try {
+            $sql = "
+              SELECT *
+                FROM member
+               WHERE member_id = :member_id
+            ORDER BY member_name";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    
+    /**
+     * Get the state_abb from the state table given an id
+     *
+     * @param PDO $dbh Database Connection
+     * @param int $id  State id
+     *
+     * @return string
+     * @access public
+     */
+    public function getStateName(PDO $dbh, $id)
+    {
+        if (!is_numeric($id)) {
+            throw new InvalidArgumentException('id must be numeric');
+        }
+        try {
+            $sql = "
+            SELECT state_abb
+              FROM state
+             WHERE state_id = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':id',
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Create the pdf from the pdflib functions
+     *
+     * @param array $inv Array of form values for the pdf
+     *
+     * @return string
+     * @access public
+     * @throws Exception
+     */
+    function glmPdfInvoice($inv)
+    {
+        $invoiceForms = array(
+            1 => array( 'x' => 0, 'y' => 0, 'xs' => 612,  'ys' => 792 )
+        );
+
+        // Initialize Forms
+        $r = $this->glmpdfSetForms(
+            count($invoiceForms),
+            $invoiceForms,
+            $this->glmpdfStandardPage[PAPER_SIZE]['x'],
+            $this->glmpdfStandardPage[PAPER_SIZE]['y']
+        );
+        if (!$r) {
+            echo "ERROR: Unable to set PDF forms layout.";
+            exit;
+        }
+
+        // Start PDF Generation - (Creator, Author, Title)
+        $this->glmpdfStart("GLM PDF", "Gaslight Media", "Standard Invoice with Payment Form");
+
+        // Load barcode font
+        if (!$this->glmpdfAddFont('barcode', 'barcode/FREE3OF9.TTF')) {
+            throw new Exception(
+                'ERROR: Unable to add barcode font.<P>
+                Did you place the barcode font into a system fonts directory
+                (/usr/share/fonts/ttf) and set the fonts directory correctly in the
+                pdf_functions.inc file?'
+            );
+            exit;
+        }
+
+        // Create new form
+        $this->glmpdfNextForm();
+
+        // Create Company Header
+        if (trim($inv['company_logo']) != '') {
+            $logo_y = 760 - $inv['company_logo_height'];
+            $logoImage = $this->glmpdfOpenImage($inv['company_logo']);
+            $this->glmpdfPlaceImage($logoImage, 5, $logo_y, .45);
+        }
+        $this->glmpdfSetFont("Helvetica-Bold", 12.0);
+        $this->glmpdfPlaceText($inv['company_name'], 20, 660, "left", 'black');
+        $this->glmpdfSetFont("Helvetica", 12.0);
+        $this->glmpdfPlaceText($inv['company_addr1'], 20, $this->glmpdfCurrentY, "left", 'black');
+        if (trim($inv['company_addr2']) != '') {
+            $this->glmpdfPlaceText($inv['company_addr2'], 20, $this->glmpdfCurrentY, "left", 'black');
+        }
+        $city_state = $inv['company_city'].', '.$inv['company_state'].' '.$inv['company_zip'];
+        $this->glmpdfPlaceText($city_state, 20, $this->glmpdfCurrentY, "left", 'black');
+        $this->glmpdfPlaceText($inv['company_phone'], 20, $this->glmpdfCurrentY, "left", 'black');
+        $this->glmpdfPlaceText($inv['company_email'], 20, $this->glmpdfCurrentY, "left", 'black');
+
+        // Invoice Header
+        $this->glmpdfSetFont("Helvetica-Bold", 26.0);
+        $this->glmpdfPlaceText('INVOICE', 570, 710, "right", 'black');
+        $this->glmpdfSetFont("Helvetica", 12.0);
+        $this->glmpdfPlaceText('Date:', 350, 650, "left", 'black');
+        $this->glmpdfPlaceText($inv['invoice_date'], 450, $this->glmpdfLastY, "left", 'black');
+//        $this->glmpdfPlaceText('Invoice #:', 350, $this->glmpdfCurrentY, "left", 'black');
+//        $this->glmpdfPlaceText($inv['invoice_number'], 450, $this->glmpdfLastY, "left", 'black');
+        $this->glmpdfPlaceText('Member Billing #:', 350, $this->glmpdfCurrentY, "left", 'black');
+        $this->glmpdfPlaceText($inv['member_billing_no'], 450, $this->glmpdfLastY, "left", 'black');
+
+        // Member Info
+        $this->glmpdfSetFont("Helvetica-Bold", 22.0);
+        $this->glmpdfPlaceText('Bill To:', 20, 570, "left", 'black');
+        $this->glmpdfSetFont("Helvetica", 12.0);
+        $this->glmpdfPlaceText($inv['member_name'], 20, $this->glmpdfCurrentY, "left", 'black');
+        if ($inv['member_contact_name']) {
+            $this->glmpdfPlaceText($inv['member_contact_name'], 20, $this->glmpdfCurrentY, "left", 'black');
+        }
+        $this->glmpdfPlaceText($inv['member_addr1'], 20, $this->glmpdfCurrentY, "left", 'black');
+        if (trim($inv['member_addr2']) != '') {
+            $this->glmpdfPlaceText($inv['member_addr2'], 20, $this->glmpdfCurrentY, "left", 'black');
+        }
+        $city_state = $inv['member_city'].', '.$inv['member_state'].' '.$inv['member_zip'];
+        $this->glmpdfPlaceText($city_state, 20, $this->glmpdfCurrentY, "left", 'black');
+        //$this->glmpdfPlaceText($inv['member_email'], 20, $this->glmpdfCurrentY, "left", 'black');
+
+        // Items Header
+        //$this->glmpdfPlaceBox(1, 20, 470, 550, 20, 'white', 'white', 'round');
+        $this->glmpdfSetFont("Helvetica-Bold", 12.0);
+        $this->glmpdfPlaceText('Date', 30, 470, "left", 'black');
+        $this->glmpdfPlaceText('Description', 110, $this->glmpdfLastY, "left", 'black');
+        $this->glmpdfPlaceText('Amount', 490, $this->glmpdfLastY, "right", 'black');
+        $this->glmpdfPlaceText('Balance', 560, $this->glmpdfLastY, "right", 'black');
+        $this->glmpdfPlaceLine(1, 20, $this->glmpdfLastY - 3, 570, $this->glmpdfLastY - 3, 'black');
+
+        // Items
+        $this->glmpdfSetFont("Helvetica", 12.0);
+        $this->glmpdfPlaceText('', 30, $this->glmpdfLastY, "left", 'black');
+        foreach ($inv['items'] as $item) {
+            switch ($item['type']) {
+            // Type 1 - Invoice
+            case 1;
+                $this->glmpdfPlaceText($item['date'], 30, $this->glmpdfCurrentY, "left", 'black');
+                $this->glmpdfPlaceText($item['descr'], 110, $this->glmpdfLastY, "left", 'black');
+                $this->glmpdfPlaceText($this->money($item['amount']), 490, $this->glmpdfLastY, "right", 'black');
+                $this->glmpdfPlaceText($this->money($item['balance']), 560, $this->glmpdfLastY, "right", 'black');
+                break;
+
+            // Type 2 - Payment
+            case 2:
+                $this->glmpdfPlaceText($item['date'], 30, $this->glmpdfCurrentY, "left", 'black');
+                $this->glmpdfPlaceText('Payment - Thank You!', 110, $this->glmpdfLastY, "left", 'black');
+                $this->glmpdfPlaceText($this->money($item['amount']*-1), 490, $this->glmpdfLastY, "right", 'black');
+                $this->glmpdfPlaceText($this->money($item['balance']), 560, $this->glmpdfLastY, "right", 'black');
+                break;
+
+            }
+        }
+
+        // Terms
+        $this->glmpdfSetFont("Helvetica-Bold", 12.0);
+        $this->glmpdfPlaceText('Payment Terms', 30, 200, "left", 'black');
+        $this->glmpdfPlaceLine(1, 20, 197, 570, 197, 'black');
+        $this->glmpdfSetFont("Helvetica", 12.0);
+        $this->glmpdfPlaceText($inv['payment_terms'], 30, 180, "left", 'black');
+        
+
+        // Tear-off Payment Form
+        $this->glmpdfPlaceLine(1, 20, 150, 570, 150, 'black', true, 4, 14);
+        $this->glmpdfSetFont("Helvetica", 10.0);
+        $this->glmpdfPlaceText('Please return this coupon below with your payment.', 300, 154, 'center', 'black');
+        $this->glmpdfPlaceText('Make checks payable to:', 20, 140, 'left', 'red');
+        $this->glmpdfSetFont("Helvetica", 12.0);
+
+        $this->glmpdfPlaceText($inv['company_name2'], 20, 128, "left", 'black');
+        $addr = $inv['company_addr1'];
+        if (trim($inv['company_addr2']) != '') {
+            $addr .= ', '.$inv['company_addr2'];
+        }
+        $addr .= ', '.$inv['company_city'].', '.$inv['company_state'].' '.$inv['company_zip'];
+        $this->glmpdfPlaceText($addr, 20, $this->glmpdfCurrentY, "left", 'black');
+        $this->glmpdfPlaceText($inv['company_phone'].'  -  '.$inv['company_email'], 20, $this->glmpdfCurrentY, "left", 'black');
+
+        $this->glmpdfPlaceText($inv['member_name'], 20, 80, "left", 'black');
+        $this->glmpdfPlaceText($inv['member_addr1'], 20, $this->glmpdfCurrentY, "left", 'black');
+        if (trim($inv['member_addr2']) != '') {
+            $this->glmpdfPlaceText($inv['member_addr2'], 20, $this->glmpdfCurrentY, "left", 'black');
+        }
+        $city_state = $inv['member_city'].', '.$inv['member_state'].' '.$inv['member_zip'];
+        $this->glmpdfPlaceText($city_state, 20, $this->glmpdfCurrentY, "left", 'black');
+        $this->glmpdfPlaceText($inv['member_phone'], 20, $this->glmpdfCurrentY, "left", 'black');
+        $this->glmpdfPlaceText($inv['member_email'], 20, $this->glmpdfCurrentY, "left", 'black');
+
+        $this->glmpdfSetFont("Helvetica-Bold", 12.0);
+        $this->glmpdfPlaceText('Please Pay:', 450, 80, "right", 'black');
+        $this->glmpdfPlaceText($this->money($inv['invoice_balance']), 560, $this->glmpdfLastY, "right", 'black');
+
+        $this->glmpdfSetFont("Helvetica-Bold", 12.0);
+        if (($inv['invoice_balance']-0) > 0) {
+            $this->glmpdfPlaceText('Payment Amount:', 450, 60, "right", 'black');
+            $this->glmpdfPlaceBox(1, 460, 75, 100, 20, 'black', 'white');
+        } else {
+            $this->glmpdfPlaceText('NO PAYMENT REQUIRED', 560, 60, "right", 'black');
+        }
+
+        $this->glmpdfSetFont("Helvetica", 12.0);
+        $this->glmpdfPlaceText('Member Billing #:', 450, 30, "right", 'black');
+        $this->glmpdfPlaceText($inv['member_billing_no'], 560, $this->glmpdfLastY, "right", 'black');
+
+        $barcode = $inv['member_billing_no'].'-'.$inv['invoice_number'];
+        $this->glmpdfSetFont('barcode', 40);
+        $this->glmpdfPlaceText("*$barcode*", 560, 110, 'right', 'black');
+        return $this->glmpdfEnd();
+    }
+
+    /**
+     * Format to money
+     *
+     * @param integer $value  Value
+     * @param string  $option Option
+     *
+     * @return string
+     * @access public
+     */
+    function money($value, $option = "")
+    {
+        // Check if the "NOPREFIX" option is specified
+        if (strstr($option, 'NOPREFIX')) {
+            $prefix = "";
+        } else {
+            $prefix = "$";
+        }
+
+        // Check if it's a negative value. If so, save that and make it positive.
+        $neg = false;
+        if ($value < 0) {
+            $neg = true;
+            $value *= -1;
+        }
+
+        // Do value sanity check
+        if (!is_numeric($value)) {
+            return $prefix . "0.00";
+        }
+
+        // Format number and add prefix
+        $r = $prefix.number_format($value, 2, ".", ",");
+
+        // Check if the value was negative.
+        if ($neg) {
+            if (strstr($option, 'NEG_PAREN')) {
+                $r = '('.$r.')';
+            } else {
+                $r = '-'.$r;
+            }
+        }
+
+        return $r;
+    }
+}
diff --git a/Toolkit/Members/Billing/Invoices.php b/Toolkit/Members/Billing/Invoices.php
new file mode 100644 (file)
index 0000000..5de9c39
--- /dev/null
@@ -0,0 +1,439 @@
+<?php
+/**
+ * Invoices.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+require_once GLM_APP_BASE . 'pdf/pdf_lib_8/GlmPdf.php';
+/**
+ * Toolkit_Members_Billing_Invoices
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_Invoices
+{
+
+    /**
+     * Class Constructor
+     * 
+     * @access public
+     */
+    public function  __construct()
+    {
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $this->config = $root;
+    }
+
+    /**
+     * Add invoice for the member (full price for the year)
+     * this will need to create a PDF using php pdf pdflib functions
+     *
+     * @param PDO   $dbh Database Connection
+     * @param array $row Member data array
+     *
+     * @return void
+     * @access public
+     * @throws Exception
+     */
+    public function addInvoice(PDO $dbh, $row)
+    {
+        $paymentType = Toolkit_Members_Billing_Factory::createDbObjectById(
+            $dbh,
+            'Toolkit_Members_Billing_PaymentTypes',
+            $row['payment_type']
+        );
+        if (!($paymentType instanceof Toolkit_Members_Billing_PaymentTypes)) {
+            throw new Exception(
+                'Payment Type is not an instance of
+                Toolkit_Members_Billing_PaymentTypes'
+            );
+        }
+
+        $currentInvoiceDate = $this->getCurrentInvoiceDate(true);
+
+        $amount = $paymentType->getAmount();
+        if ($amount > 0) {
+            $memberData = $this->getMemberData($dbh, $row['member_id']);
+            //var_dump($memberData);exit;
+            $stmt = new Toolkit_Members_Billing_Statement();
+            $transactionDate = date(
+                'm/d/Y',
+                $currentInvoiceDate
+            );
+            $invoice = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_Billing',
+                array(
+                    'member_name'      => $memberData['member_name'],
+                    'member_id'        => $row['member_id'],
+                    'transaction_date' => $transactionDate,
+                    'transaction_time' => date('m/d/Y H:i:s'),
+                    'account_number'   => $row['account_number'],
+                    'account_id'       => $row['account_id'],
+                    'billing_type'     => 1,
+                    'amount'           => (float)$amount,
+                    'emailed'          => 0,
+                    'printed'          => 0,
+                    'notes'            => '',
+                    'balance'          => (float)($stmt->getBalanceDue(
+                        $dbh,
+                        $row['member_id'],
+                        $row['account_id']
+                    ) + $amount)
+                 )
+            );
+
+            $invoice->save($dbh);
+        }
+    }
+
+    /**
+     * creating invoices
+     * 1) get only active members
+     * 2) get only members that do not have current invoice for this year
+     * 3) year
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return string
+     * @access public
+     */
+    public function createInvoices(PDO $dbh)
+    {
+        $membersWithAccounts = $this->getMembersWithAccounts($dbh);
+        if (!empty($membersWithAccounts)) {
+            foreach ($membersWithAccounts as $member) {
+                $hasInvoice = $this->hasInvoice($dbh, $member);
+                if (!$hasInvoice) {
+                    $this->addInvoice($dbh, $member);
+                }
+            }
+        }
+        return '<div id="">Created Invoices</div>';
+    }
+    
+    /**
+     * Description of listCreateInvoices
+     * 
+     * @param PDO $dbh Database Handler
+     * 
+     * @return array
+     * @access public 
+     */
+    public function listCreateInvoices(PDO $dbh)
+    {
+        $membersWithAccounts = $this->getMembersWithAccounts($dbh);
+        if (!empty($membersWithAccounts)) {
+            foreach ($membersWithAccounts as $member) {
+                $hasInvoice = $this->hasInvoice($dbh, $member);
+                if (!$hasInvoice) {
+                    $newMembers[] = $member;
+                }
+            }
+        }
+        return $newMembers;
+    }
+    
+    /**
+     * From the member_id get the member name
+     *
+     * @param PDO     $dbh Database Connection
+     * @param integer $id  Member_id field
+     * 
+     * @return string
+     */
+    public function getMemberData(PDO $dbh, $id)
+    {
+        try {
+            $sql = "
+            SELECT *
+              FROM member
+             WHERE member_id = :member_id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * get an array of members with account data
+     * 
+     * @param PDO $dbh   Database Connetion
+     * @param int $types email,usmail,fax pref
+     * 
+     * @return array
+     * @access public
+     */
+    public function getMembersWithAccounts(PDO $dbh, $types = array())
+    {
+        $members = array();
+        if (empty($types)) {
+            $types = array(
+                'email_invoice'  => 0,
+                'usmail_invoice' => 0,
+                'fax_invoice'    => 0
+            );
+        }
+        try {
+            $params = array();
+            $sql = "
+            SELECT m.member_id,m.member_name,
+                   ma.id as account_id,m.account_number,ma.payment_type
+              FROM member m, member_account ma
+             WHERE m.active = 't'
+               AND m.member_id = ma.member_id";
+            if ($types['email_invoice']) {
+                $params[] = "ma.email_invoice = 't'";
+            }
+            if ($types['usmail_invoice']) {
+                $params[] = "ma.usmail_invoice = 't'";
+            }
+            if ($types['fax_invoice']) {
+                $params[] = "ma.fax_invoice = 't'";
+            }
+            $payment_types = (is_array($_POST['payment_type']))
+                ? array_filter($_POST['payment_type'])
+                : null;
+            if ($payment_types) {
+                $params2[]
+                    = "ma.payment_type in ("
+                    . implode(",", $payment_types)
+                    . ")";
+            }
+            $counties = (is_array($_POST['county']))
+                ? array_filter($_POST['county'])
+                : null;
+            if ($counties) {
+                $params2[]
+                    = "m.region in ("
+                    . implode(",", $counties)
+                    . ")";
+            }
+            if (!empty($params)) {
+                $sql .= " AND (" . implode(" OR ", $params) . ")";
+            }
+            if (!empty($params2)) {
+                $sql .= " AND (" . implode(" AND ", $params2) . ")";
+            }
+            $sql .= " ORDER BY m.member_name";
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $members[] = $row;
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $members;
+    }
+
+    /**
+     * get array of member without account data
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return array
+     * @access public
+     */
+    public function getMembersWithOutAccounts(PDO $dbh)
+    {
+        $members = array();
+        try {
+            $sql = "
+            SELECT member_id,member_name
+              FROM member
+             WHERE active = 't'
+               AND (member_id NOT IN (
+                   SELECT DISTINCT member_id
+                   FROM member_account
+                   )
+                   OR (account_number is null OR account_number = '')
+                   )";
+            $sql .= " ORDER BY member_name";
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $members[] = $row;
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $members;
+    }
+
+    /**
+     * get the current invoice date for members
+     * 
+     * Grabs the invoiceDay and invoiceMonth from config.ini and creates a
+     * timestamp using current year. If this timestamp is greater than current
+     * date then it will substract a year and use that timestamp.
+     * 
+     * @param boolean $all Description for $all
+     * 
+     * @return integer
+     * @access public
+     */
+    public function getCurrentInvoiceDate($all = false)
+    {
+        // invoice date
+        $invoiceDay = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'invoiceDay')
+            ->getContent();
+        $invoiceMonth = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'invoiceMonth')
+            ->getContent();
+        $currentInvoiceDate = mktime(
+            0,
+            0,
+            0,
+            $invoiceMonth,
+            $invoiceDay,
+            date('Y')
+        );
+        if ($currentInvoiceDate > mktime() && !$all) {
+            $currentInvoiceDate = mktime(
+                0,
+                0,
+                0,
+                $invoiceMonth,
+                $invoiceDay,
+                date('Y') - 1
+            );
+        }
+        return $currentInvoiceDate;
+    }
+    
+    /**
+     * get the next invoice date for prorated members
+     * that hasn't passed yet this year.
+     *
+     * @return integer
+     * @access public
+     */
+    public function getNextInvoiceDate()
+    {
+        // invoice date
+        $invoiceDay = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'invoiceDay')
+            ->getContent();
+        $invoiceMonth = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'invoiceMonth')
+            ->getContent();
+        $nextInvoiceDate = mktime(
+            0,
+            0,
+            0,
+            $invoiceMonth,
+            $invoiceDay,
+            date('Y')
+        );
+        if ($nextInvoiceDate <= mktime()) {
+            $nextInvoiceDate = mktime(
+                0,
+                0,
+                0,
+                $invoiceMonth,
+                $invoiceDay,
+                date('Y') + 1
+            );
+        }
+        return $nextInvoiceDate;
+    }
+
+    /**
+     * Check to see if the member has a current invoice (this year) or not
+     * Need to check based on the record in member_account table
+     *
+     * @param PDO   $dbh    Database Connection
+     * @param array $member Member array
+     *
+     * @return boolean
+     * @access public
+     */
+    public function hasInvoice(PDO $dbh, $member)
+    {
+        $nextInvoiceDate    = $this->getNextInvoiceDate();
+        $currentInvoiceDate = $this->getCurrentInvoiceDate();
+        try {
+            $sql = "
+            SELECT *
+              FROM billing
+             WHERE billing_type = 1
+               AND transaction_date BETWEEN
+                   '".date('m/d/Y', $currentInvoiceDate)."'
+                   AND
+                   '".date('m/d/Y', $nextInvoiceDate)."'
+               AND member_id = :member_id
+               AND account_id = :account_id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $member['member_id'],
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':account_id',
+                $member['account_id'],
+                PDO::PARAM_STR
+            );
+            $stmt->execute();
+            return (bool)$stmt->rowCount();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Output the billing invoice field to the browser
+     * 
+     * Billing invoice field contains the pdf base64encoded
+     *
+     * @param PDO    $dbh        Database Connection
+     * @param int    $invoice_id Billing table id
+     * @param string $name       Filename Out
+     *
+     * @return mixed
+     */
+    public function pdfToBrowser(PDO $dbh, $invoice_id, $name = 'output.pdf')
+    {
+        $billing = Toolkit_Members_Billing_Factory::createDbObjectById(
+            $dbh,
+            'Toolkit_Members_Billing_Billing',
+            $invoice_id
+        );
+        $buf = $billing->getInvoiceAsPdf($dbh);
+        $pdf = new Toolkit_Members_Billing_InvoicePdf();
+        if (!$buf) {
+            return false;
+        }
+        $len = strlen($buf);
+        header("Content-type: application/pdf");
+        header("Content-Length: $len");
+        header("Content-Disposition: inline; filename=$name");
+        echo $buf;
+    }
+}
diff --git a/Toolkit/Members/Billing/ListPaymentTypes.php b/Toolkit/Members/Billing/ListPaymentTypes.php
new file mode 100644 (file)
index 0000000..2fd292d
--- /dev/null
@@ -0,0 +1,112 @@
+<?php
+/**
+ * ListPaymentTypes.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_ListPaymentTypes
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_ListPaymentTypes
+    extends Toolkit_DataGridBuilder
+{
+    /**
+     * Class constructor
+     * 
+     * Instantiates a DataGrid and sets up when to make the grid sortable
+     * 
+        * @param PDO     $pdo          PDO object
+     * @param integer $limit        The number of records to display per page.
+     * @param integer $page         The current page view. In most cases,
+        *                                                              this is useless. Note: if you specify
+        *                                                              this, the "page"GET variable will be ignored.
+     * @param string  $rendererType The type of renderer to use. You may
+        *                                                              prefer to use the $type argument of
+        *                                                              render, fill or getOutput.
+        *
+     * @return void   
+     * @access public 
+     */
+    public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null
+    ) {
+               parent::__construct($pdo, $limit, $page, $rendererType);
+        $sql = "
+        SELECT *
+          FROM payment_types";
+        $this->setQuery($sql);
+               $this->options = array('dbc' => $pdo);
+        $defaultSort = array('name' => 'ASC');
+               $this->setDefaultSort($defaultSort);
+               if (!is_null($limit)) {
+                       $this->sortableAfter = $limit;
+               }
+       }
+
+    /**
+     * configure retrieved columns
+     *
+     * Tells the DataGrid how to render the retrieved columns
+     * 
+        * @return void
+     * @access protected
+     */
+    protected function configureColumns() 
+    {
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Function',
+                null,
+                null,
+                null,
+                null,
+                array($this, 'editButton')
+            )
+        );
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Name',
+                'name',
+                'name'
+            )
+        );
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Amount',
+                'amount',
+                'amount'
+            )
+        );
+    }
+
+    /**
+     * Description of editButton()
+     * 
+     * @param array $data Data
+     * 
+     * @return string
+     * @access public 
+     */
+    public function editButton($data)
+    {
+        $format = '<a href="'.BASE_URL.'admin/members.php?rt=Billing&ac=EditPaymentType&id=%s">Edit</a>';
+        return sprintf($format, $data['record']['id']);
+    }
+}
+?>
diff --git a/Toolkit/Members/Billing/MailingLabelPdf.php b/Toolkit/Members/Billing/MailingLabelPdf.php
new file mode 100644 (file)
index 0000000..5100703
--- /dev/null
@@ -0,0 +1,308 @@
+<?php
+/**
+ * MailingLabelPdf.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+require_once GLM_APP_BASE . 'pdf/pdf_lib_8/GlmPdf.php';
+/**
+ * Toolkit_Members_Billing_MailingLabelPdf
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_MailingLabelPdf
+    extends GlmPdf
+{
+    /**
+     * Description of getCities()
+     * 
+     * @param PDO $dbh Database handler
+     * 
+     * @return array
+     * @access protected 
+     */
+    protected function getCities(PDO $dbh)
+    {
+        $cities = array();
+        try {
+            $sql = "
+              SELECT *
+                FROM city
+            ORDER BY city_id";
+            $stmt = $dbh->query($sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $cities[$row['city_id']] = $row['city_name'];
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $cities;
+    }
+    
+    /**
+     * Description of getStates
+     * 
+     * @param PDO $dbh database handler
+     * 
+     * @return array
+     * @access protected 
+     */
+    protected function getStates(PDO $dbh)
+    {
+        $states = array();
+        try {
+            $sql = "
+              SELECT *
+                FROM state
+            ORDER BY state_id";
+            $stmt = $dbh->query($sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $states[$row['state_id']] = $row['state_abb'];
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $states;
+    }
+
+    /**
+     * Get all mailing addresses that have invoices
+     *
+     * @param PDO   $dbh     Database Connection
+     * @param array $members Array of member ids
+     *
+     * @return string
+     */
+    protected function getMemberAddresses(PDO $dbh, $members = array())
+    {
+        if (empty($members)) {
+            return false;
+        }
+        $memberIds = array();
+        $addresses = array();
+        $statement = new Toolkit_Members_Billing_Statement();
+        foreach ($members as $row => &$member) {
+            $balanceDue = (float)$statement->getBalanceDue(
+                $dbh,
+                $member['member_id'],
+                $member['account_id']
+            );
+            if ($_REQUEST['balance_due'] && $balanceDue <= 0.00) {
+                unset($members[$row]);
+            } else {
+                $memberIds[] = $member['member_id'];
+            }
+        }
+        if (empty($memberIds)) {
+            return false;
+        }
+        $states = $this->getStates($dbh);
+        $cities = $this->getCities($dbh);
+        try {
+            $sql = "
+              SELECT member_name,mailing_address,mailing_city_id,
+                     mailing_state_id,mailing_zip,street,city_id,
+                     state_id,zip,
+                     billing_contact as contact
+                FROM member
+               WHERE member_id IN (".implode(",", $memberIds).")
+                -- AND member_id IN (SELECT DISTINCT member_id FROM billing)
+            ORDER BY member_name";
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                if (strlen($row['member_name']) > 40) {
+                    $splitPos = strpos($row['member_name'], ' ', 40);
+                    if ($splitPos) {
+                        $text1    = substr($row['member_name'], 0, $splitPos);
+                        ++$splitPos;
+                        $text2    = substr(
+                            $row['member_name'],
+                            $splitPos,
+                            strlen($row['member_name'])
+                        );
+                    } else {
+                        $text1 = $row['member_name'];
+                    }
+                    
+                } else {
+                    $text1 = $row['member_name'];
+                    $text2 = null;
+                }
+                $contact = $row['contact'];
+                if ($row['mailing_address']) {
+                    $address = $row['mailing_address'];
+                    $city    = $cities[$row['mailing_city_id']];
+                    $state   = $states[$row['mailing_state_id']];
+                    $zip     = $row['mailing_zip'];
+                } else {
+                    $address = $row['street'];
+                    $city    = $cities[$row['city_id']];
+                    $state   = $states[$row['state_id']];
+                    $zip     = $row['zip'];
+                }
+                $addresses[] = array(
+                    'name'    => iconv('UTF-8', 'ISO-8859-1//IGNORE', $row['member_name']),
+                    'name1'   => iconv('UTF-8', 'ISO-8859-1//IGNORE', $text1),
+                    'name2'   => iconv('UTF-8', 'ISO-8859-1//IGNORE', $text2),
+                    'contact' => iconv('UTF-8', 'ISO-8859-1//IGNORE', $contact),
+                    'address' => iconv('UTF-8', 'ISO-8859-1//IGNORE', $address),
+                    'city'    => iconv('UTF-8', 'ISO-8859-1//IGNORE', $city),
+                    'state'   => iconv('UTF-8', 'ISO-8859-1//IGNORE', $state),
+                    'zip'     => iconv('UTF-8', 'ISO-8859-1//IGNORE', $zip)
+                );
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $addresses;
+    }
+
+    /**
+     * creates a pdf of labels for members
+     *
+     * @param array $addresses Address array of member data
+     *
+     * @return mixed
+     */
+    protected function glmPdfInvoice($addresses = array())
+    {
+        if (empty($addresses)) {
+            return false;
+        }
+        // setup the forms
+        $i = 1;
+        $j = 0;
+
+        for ($y = 750; $y >= 5; $y = $y - 75) {
+            for ($x = 30; $x <= 340; $x = $x + 300) {
+                $invoiceForms[$i] = array(
+                    'x'  => $x,
+                    'y'  => $y,
+                    'xs' => 300,
+                    'ys' => 75
+                );
+                ++$i;
+            }
+            ++$j;
+        }
+        // Initialize Forms
+        $r = $this->glmpdfSetForms(
+            count($invoiceForms),
+            $invoiceForms,
+            $this->glmpdfStandardPage[PAPER_SIZE]['x'],
+            $this->glmpdfStandardPage[PAPER_SIZE]['y']
+        );
+        if (!$r) {
+            echo "ERROR: Unable to set PDF forms layout.";
+            exit;
+        }
+
+        // Start PDF Generation - (Creator, Author, Title)
+        $this->glmpdfStart(
+            "GLM PDF",
+            "Gaslight Media",
+            "Standard Invoice with Payment Form"
+        );
+        
+        foreach ($addresses as $add) {
+            // Create new form
+            $this->glmpdfNextForm();
+            $this->glmpdfSetFont("Helvetica-Bold", 12.0);
+            $this->glmpdfPlaceText(
+                $add['name1'],
+                0,
+                0,
+                "left",
+                'black'
+            );
+            if ($add['name2']) {
+                $this->glmpdfPlaceText(
+                    $add['name2'],
+                    0,
+                    $this->glmpdfCurrentY,
+                    "left",
+                    'black'
+                );
+            }
+            $this->glmpdfSetFont("Helvetica", 12.0);
+            $this->glmpdfPlaceText(
+                $add['contact'],
+                0,
+                $this->glmpdfCurrentY,
+                "left",
+                'black'
+            );
+            
+            $this->glmpdfPlaceText(
+                $add['address'],
+                0,
+                $this->glmpdfCurrentY,
+                "left",
+                'black'
+            );
+            $city_state
+                = $add['city'] . ', '
+                . $add['state'] . ' '
+                . $add['zip'];
+            $this->glmpdfPlaceText(
+                $city_state,
+                0,
+                $this->glmpdfCurrentY,
+                "left",
+                'black'
+            );
+        }
+
+        $buf = $this->glmpdfEnd();
+        $len = strlen($buf);
+        if (ini_get('zlib.output_compression')) {
+            ini_set('zlib.output_compression', 'Off');
+        }
+        header("Content-type: application/force-download\n");
+        header("Content-type: application/pdf");
+        header("Content-Length: $len");
+        /* Correction for the stupid MSIE thing */
+        if (strstr(getenv('HTTP_USER_AGENT'), 'MSIE')) {
+            header("Content-Disposition: inline; filename=\"MemberLabel.pdf\"");
+        } else {
+            header("Content-Disposition: attachment; filename=\"MemberLabel.pdf\"");
+        }
+        echo $buf; 
+    }
+
+    /**
+     * gather all members with a usmail set that have invoices
+     * and call the pdf creation function
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return void
+     */
+    public function printMailingLabels(PDO $dbh)
+    {
+        // get all member id's that have billing setup
+        $inv     = new Toolkit_Members_Billing_Invoices();
+        $members = $inv->getMembersWithAccounts(
+            $dbh,
+            array(
+                'usmail_invoice' => 1,
+                'email_invoice'  => 0,
+                'fax_invoice'    => 1
+            )
+        );
+        $addresses = $this->getMemberAddresses($dbh, $members);
+        $this->glmPdfInvoice($addresses);
+    }
+}
diff --git a/Toolkit/Members/Billing/MemberAccount.php b/Toolkit/Members/Billing/MemberAccount.php
new file mode 100644 (file)
index 0000000..a2e0d4e
--- /dev/null
@@ -0,0 +1,155 @@
+<?php
+/**
+ * Billing.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_Billing
+ * 
+ * Member Billing Module Billing table class
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_MemberAccount
+    extends Toolkit_Table
+{
+    /**
+     * Description of $tableName
+     * @var string
+     * @access public
+     */
+    public $tableName = 'member_account';
+    
+    /**
+     * Description of $id
+     * @var int
+     * @access protected
+     */
+    protected $id;
+    
+    /**
+     * Description of $member_id
+     * @var int
+     * @access protected
+     */
+    protected $member_id;
+    
+    /**
+     * Description of $payment_type
+     * @var int
+     * @access protected
+     */
+    protected $payment_type;
+    
+    /**
+     * Description of $email_invoice
+     * @var boolean
+     * @access protected
+     */
+    protected $email_invoice;
+    
+    /**
+     * Description of $usmail_invoice
+     * @var boolean
+     * @access protected
+     */
+    protected $usmail_invoice;
+    
+    /**
+     * Description of $fax_invoice
+     * @var boolean
+     * @access protected
+     */
+    protected $fax_invoice;
+
+    /**
+     * Make sure this is a boolean value
+     *
+     * @param boolean $email_invoice Emailed to the member
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     */
+    public function setEmailInvoice($email_invoice)
+    {
+        $this->email_invoice = ($email_invoice);
+        return $this;
+    }
+
+    /**
+     * Make sure this is a boolean value
+     *
+     * @param boolean $usmail_invoice Emailed to the member
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     */
+    public function setUsmailInvoice($usmail_invoice)
+    {
+        $this->usmail_invoice = ($usmail_invoice);
+        return $this;
+    }
+
+    /**
+     * Make sure this is a boolean value
+     *
+     * @param boolean $fax_invoice Emailed to the member
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     */
+    public function setFaxInvoice($fax_invoice)
+    {
+        $this->fax_invoice = ($fax_invoice);
+        return $this;
+    }
+    
+    /**
+     * Check to see if given an id that it is numeric
+     *
+     * @param int $type payment_type field
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException 
+     */
+    public function setPaymentType($type)
+    {
+        if ( !is_numeric($type)) {
+            throw new InvalidArgumentException('payment_type must be numeric');
+        }
+        $this->payment_type = $type;
+        return $this;
+    }
+
+    /**
+     * Check to see if given an id that it is numeric
+     *
+     * @param int $id member_id field
+     *
+     * @return Toolkit_Members_Billing_Billing
+     * @access public
+     * @throws InvalidArgumentException 
+     */
+    public function setMemberId($id)
+    {
+        if (!is_numeric($id)) {
+            throw new InvalidArgumentException('member_id must be numeric');
+        }
+        $this->member_id = $id;
+        return $this;
+    }
+}
+
diff --git a/Toolkit/Members/Billing/MemberLists.php b/Toolkit/Members/Billing/MemberLists.php
new file mode 100644 (file)
index 0000000..e7c1f65
--- /dev/null
@@ -0,0 +1,468 @@
+<?php
+/**
+ * MemberLists.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_MemberLists
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_MemberLists
+{
+    /**
+     * Database handler
+     * @var PDO
+     * @access protected
+     */
+    protected $dbh;
+    
+    /**
+     * Money Format
+     * @var string
+     * @access protected
+     */
+    protected $moneyFormat = '%01.2f';
+
+    /**
+     * Class constructor
+     * 
+     * @param PDO $pdo Database handler
+     * 
+     * @access public
+     */
+    public function __construct(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+    
+    /**
+     * Pull all accounts that have a balance
+     * 
+     * @return string
+     * @access public
+     */
+    public function getOpenAccounts()
+    {
+        $out = '<p>Open Accounts</p>';
+        $mc      = new Toolkit_Members_Billing_Invoices();
+        $members = $mc->getMembersWithAccounts($this->dbh);
+        $statement = new Toolkit_Members_Billing_Statement();
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                $balanceDue = (float)$statement->getBalanceDue(
+                    $this->dbh,
+                    $member['member_id'],
+                    $member['account_id']
+                );
+                if ($balanceDue <= 0.00) {
+                    unset($members[$row]);
+                } else {
+                    $member['balanceDue'] = sprintf(
+                        $this->moneyFormat,
+                        (float)$balanceDue
+                    );
+                }
+            }
+            $out .= $this->displayMemberList($members);
+        }
+        return $out;
+    }
+    
+    /**
+     * Pull all accounts past due sorted by past date ranges
+     * 
+     * Using an array to sort them out by how far past the due date is
+     * probely won't have but one table to output as they may all have same 
+     * over due date range since we're using October 1st of each year as due date
+     * 
+     * @return string
+     * @access public
+     */
+    public function getAccountsByAge()
+    {
+        $out       = '';
+        $tableByAge = array(
+            0 => array('title' => 'past due'),
+            1 => array('title' => 'over 30 days'),
+            2 => array('title' => 'over 60 days'),
+            3 => array('title' => 'over 90 days'),
+            4 => array('title' => 'over 120 days')
+        );
+        $mc        = new Toolkit_Members_Billing_Invoices();
+        $members   = $mc->getMembersWithAccounts($this->dbh);
+        $statement = new Toolkit_Members_Billing_Statement();
+        
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                
+                $balanceDue = (float)$statement->getBalanceDue(
+                    $this->dbh,
+                    $member['member_id'],
+                    $member['account_id']
+                );
+                if ($balanceDue <= 0.00) {
+                    unset($members[$row]);
+                } else {
+                    $member['balanceDue'] = sprintf(
+                        $this->moneyFormat,
+                        (float)$balanceDue
+                    );
+                    // get original invoice
+                    $originalInvoice = $statement->getOriginalInvoice(
+                        $this->dbh,
+                        $member['member_id'],
+                        $member['account_id']
+                    );
+                    // get original invoice date
+                    $originalInvoiceDate = $originalInvoice->getTransaction_date();
+                    // calulate time span 
+                    list($month, $day, $year) = explode("/", $originalInvoiceDate);
+                    // the due date is always Oct 1st of the said year
+                    $dueDate     = new Date(mktime(0, 0, 1, 10, 1, $year));
+                    $currentDate = new Date();
+                    $span        = new Date_Span();
+                    $span->setFromDateDiff($dueDate, $currentDate);
+                    $daysPastDue = (int)$span->toDays();
+                    $format = '<p>
+                        Member Name: %s<br>
+                        Due Date: %s<br>
+                        Current Date: %s<br>
+                        Days Past Due: %s
+                        </p>';
+                    $testDates = Date::compare($currentDate, $dueDate);
+                    if ($testDates >= 0) {
+                        if ($daysPastDue <= 30) {
+                            $tableByAge[0]['data'][] = $member;
+                        } else if ($daysPastDue >= 30 && $daysPastDue < 60) {
+                            $tableByAge[1]['data'][] = $member;
+                        } else if ($daysPastDue >= 60 && $daysPastDue < 90) {
+                            $tableByAge[2]['data'][] = $member;
+                        } else if ($daysPastDue >= 90 && $daysPastDue < 120) {
+                            $tableByAge[3]['data'][] = $member;
+                        } else if ($daysPastDue >= 120) {
+                            $tableByAge[4]['data'][] = $member;
+                        }
+                    }
+                }
+            }
+        }
+        foreach ($tableByAge as $tableNumber => $tArray) {
+            if (is_array($tArray['data']) && !empty($tArray['data'])) {
+                $out .= '<p><b>'.$tArray['title'].'</b></p>';
+                $out .= $this->displayMemberList($tArray['data']);
+            }
+        }
+        return $out;
+    }
+    
+    /**
+     * Description of getClosedAccounts()
+     * 
+     * @return string
+     * @access public 
+     */
+    public function getClosedAccounts()
+    {
+        $out = '<p>Closed Accounts</p>';
+        $mc      = new Toolkit_Members_Billing_Invoices();
+        $members = $mc->getMembersWithAccounts($this->dbh);
+        $statement = new Toolkit_Members_Billing_Statement();
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                $balanceDue = (float)$statement->getBalanceDue(
+                    $this->dbh,
+                    $member['member_id'],
+                    $member['account_id']
+                );
+                if ($balanceDue <= 0.00) {
+                    $member['balanceDue'] = sprintf(
+                        $this->moneyFormat,
+                        (float)$balanceDue
+                    );
+                } else {
+                    unset($members[$row]);
+                }
+            }
+            $out .= $this->displayMemberList($members);
+        }
+        return $out;
+    }
+    
+    /**
+     * Description for getAllAccounts()
+     * 
+     * @return string
+     * @access public
+     */
+    public function getAllAccounts()
+    {
+        $out = '<p>All Accounts</p>';
+        $mc      = new Toolkit_Members_Billing_Invoices();
+        $members = $mc->getMembersWithAccounts($this->dbh);
+        $statement = new Toolkit_Members_Billing_Statement();
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                $balanceDue = (float)$statement->getBalanceDue(
+                    $this->dbh,
+                    $member['member_id'],
+                    $member['account_id']
+                );
+                if ($balanceDue <= 0.00) {
+                    $member['balanceDue'] = sprintf(
+                        $this->moneyFormat,
+                        (float)$balanceDue
+                    );
+                } else {
+                    $member['balanceDue'] = 'N/A';
+                }
+            }
+            $out .= $this->displayMemberList($members, 7);
+        }
+        return $out;
+    }
+    
+    /**
+     * Description for getAccountsNeedingData
+     * 
+     * @return string
+     * @access publics
+     */
+    public function getAccountsNeedingData()
+    {
+        $out = '<p>Accounts Needing Data</p>';
+        $mc      = new Toolkit_Members_Billing_Invoices();
+        $members = $mc->getMembersWithOutAccounts($this->dbh);
+        $statement = new Toolkit_Members_Billing_Statement();
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                $member['balanceDue'] = 'N/A';
+                
+            }
+            $out .= $this->displayMemberList($members, 7);
+        }
+        return $out;
+    }
+    
+    /** 
+     * Description for getPrintableInvoices()
+     * 
+     * @return string
+     * @access public 
+     */
+    public function getPrintableInvoices()
+    {
+        $out     = '<p>Printable Invoices</p>';
+        $inv     = new Toolkit_Members_Billing_Invoices();
+        $members = $inv->getMembersWithAccounts(
+            $this->dbh,
+            array(
+                'usmail_invoice' => 1,
+                'email_invoice'  => 0,
+                'fax_invoice'    => 1
+            ),
+            $_POST
+        );
+        $statement = new Toolkit_Members_Billing_Statement();
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                $balanceDue = (float)$statement->getBalanceDue(
+                    $this->dbh,
+                    $member['member_id'],
+                    $member['account_id']
+                );
+                if ($balanceDue <= 0.00) {
+                    unset($members[$row]);
+                } else {
+                    $member['balanceDue'] = sprintf(
+                        $this->moneyFormat,
+                        (float)$balanceDue
+                    );
+                }
+            }
+            $out = $this->displayMemberList($members);
+        }
+        return $out;
+    }
+    
+    /**
+     * Description for getEmailableInvoices()
+     * 
+     * @return string
+     * @access public 
+     */
+    public function getEmailableInvoices()
+    {
+        $out     = '<p>Emails Invoices</p>';
+        $inv     = new Toolkit_Members_Billing_Invoices();
+        $members = $inv->getMembersWithAccounts(
+            $this->dbh,
+            array(
+                'usmail_invoice' => 0,
+                'email_invoice'  => 1,
+                'fax_invoice'    => 0
+            )
+        );
+        $statement = new Toolkit_Members_Billing_Statement();
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                $balanceDue = (float)$statement->getBalanceDue(
+                    $this->dbh,
+                    $member['member_id'],
+                    $member['account_id']
+                );
+                if ($balanceDue <= 0.00) {
+                    unset($members[$row]);
+                } else {
+                    $member['balanceDue'] = sprintf(
+                        $this->moneyFormat,
+                        (float)$balanceDue
+                    );
+                }
+            }
+            $out = $this->displayMemberList($members);
+        }
+        return $out;
+    }
+    
+    /**
+     * Description for getMailableInvoices()
+     * 
+     * @return string
+     * @access public
+     */
+    public function getMailableInvoices()
+    {
+        $out     = '<p>Labels for Invoices</p>';
+        $inv     = new Toolkit_Members_Billing_Invoices();
+        $members = $inv->getMembersWithAccounts(
+            $this->dbh,
+            array(
+                'usmail_invoice' => 1,
+                'email_invoice'  => 0,
+                'fax_invoice'    => 1
+            )
+        );
+        $statement = new Toolkit_Members_Billing_Statement();
+        if ($members && is_array($members)) {
+            foreach ($members as $row => &$member) {
+                $balanceDue = (float)$statement->getBalanceDue(
+                    $this->dbh,
+                    $member['member_id'],
+                    $member['account_id']
+                );
+                if ($_REQUEST['balance_due'] && $balanceDue <= 0.00) {
+                    unset($members[$row]);
+                } else {
+                    $member['balanceDue'] = sprintf(
+                        $this->moneyFormat,
+                        (float)$balanceDue
+                    );
+                }
+            }
+            $out = $this->displayMemberList($members);
+        }
+        return $out;
+    }
+    
+    /**
+     * Description for getNeededInvoices()
+     * 
+     * @return string
+     * @access public 
+     */
+    public function getNeededInvoices()
+    {
+        $out = '<p>No Records Matching</p>';
+        $mc = new Toolkit_Members_Billing_Invoices();
+        $members = $mc->listCreateInvoices($this->dbh);
+        
+        if (!empty($members)) {
+            foreach ($members as $row => &$member) {
+                if (in_array($member['payment_type'], array(1))) {
+                    unset($members[$row]);
+                }
+            }
+            $out = $this->displayMemberList($members);
+        }
+        return $out;
+    }
+
+    /**
+     * Description for displayMemberList
+     * 
+     * @param array  $members Members array
+     * @param string $tab     Description for $tab
+     * 
+     * @return boolean|string
+     * @access protected
+     */
+    protected function displayMemberList($members, $tab = 'invoices')
+    {
+        if (is_array($members) && !empty($members)) {
+            $paymentTypes = $this->getPaymentTypes();
+            $counter = 1;
+            foreach ($members as $row => &$member) {
+                $member['classStyle']
+                    = ($counter % 2)
+                    ? 'even'
+                    : 'odd';
+                ++$counter;
+                $member['member_url']
+                    = BASE_URL . 'admin/members.php?rt=Members&ac=editMember&id='
+                    . $member['member_id'] . '&tab=' . $tab;
+                $member['payment_type']
+                    = $paymentTypes[$member['payment_type']];
+            }
+            $tplOptions = $GLOBALS['flexyOptions'];
+            $tplOptions['templateDir']
+                = BASE . 'Toolkit/Members/Billing/templates';
+            $tplOptions['compileDir']
+                = BASE . 'Toolkit/Members/Billing/templates/compiled';
+            $tpl = new HTML_Template_Flexy($tplOptions);
+            $page = new stdClass();
+            $page->members = $members;
+            $tpl->compile('memberList.html');
+
+            return $tpl->bufferedOutputObject($page);
+        } else {
+            return false;
+        }
+    }
+    
+    /**
+     * Description of getPaymentTypes
+     * 
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentTypes()
+    {
+        $types = array();
+        $sql = "
+          SELECT id, name
+            FROM payment_types
+        ORDER BY id";
+        try {
+            $stmt = $this->dbh->query($sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $types[$row['id']] = $row['name'];
+            }
+            return $types;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/Members/Billing/PaymentForm.php b/Toolkit/Members/Billing/PaymentForm.php
new file mode 100644 (file)
index 0000000..3b1a30d
--- /dev/null
@@ -0,0 +1,548 @@
+<?php
+
+/**
+ * Controls Amenity definitions for the member db
+ * 
+ * PHP version 5
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handles creating / editing amenities that the members will use
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2011 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Billing_PaymentForm
+    extends Toolkit_Members_Billing_Auxiliary
+{
+    /**
+     * template for edit form
+     *
+     * @var    string   
+     * @access protected
+     */
+    protected $formTemplate = 'paymentForm.html';
+
+    /**
+     * Class constructor
+     *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                              submitted by adding a special hidden field
+     * 
+     * @access public
+     */
+    public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+        
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $this->config = $root;
+    }
+    
+    /**
+     * Description for addAdjustment
+     * 
+     * @param array $values Values array
+     *
+     * @return void
+     * @access protected
+     */
+    protected function addAdjustment($values)
+    {
+        $statement = new Toolkit_Members_Billing_Statement();
+        $balanceDue = (float)$statement->getBalanceDue(
+            $this->dbh,
+            $values['member_id'],
+            $values['account_id']
+        );
+        $balance = (float)($balanceDue + (float)$values['amount']);
+        $paid
+            = ($balance == (float)'0.00')
+            ? true
+            : false;
+        // need to get the original invoice id
+        $originalInvoice = $statement->getOriginalInvoice(
+            $this->dbh,
+            $values['member_id'],
+            $values['account_id']
+        );
+        $invoiceId = $originalInvoice->getInvoice_id();
+        if ($values['amount']) {
+            $invoice = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_Billing',
+                array(
+                    'member_name'      => $values['member_name'],
+                    'invoice_id'       => $invoiceId,
+                    'member_id'        => $values['member_id'],
+                    'transaction_date' => date('m/d/Y'),
+                    'transaction_time' => date('m/d/Y H:i:s'),
+                    'account_number'   => $values['account_number'],
+                    'account_id'       => $values['account_id'],
+                    'billing_type'     => 3,
+                    'emailed'          => 0,
+                    'printed'          => 0,
+                    'amount'           => (float)$values['amount'],
+                    'balance'          => $balance,
+                    'paid'             => $paid,
+                    'payment_method'   => $values['payment_method'],
+                    'payment_data'     => $values['payment_data']
+                )
+            )->save($this->dbh);
+        }
+    }
+    
+    /**
+     * Description for addPayment()
+     * 
+     * @param array $values Values Array
+     * 
+     * @return void
+     * @access protected 
+     */
+    protected function addPayment($values)
+    {
+        //var_dump($values);exit;
+        $statement = new Toolkit_Members_Billing_Statement();
+        $balanceDue = (float)$statement->getBalanceDue(
+            $this->dbh,
+            $values['member_id'],
+            $values['account_id']
+        );
+        //var_dump($balanceDue);exit;
+        if ($values['amount']) {
+            $balanceDue = (float)($balanceDue - (float)$values['amount']);
+            $paid
+                = ($balanceDue == (float)'0.00')
+                ? true
+                : false;
+            // need to get the original invoice id
+            $originalInvoice = $statement->getOriginalInvoice(
+                $this->dbh,
+                $values['member_id'],
+                $values['account_id']
+            );
+            $invoiceId = $originalInvoice->getInvoice_id();
+            if ($paid) {
+                $originalInvoice
+                    ->setPaid(true)
+                    ->save($this->dbh);
+                
+            }
+            $invoice = Toolkit_Members_Billing_Factory::createDBObjectByValues(
+                'Toolkit_Members_Billing_Billing',
+                array(
+                    'member_name'      => $values['member_name'],
+                    'invoice_id'       => $invoiceId,
+                    'member_id'        => $values['member_id'],
+                    'transaction_date' => date('m/d/Y'),
+                    'transaction_time' => date('m/d/Y H:i:s'),
+                    'account_number'   => $values['account_number'],
+                    'account_id'       => $values['account_id'],
+                    'billing_type'     => 2,
+                    'emailed'          => 0,
+                    'printed'          => 0,
+                    'amount'           => (float)$values['amount'],
+                    'balance'          => $balanceDue,
+                    'paid'             => $paid,
+                    'payment_method'   => $values['payment_method'],
+                    'payment_data'     => $values['payment_data']
+                )
+            )->save($this->dbh);
+        }
+    }
+
+    /**
+     * Description for checkForAccountNumber()
+     * 
+     * @param string $accountNumber Account number
+     * 
+     * @return boolean
+     * @access public
+     */
+    public function checkForAccountNumber($accountNumber)
+    {
+        try {
+            $sql = "
+            SELECT count(member_id) as count
+              FROM member
+             WHERE account_number = :account_number";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':account_number',
+                $accountNumber,
+                PDO::PARAM_STR
+            );
+            $stmt->execute();
+            $valid = $stmt->fetchColumn();
+            //var_dump($accountNumber);
+            //var_dump($valid);
+            //var_dump((bool)$valid);exit;
+            return (bool) $valid;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    
+    /**
+     * Form element definitions
+     * 
+     * @return void     
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e = array();
+        $paymentTypes   = $this->getPaymentTypes();
+        $paymentMethods = $this->getPaymentMethods();
+        unset($paymentMethods[0]);
+        $paymentMethods['5'] = 'Adjustment';
+        //    All Grouped Elements are created here.
+
+        //    All Elements are created here.
+        //    This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'PaymentTypeInfoHdr',
+            'display' => 'Make Payment'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'account_number',
+            'display' => 'Account Number'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'amount',
+            'display' => 'Amount'
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => true,
+            'name'    => 'payment_type',
+            'display' => 'Payment Type',
+            'opts'    => array('' => '-- Select --') + $paymentTypes
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => true,
+            'name'    => 'payment_method',
+            'display' => 'Payment Method',
+            'opts'    => array('' => '-- Select --') + $paymentMethods
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'payment_data',
+            'display' => 'Payment Details',
+            'opts'    => array('class' => 'text')
+        );
+
+
+        $this->setupElements($e);
+    }
+
+    /**
+     * Descriptionfor configureFilters()
+     * 
+     * @return void
+     * @access public 
+     */
+    public function configureFilters()
+       {
+               $f = array();
+               $f[] = array(
+                       'element' => '__ALL__',
+                       'filter' => 'trim'
+               );
+
+               $this->setupFilters($f);
+       }
+    
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    /**
+     * Form rule definitions
+     * 
+     * @return void     
+     * @access public
+     */
+    public function configureRules()
+    {
+        $r = array();
+
+        $r[] = array(
+            'element' => 'amount',
+            'message' => 'ERROR: Invalid amount!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+        $r[] = array(
+            'element'    => 'account_number',
+            'message'    => 'ERROR: No Member with that Account Number',
+            'type'       => 'callback',
+            'format'     => array(&$this, 'checkForAccountNumber'),
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+
+        $this->setupRules($r);
+    }
+    
+    /**
+     * Description for getMemberDataByAccountNumber()
+     * 
+     * @param array $values Values array
+     * 
+     * @return mixed 
+     * @access protected
+     */
+    protected function getMemberDataByAccountNumber($values)
+    {
+        try {
+            $sql = "
+            SELECT m.member_id,m.member_name,m.account_number,
+                   ma.id as account_id,ma.payment_type
+              FROM member m, member_account ma
+             WHERE m.active = 't'
+               AND m.member_id = ma.member_id
+               AND m.account_number = :account_number
+               AND ma.payment_type = :payment_type";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':account_number',
+                $values['account_number'],
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':payment_type',
+                $values['payment_type'],
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Description for getMemberDataByInvoiceId()
+     * 
+     * @param array $values Values array
+     * 
+     * @return boolean|array
+     * @access protected
+     */
+    protected function getMemberDataByInvoiceId($values)
+    {
+        try {
+            // first need to get member_id from the billing table
+            $sql = "
+            SELECT member_id,account_id
+              FROM billing
+             WHERE billing_type = 1
+               AND invoice_id = :invoice_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':invoice_id',
+                $values['invoice_id'],
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            $member     = $stmt->fetch(PDO::FETCH_ASSOC);
+            $member_id  = $member['member_id'];
+            $account_id = $member['account_id'];
+            if (!$member_id) {
+                return false;
+            } else {
+                $sql = "
+                SELECT m.member_id,m.member_name,m.account_number,
+                       ma.id as account_id,ma.payment_type
+                  FROM member m, member_account ma
+                 WHERE m.active = 't'
+                   AND m.member_id = ma.member_id
+                   AND m.member_id = :member_id";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(
+                    ':member_id',
+                    $member_id,
+                    PDO::PARAM_INT
+                );
+                $stmt->execute();
+                $memberData = $stmt->fetchAll(PDO::FETCH_ASSOC);
+                if (is_array($memberData) && !empty($memberData)) {
+                    foreach ($memberData as $memberD) {
+                        if ($memberD['account_id'] == $account_id) {
+                            return $memberD;
+                        }
+                    }
+                }
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    
+    /**
+     * Description of getPaymentMethods()
+     * 
+     * @return array 
+     * @access protected
+     */
+    protected function getPaymentMethods()
+    {
+        $types = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'paymentMethod')
+            ->getContent();
+        unset($types[2]);
+        return $types;
+    }
+    
+    /**
+     * Description of getPaymentTypes()
+     * 
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentTypes()
+    {
+        $paymentTypes = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM payment_types
+               WHERE dynamic_amount = true
+                  OR amount > 0.00
+            ORDER BY name";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $paymentTypes[$row['id']] = $row['name'];
+            }
+            return $paymentTypes;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Description of processData()
+     * 
+     * @param array $values Values array
+     * 
+     * @return boolean 
+     * @access protected
+     */
+    protected function processData($values)
+    {
+        $memberData = $this->getMemberDataByAccountNumber($values);
+        //var_dump($memberData);
+        //exit;
+        if (!$memberData) {
+            return false;
+        }
+        if (   $memberData['account_id']
+            && $values['amount']
+            && $values['payment_method']
+        ) {
+            if ($values['payment_method'] == 5) {
+                // add adjustment
+                $adjustment = array(
+                    'member_id'      => $memberData['member_id'],
+                    'account_id'     => $memberData['account_id'],
+                    'member_name'    => $memberData['member_name'],
+                    'account_number' => $memberData['account_number'],
+                    'amount'         => $values['amount'],
+                    'payment_method' => null,
+                    'payment_data'   => $values['payment_data']
+                );
+                $this->addAdjustment($adjustment);
+            } else {
+                $payment = array(
+                    'member_id'      => $memberData['member_id'],
+                    'account_id'     => $memberData['account_id'],
+                    'member_name'    => $memberData['member_name'],
+                    'account_number' => $memberData['account_number'],
+                    'amount'         => $values['amount'],
+                    'payment_method' => $values['payment_method'],
+                    'payment_data'   => $values['payment_data']
+                );
+                $this->addPayment($payment);
+            }
+        }
+        return true;
+    }
+    
+    /**
+     * Renders the form for viewing
+     *
+     * This function validates the form if needed, and if it successfully
+     * validates attempts to insert or update the data record.
+     * If it is unsuccessful, it will return an error to the user
+     * informing them of what went wrong.
+     *
+     * @return string The compiled and filled form template.
+     * @access public
+     */
+    public function toHtml()
+    {
+        $listPage = BASE_URL . 'admin/members.php?rt=Payment&formSubmitGood=1';
+        return parent::toHtml($listPage);
+    }
+}
diff --git a/Toolkit/Members/Billing/PaymentTypes.php b/Toolkit/Members/Billing/PaymentTypes.php
new file mode 100644 (file)
index 0000000..938f642
--- /dev/null
@@ -0,0 +1,115 @@
+<?php
+/**
+ * PaymentTypes.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_PaymentTypes
+ *
+ * Member Billing Module Payment Type table class
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_PaymentTypes
+    extends Toolkit_Table
+{
+    /**
+     * Description of $tableName
+     * @var string
+     * @access public
+     */
+    public $tableName = 'payment_types';
+    
+    /**
+     * Description of $id
+     * @var int
+     * @access protected
+     */
+    protected $id;
+    
+    /**
+     * Description of $name
+     * @var string
+     * @access protected
+     */
+    protected $name;
+    
+    /**
+     * Description of $qcode
+     * @var int
+     * @access protected
+     */
+    protected $qcode;
+    
+    /**
+     * Description of $category
+     * @var text
+     * @access protected
+     */
+    protected $category;
+    
+    /**
+     * Description of $amount
+     * @var int
+     * @access protected
+     */
+    protected $amount;
+    
+    /**
+     * Description of $notes
+     * @var string
+     * @access protected
+     */
+    protected $notes;
+    
+    /**
+     * Description of $dynamic_amount
+     * @var boolean
+     * @access protected
+     */
+    protected $dynamic_amount;
+
+    /**
+     * Description of setDynamicAmount
+     * 
+     * @param boolean $dynamic_amount Dynamic Amount
+     * 
+     * @return \Toolkit_Members_Billing_PaymentTypes 
+     * @access public
+     */
+    public function setDynamicAmount($dynamic_amount)
+    {
+        $this->dynamic_amount = ($dynamic_amount);
+        return $this;
+    }
+
+    /**
+     * Description of setQcode
+     * 
+     * @param int $id Qcode ID
+     * 
+     * @return \Toolkit_Members_Billing_PaymentTypes
+     * @throws InvalidArgumentException 
+     * @access public
+     */
+    public function setQcode($id)
+    {
+        if (!is_numeric($id)) {
+            throw new InvalidArgumentException('qcode must be numeric');
+        }
+        $this->qcode = $id;
+        return $this;
+    }
+}
diff --git a/Toolkit/Members/Billing/PrintInvoices.php b/Toolkit/Members/Billing/PrintInvoices.php
new file mode 100644 (file)
index 0000000..e38210a
--- /dev/null
@@ -0,0 +1,232 @@
+<?php
+/**
+ * EmailInvoices.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+require_once GLM_APP_BASE . 'pdf/pdf_lib_8/GlmPdf.php';
+/**
+ * Toolkit_Members_Billing_EmailInvoices
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_PrintInvoices
+    extends Toolkit_Members_Billing_InvoiceAbstract
+    implements Toolkit_Members_Billing_IInvoice
+{
+    /**
+     * Subject line for email
+     * 
+     * @var string
+     */
+    protected $subject = 'Member Invoice';
+
+    /**
+     * Billing storage array
+     *
+     * @var array
+     * @access protected
+     */
+    protected $billings = array();
+
+    /**
+     * Template file to use
+     * 
+     * @var string
+     */
+    protected $template = 'sendEmailInvoice.html';
+
+    /**
+     * Base of the billing template directory
+     *  
+     * @var string
+     * @access protected
+     */
+    protected $templateBase = 'Toolkit/Members/Billing/';
+    
+    /**
+     * The directory of the templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $templatesDir = 'templates';
+
+    /**
+     * The directory of the flexy-compiled templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $compiledDir = 'templates/compiled';
+    
+    /**
+     * Flexy Template Options array
+     * 
+     * @var array
+     */
+    protected $flexyOptions = array();
+
+    /**
+     * class Constructor
+     *
+     * @return void
+     */
+    public function  __construct() {
+        $this->flexyOptions = array(
+            'templateDir'  => BASE . "{$this->templateBase}{$this->templatesDir}",
+            'compileDir'   => BASE . "{$this->templateBase}{$this->compiledDir}",
+            'forceCompile' => 1,
+            'debug'        => 0,
+            'locale'       => 'en',
+        );
+    }
+    /**
+     * get all members with the usmail,fax type set and print their invoices
+     *
+     * @todo     generate email from template
+     * @param PDO $dbh Database Connection
+     *
+     * @return void
+     */
+    public function printInvoices(PDO $dbh)
+    {
+        // get all member id's that have billing setup
+        $inv     = new Toolkit_Members_Billing_Invoices();
+        $members = $inv->getMembersWithAccounts(
+            $dbh,
+            array(
+                'usmail_invoice' => 1,
+                'email_invoice'  => 0,
+                'fax_invoice'    => 1
+            )
+        );
+        if (empty($members)) {
+            return false;
+        }
+        $this->billings = $this->getLastInvoices($dbh, $members, 'printed');
+        if (empty($this->billings)) {
+            return false;
+        }
+        try {
+            $pdf = PDF_new();
+            $i   = 1;
+            if (PDF_begin_document($pdf, '', "") == 0) {
+               die("Error: " . PDF_get_errmsg($pdf));
+            }
+
+            foreach ($this->billings as $bill) {
+                if ($bill->getAmount() == 0) {
+                    continue;
+                }
+                if ($bill->getBalance() == 0) {
+                    continue;
+                }
+                $pdfName     = "/pvf/invoice{$i}.pdf";
+                $out        .= '<p>pdfName: '.$pdfName.'</p>';
+                $out        .= '<p>pdf_create_pvf</p>';
+                $invoiceText = $bill->getInvoiceAsPdf($dbh);
+                $pvf         = pdf_create_pvf(
+                    $pdf,
+                    $pdfName,
+                    $invoiceText,
+                    ""
+                );
+                if ($pvf == 0) {
+                    $out .= "<p>Error: " . PDF_get_errmsg($pdf).'</p>';
+                }
+                $out   .= '<p>pdf_open_pdi_document</p>';
+                $srcDoc = pdf_open_pdi_document($pdf,
+                    $pdfName,
+                    ''
+                );
+                if ($srcDoc == 0) {
+                    $out .= "<p>Error: " . PDF_get_errmsg($pdf).'</p>';
+                }
+                $out     .= '<p>pdf_open_pdi_page</p>';
+                $srcPage  = pdf_open_pdi_page($pdf, $srcDoc, 1, '');
+                if ($srcPage == 0) {
+                    $out .= "<p>Error: " . PDF_get_errmsg($pdf).'</p>';
+                }
+                
+                $srcWidth = pdf_get_pdi_value(
+                    $pdf,
+                    'width',
+                    $srcDoc,
+                    $srcPage,
+                    0
+                );
+                $out      .= '<p>pdf_get_pdi_value: width = '.$srcWidth.'</p>';
+                $srcHeight = pdf_get_pdi_value(
+                    $pdf,
+                    'height',
+                    $srcDoc,
+                    $srcPage,
+                    0
+                );
+                $out .= '<p>pdf_get_pdi_value: height = '.$srcHeight.'</p>';
+                $out .= '<p>PDF_begin_page_ext</p>';
+                PDF_begin_page_ext($pdf, $srcWidth, $srcHeight, '');
+                $out .= '<p>pdf_fit_pdi_page</p>';
+                pdf_fit_pdi_page($pdf, $srcPage, 0, 0, '');
+                $out .= '<p>pdf_close_pdi_page</p>';
+                pdf_close_pdi_page($pdf, $srcPage);
+                $out .= '<p>PDF_end_page_ext</p>';
+                PDF_end_page_ext($pdf, '');
+                $out .= '<p>PDF_delete_pvf</p>';
+                PDF_delete_pvf($pdf, $pdfName);
+                // Don't mark sent to member at this time
+                //$this->markSentToMember($dbh, $bill);
+                ++$i;
+            }
+
+            
+        } catch(PDFlibException $e) {
+            Toolkit_Common::handleError($e);
+            exit;
+        }
+        PDF_end_document($pdf, '');
+        $buf = PDF_get_buffer($pdf);
+        PDF_delete($pdf);
+        $len = strlen($buf);
+        header("Content-type: application/force-download\n");
+        header("Content-type: application/pdf");
+        header("Content-Length: $len");
+        /* Correction for the stupid MSIE thing */
+        if (strstr(getenv('HTTP_USER_AGENT'), 'MSIE')) {
+            header("Content-Disposition: inline; filename=\"MemberInvoices.pdf\"");
+        } else {
+            header("Content-Disposition: attachment; filename=\"MemberInvoices.pdf\"");
+        }
+        print $buf;
+        exit;
+    }
+
+    /**
+     * with an existing billing object set the billing feild printed
+     * to true (boolean) and save it
+     *
+     * @param PDO                             $dbh     Database Connection
+     * @param Toolkit_Members_Billing_Billing $billing Billing object
+     *
+     * @return void
+     */
+    public function markSentToMember(
+        PDO $dbh,
+        Toolkit_Members_Billing_Billing $billing
+    ) {
+        $billing
+            ->setPrinted(1) // set to true
+            ->save($dbh); // save the object to database
+    }
+}
diff --git a/Toolkit/Members/Billing/QifExport.php b/Toolkit/Members/Billing/QifExport.php
new file mode 100644 (file)
index 0000000..f59e0c8
--- /dev/null
@@ -0,0 +1,201 @@
+<?php
+
+/**
+ * QifExport.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_QifExport
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_QifExport
+{
+    
+    /**
+     * Description of $fileData
+     * @var array
+     * @access protected 
+     */
+    protected $fileData = array();
+    const HEADERFORMAT = "!Type:Bank\nD%s\nT%s\nP%s\nL[%s]\n^\n";
+    const INVOICEFORMAT = "!D%s\nT%s\nP%s\nL%s\n^\n";
+    const PAYMENTFORMAT = "D%s\nT%s\nP%s\nN%s\nM%s\nL%s\n^\n";
+    const MAINCATEGORY  = 'Member Services:';
+    const INVCATEGORY   = 'Other Inc';
+    
+    /**
+     * Description of $paymentTypes
+     * @var array
+     */
+    protected $paymentTypes = array();
+
+    /**
+     * Class constructor
+     * 
+     * @return void
+     * @access public 
+     */
+    public function __construct()
+    {
+        // nothing yet
+    }
+    
+    /**
+     * Description for setQUery
+     * 
+     * @param PDO   $dbh    Database handler
+     * @param array $params Parameter array
+     * 
+     * @return void
+     * @access public
+     */
+    public function setQuery(PDO $dbh, $params)
+    {
+        
+        //$params[] = "billing_type = 2";
+        
+        $sql = "
+        SELECT id,member_id
+          FROM billing ";
+        if (!empty($params) && is_array($params)) {
+            foreach ($params as $key => &$param) {
+                if (preg_match('/billing_type IN \((.*)\)/i', $param, $matches)) {
+                    $billing_types = explode(",", $matches[1]);
+                    $billing_types[] = 2;
+                    $param = "billing_type IN (" . implode(',', $billing_types) . ")";
+                }
+            }
+            $sql .= " WHERE ".implode(" AND ", $params);
+        }
+        $sql .= " ORDER BY account_number,transaction_date,billing_type";
+        
+        try {
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $billings[$row['member_id']][]
+                    = Toolkit_Members_Billing_Factory::createDbObjectById(
+                        $dbh, 'Toolkit_Members_Billing_Billing', $row['id']
+                    );
+            }
+        } catch(PDOException $e) {
+            var_dump($e);
+            Toolkit_Common::handleError($e);
+        }
+        $this->getPaymentTypes($dbh);
+        $this->createExportFile($dbh, $billings);
+    }
+    
+    /**
+     * Description of createExportFile()
+     * 
+     * @param PDO   $dbh      Database handler
+     * @param array $billings Billings array
+     * 
+     * @return void
+     * @access protected
+     */
+    protected function createExportFile(PDO $dbh, $billings)
+    {
+        $this->fileData[] = "!Type:Bank\n";
+        foreach ($billings as $member_id => $records) {
+            foreach ($records as $record) {
+                $billingType = $record->getBilling_type();
+                switch ($billingType) {
+                case 2 :
+                    $paymentTypeId = $this->getPaymentTypeFromAccountId(
+                        $dbh,
+                        $record->getAccount_id()
+                    );
+                    $paymentType = $this->paymentTypes[$paymentTypeId];
+                    $this->fileData[] = sprintf(
+                        self::PAYMENTFORMAT,
+                        $record->getTransaction_date(), // D
+                        '-' . $record->getAmount(), // T
+                        $record->getMember_name(), // P
+                        preg_replace(
+                            '[0-9]',
+                            '',
+                            $record->getPayment_data()
+                        ), // N
+                        $paymentType->getCategory(), // M
+                        $paymentType->getQcode() // L
+                    );
+                    break;
+                }
+            }
+        }
+        $buf = implode('', $this->fileData);
+        $len = strlen($buf);
+        header("Content-type: application/force-download");
+        header("Content-Length: $len");
+        header("Content-Disposition: inline; filename=testImport.qif");
+        echo $buf;
+    }
+    
+    /**
+     * Description of getPaymentTypeFromAccountId
+     * 
+     * @param PDO $dbh        Database handler
+     * @param int $account_id Account ID
+     * 
+     * @return string
+     * @access protected 
+     */
+    protected function getPaymentTypeFromAccountId(PDO $dbh, $account_id)
+    {
+        try {
+            $sql = "
+            SELECT payment_type
+              FROM member_account
+             WHERE id = :account_id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':account_id', $account_id, PDO::PARAM_INT);
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    
+    /**
+     * Description for getPaymentTypes
+     * 
+     * @param PDO $dbh Database handler
+     * 
+     * @return void
+     * @access protected
+     */
+    protected function getPaymentTypes(PDO $dbh)
+    {
+        try {
+            $sql = "
+               SELECT id
+                 FROM payment_types
+             ORDER BY id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $this->paymentTypes[$row['id']]
+                    = Toolkit_Members_Billing_Factory::createDbObjectById(
+                        $dbh, 'Toolkit_Members_Billing_PaymentTypes', $row['id']
+                    );
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/Members/Billing/RecordNavigation.php b/Toolkit/Members/Billing/RecordNavigation.php
new file mode 100644 (file)
index 0000000..19d4e7a
--- /dev/null
@@ -0,0 +1,86 @@
+<?php
+/**
+ * RecordNavigation.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_RecordNavigation
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_RecordNavigation
+{
+    /**
+     * Description of getNavigationArray()
+     * 
+     * @param string $params Description for $params
+     * @param array  $nav    Description for $nav
+     * 
+     * @return string 
+     * @access public
+     */
+    public function getNavigationArray($params, $nav)
+    {
+        $nav['billingInfo'] = array(
+            'title' => 'Billing Info',
+            'url'   => "/members.php?$params",
+            'desc'  => 'View and edit billing details'
+        );
+        // this should only show if they have account data and member account 
+        // with amounts or dynamic amounts assigned to them
+        $hasPaymentAccounts = $this->hasPaymentAccounts();
+        if ($hasPaymentAccounts) {
+            $nav['invoices'] = array(
+                'title' => 'Payments/Statements',
+                'url'   => "/members.php?$params",
+                'desc'  => 'View and edit Payment details'
+            );
+        }
+        return $nav;
+    }
+    
+    /**
+     * Description for hasPaymentAccounts()
+     * 
+     * @return boolean 
+     * @access protected
+     */
+    protected function hasPaymentAccounts()
+    {
+        $hasPaymentAccount = false;
+        try {
+            $dbh = Toolkit_Database::getInstance();
+            $sql = "
+            SELECT pt.*
+              FROM member_account ma
+                   LEFT OUTER JOIN payment_types pt
+                   ON (pt.id = ma.payment_type)
+             WHERE ma.member_id = :member_id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                if ($row['amount'] > 0 && $row['dynamic_amount'] == false) {
+                    $hasPaymentAccount = true;
+                } else if ($row['dynamic_amount'] == true) {
+                    $hasPaymentAccount = true;
+                }
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $hasPaymentAccount;
+    }
+}
diff --git a/Toolkit/Members/Billing/Report.php b/Toolkit/Members/Billing/Report.php
new file mode 100644 (file)
index 0000000..4fcf065
--- /dev/null
@@ -0,0 +1,390 @@
+<?php
+/**
+ * Report.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_Report
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_Report
+    extends Toolkit_DataGridBuilder
+{
+    /**
+     * Description of $config
+     * @var Config
+     * @access public 
+     */
+    public $config;
+    
+    /**
+     * Description of $sortableAfter
+     * @var integer
+     * @access protected
+     */
+    protected $sortableAfter = 100000;
+    
+    /**
+     * Description of configureColumns()
+     * 
+     * @return void
+     * @access public 
+     */
+    protected function configureColumns()
+    {
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $this->config = $root;
+        
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Transaction Time',
+                'transaction_time',
+                'transaction_time',
+                array(
+                    'nowrap' => 'nowrap',
+                    'width'   => '120'
+                )
+            )
+        );
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Type',
+                'billing_type',
+                'billing_type',
+                array(
+                    'nowrap' => 'nowrap',
+                    'width'   => '70'
+                ),
+                null,
+                array($this, 'renderBillingType')
+            )
+        );
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Member Name',
+                'member_name',
+                'member_name',
+                null,
+                null,
+                array($this, 'renderMemberName')
+            )
+        );
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Description',
+                'member_id',
+                null,
+                null,
+                null,
+                array($this, 'renderDescription')
+            )
+        ); 
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Amount',
+                'amount',
+                null,
+                array(
+                    'nowrap' => 'nowrap',
+                    'width'   => '50'
+                ),
+                null,
+                array($this, 'renderAmount')
+            )
+        );
+    }
+
+    /**
+     * Description of exportFile
+     * 
+     * @param PDO   $dbh    Database Handler
+     * @param array $params Parameter array
+     * 
+     * @return void
+     * @access public
+     */
+    public function exportFile(PDO $dbh, $params)
+    {
+        $QifExport = new Toolkit_Members_Billing_QifExport();
+        $QifExport->setQuery($dbh, $params);
+    }
+    
+    /**
+     * Description of getGrandTotals()
+     * 
+     * @param PDO   $dbh    Database handler
+     * @param array $params Parameter array
+     * 
+     * @return string 
+     * @access public
+     */
+    public function getGrandTotals(PDO $dbh, $params)
+    {
+        $out = '<table class="dataGrid"><tbody>';
+        $params[] = "billing_type in (1,2)";
+        $sql = "
+        SELECT sum(amount) as sum,billing_type
+          FROM billing";
+        if (!empty($params)) {
+            $sql .= " WHERE " . implode(" AND ", $params);
+        }
+        $sql .= " GROUP BY billing_type";
+        try {
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            $format = '
+            <tr class="odd" align="right">
+              <td>Total %s:</td>
+              <td width="50" align="right">%01.2f</td>
+            </tr>';
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $name
+                    = ($row['billing_type'] == 1)
+                    ? 'Invoices'
+                    : 'Payments';
+                $out .= sprintf(
+                    $format,
+                    $name,
+                    $row['sum']
+                );
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        $out .= '</tbody></table>';
+        return $out;
+    }
+
+    /**
+     * Description of renderAmount()
+     * 
+     * @param array $data Data array
+     * 
+     * @return string Descript
+     * @access public
+     */
+    public function renderAmount($data)
+    {
+        extract($data['record']);
+        switch ($billing_type) {
+        case 1 :
+            $amount = (float)$amount;
+            break;
+        case 2 :
+            $amount = (float)-$amount;
+            break;
+        }
+        $format = "%01.2f";
+        return sprintf(
+            $format,
+            (float)$amount
+        );
+    }
+    
+    /**
+     * Description of renderBillingType()
+     * 
+     * @param array $data Data array
+     * 
+     * @return string
+     * @access public 
+     */
+    public function renderBillingType($data)
+    {
+        $billingTypes = $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'billingType')
+            ->getContent();
+        extract($data['record']);
+        return $billingTypes[$billing_type];
+    }
+
+    /**
+     * Description of renderDescription()
+     * 
+     * @param array $data Data array
+     * 
+     * @return string
+     * @access public 
+     */
+    public function renderDescription($data)
+    {
+        extract($data['record']);
+        switch ($billing_type) {
+        case 1 :
+            $urlFormat
+                = "members.php?rt=Members&ac=editMember&id=%d&invoice_id=%d"
+                . "&tab=invoices&returnPdf=1";
+            $url = sprintf(
+                $urlFormat,
+                $member_id,
+                $id
+            );
+            $format = '<a target="_blank" href="%s">Invoice: %s</a> for %s';
+            $out = sprintf(
+                $format,
+                $url,
+                $invoice_id,
+                $transaction_date
+            );
+            break;
+        case 2 :
+            $paymentMethods = $this->config
+                ->getItem('section', 'conf')
+                ->getItem('directive', 'paymentMethod')
+                ->getContent();
+            $out = $paymentMethods[$payment_method].': '.$payment_data;
+            break;
+        case 3 :
+            $out = 'Adjustment: '.$payment_data;
+            break;
+        case 4:
+            $out = $note;
+            break;
+        }
+        return $out;
+    }
+   
+    /**
+     * Description of renderMemberName()
+     * 
+     * @param array $data Data array
+     * 
+     * @return string
+     * @access public 
+     */
+    public function renderMemberName($data)
+    {
+        extract($data['record']);
+        $urlFormat
+            = "members.php?rt=Members&ac=editMember&id=%d&tab=invoices";
+        $url = sprintf(
+            $urlFormat,
+            $member_id
+        );
+        $format = '<a href="%s">%s</a>';
+        return sprintf(
+            $format,
+            $url,
+            $member_name
+        );
+    }
+
+    /**
+     * Description of setQuery()
+     * 
+     * @return array 
+     * @access public
+     */
+    public function  setQuery()
+    {
+        $params = array();
+        $sql = "
+        SELECT id,invoice_id,
+               to_char(transaction_time, 'MM/DD/YYY HH24:MI:SS') as transaction_time,
+               transaction_date,member_name,member_id,account_number,billing_type,
+               amount,balance,payment_method,payment_data,emailed,printed,paid,
+               invoice,notes
+          FROM billing";
+        if (   $_REQUEST['transaction_date_beg']['m']
+            && $_REQUEST['transaction_date_end']['m']
+        ) {
+            $startDate = implode("/", $_REQUEST['transaction_date_beg']);
+            $endDate = implode("/", $_REQUEST['transaction_date_end']);
+            $params[] = "transaction_date BETWEEN '{$startDate}' AND '{$endDate}'";
+        }
+        if ($_REQUEST['member_name']) {
+            $params[] = "member_name ilike '%{$_REQUEST['member_name']}%'";
+        }
+        if ($_REQUEST['account_number']) {
+            $params[] = "account_number = '{$_REQUEST['account_number']}'";
+        }
+        if (!empty($_REQUEST['payment_types'])) {
+            $params[] = "account_id IN (
+                SELECT id
+                  FROM member_account
+                 WHERE payment_type IN (" . implode(",", $_REQUEST['payment_types']) . ")
+                 )";
+        }
+        if (!empty($_REQUEST['counties'])) {
+            $params[] = "member_id IN (
+                SELECT member_id
+                  FROM member
+                 WHERE region IN (" . implode(",", $_REQUEST['counties']) . "))";
+        }
+        if (!empty($_REQUEST['billing_types'])) {
+            $params[] = "billing_type IN (" . implode(",", $_REQUEST['billing_types']) . ")";
+        }
+        if (!empty($params)) {
+            $sql .= " WHERE " . implode(" AND ", $params);
+        }
+        parent::setQuery($sql);
+        return $params;
+    }
+    
+    /**
+     * Description of toCSV()
+     * 
+     * @return boolean|mixed
+     * @access protected
+     */
+    protected function toCSV()
+    {
+        $this->generateColumns(
+            array(
+                'id' => 'Id',
+                'invoice_id' => 'Invoice Id',
+                'transaction_date' => 'Date',
+                'member_name' => 'Member Name',
+                'member_id' => 'Member Id',
+                'account_number' => 'Account Number',
+                'billing_type' => 'Billing Type',
+                'amount' => 'Amount',
+                'balance' => 'Balance',
+                'payment_method' => 'Payment Method',
+                'payment_data' => 'Payment Data'
+                
+            )
+        );
+        try {
+            $bind = $this->bind($this->sql, $this->options, 'PDO');
+            if (PEAR::isError($bind)) {
+                return Toolkit_Common::handleError($bind);
+            } elseif (($recCount = $this->getRecordCount()) > 0) {
+                $this->setRendererOptions($this->rendererOptions);
+                $csv = $this->getOutput(
+                    DATAGRID_RENDER_CSV,
+                    $this->rendererOptions
+                );
+                if (PEAR::isError($gridBody)) {
+                    return Toolkit_Common::handleError($gridBody);
+                }
+
+                return $csv;
+            } else {
+                return false;
+            }
+        } catch(PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+}
+
diff --git a/Toolkit/Members/Billing/ReportSearch.php b/Toolkit/Members/Billing/ReportSearch.php
new file mode 100644 (file)
index 0000000..4ced6d4
--- /dev/null
@@ -0,0 +1,364 @@
+<?php
+/**
+ * ReportSearch.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_ReportSearch
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_ReportSearch
+    extends Toolkit_FormBuilder
+{
+    /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The directory that holds the templates
+        *
+        * Keep this setting in relation to this file.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $templatesDir = 'templates';
+
+       /**
+        * The directory that holds the compiled templates
+        *
+        * Keep this setting in relation to this file.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $compiledTemplatesDir = 'templates/compiled';
+
+       /**
+        * The name of the template used to render the business info form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'reportSearch.html';
+    /**
+        * Constructor
+        *
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        * 
+        * @see    HTML_QuickForm
+        * @access public
+        */
+       public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               //      T_VARIABLE error when passing this server var in on the constructors params.
+               $action = empty($action) ? $_SERVER['REQUEST_URI'] : $action;
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        $this->flexyOptions                = $GLOBALS['flexyOptions'];
+               $this->flexyOptions['templateDir'] = dirname(__FILE__) . "/{$this->templatesDir}";
+               $this->flexyOptions['compileDir']  = dirname(__FILE__) . "/{$this->compiledTemplatesDir}";
+        
+               $this->template = BASE . 'Toolkit/Members/templates/currentTables/';
+       }
+
+    /**
+     * Setup form fields
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureElements()
+       {
+        $paymentTypes = $this->getPaymentTypes();
+        $counties     = $this->getCounties();
+        $config       = new Config();
+        $root         = $config->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $billingTypes = $root
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'billingType')
+            ->getContent();
+        unset($billingTypes[0]);
+        $dateStartYear = 2011;
+               //      All Elements are created here.  This includes group element definitions.
+        $e[] = array(
+            'type' => 'header',
+            'name' => 'Search'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'rt'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'ac'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'member_name',
+            'display' => 'Member Name'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'account_number',
+            'display' => 'Account Number'
+        );
+        $transactionDate = array();
+               $transactionDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'transaction_date_beg',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+               $transactionDate[] = array(
+                       'type'    => 'date',
+                       'req'     => false,
+                       'name'    => 'transaction_date_end',
+                       'opts'    => array(
+                               'format'           => 'm / d / Y',
+                               'minYear'          => $dateStartYear,
+                               'maxYear'          => date('Y'),
+                               'addEmptyOption'   => true,
+                               'emptyOptionValue' => '',
+                               'emptyOptionText'  => array(
+                                       'm' => 'mm',
+                                       'd' => 'dd',
+                                       'Y' => 'yyyy',
+                               )
+                       )
+               );
+        $e[] = array(
+                       'type'       => 'group',
+                       'req'        => false,
+                       'name'       => 'transaction_date',
+                       'group'      => $transactionDate,
+                       'seperator'  => '<br>',
+                       'label'      => "Date Between",
+                       'appendName' => false
+               );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'payment_types',
+            'display' => 'Payment Types',
+            'opts'    => $paymentTypes,
+            'att'     => array('multiple' => 'multiple', 'size' => count($paymentTypes))
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'billing_types',
+            'display' => 'Transaction Types',
+            'opts'    => $billingTypes,
+            'att'     => array('multiple' => 'multiple', 'size' => count($billingTypes))
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'counties',
+            'display' => 'Counties',
+            'opts'    => $counties,
+            'att'     => array('multiple' => 'multiple', 'size' => 5)
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'report_type',
+            'display' => 'Report Type',
+            'opts'    => array(
+                'html' => 'html',
+                'file' => 'file'
+            )
+        );
+        
+               $e[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit',
+            'display' => 'Search'
+        );
+
+               $this->setupElements($e);
+       }
+    
+    /**
+     * Description of configureForm()
+     * 
+     * @return void
+     * @access public 
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+               $this->configureFilters();
+               $this->configureConstants();
+    }
+    
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureFilters()
+       {
+               $filters[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($filters);
+       }
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureConstants()
+       {
+               $constants = array(
+                       'rt'    => 'Reports',
+                       'ac' => 'searchReports'
+               );
+
+               $this->setupConstants($constants);
+       }
+    
+    /**
+     * Description of getCounties()
+     * 
+     * @return array
+     * @access public 
+     */
+    public function getCounties()
+    {
+        $counties = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM region
+            ORDER BY region_name";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $counties[$row['region_id']] = $row['region_name'];
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $counties;
+    }
+
+    /**
+     * Get all payment types for a select list
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentTypes()
+    {
+        $paymentTypes = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM payment_types
+            ORDER BY name";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $paymentTypes[$row['id']] = $row['name'] . ' ($'.$row['amount'].')';
+            }
+            return $paymentTypes;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Description of setupRenderers()
+     * 
+     * @return void
+     * @access protected 
+     */
+    protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+               $this->accept($renderer);
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+               $this->view = $this;
+               $this->view->baseUrl = BASE_URL;
+               $this->view->form = $renderer->toObject();
+               $this->template->compile($this->formTemplate);
+       }
+
+    /**
+     * Description of toHTML()
+     * 
+     * @return string
+     * @access public
+     */
+    public function toHTML()
+       {
+        $this->setupRenderers();
+        return $this->template->bufferedOutputObject($this->view);
+       }
+}
diff --git a/Toolkit/Members/Billing/Statement.php b/Toolkit/Members/Billing/Statement.php
new file mode 100644 (file)
index 0000000..540159b
--- /dev/null
@@ -0,0 +1,515 @@
+<?php
+/**
+ * Statement.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_Billing_Statement
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_Billing_Statement
+{
+    /**
+     * Template file to use
+     * 
+     * @var string
+     * @access protected
+     */
+    protected $template = 'memberStatements.html';
+
+    /**
+     * Base of the billing template directory
+     *  
+     * @var string
+     * @access protected
+     */
+    protected $templateBase = 'Toolkit/Members/Billing/';
+    
+    /**
+     * The directory of the templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $templatesDir = 'templates';
+
+    /**
+     * The directory of the flexy-compiled templates
+     *
+     * @var string
+     * @access protected
+     */
+    protected $compiledDir = 'templates/compiled';
+    
+    /**
+     * Flexy Template Options array
+     * 
+     * @var array
+     * @access protected
+     */
+    protected $flexyOptions = array();
+    /**
+     * class Constructor
+     *
+     * @return void
+     * @access public
+     */
+    public function  __construct()
+    {
+        $config = new Config();
+        $root = $config->parseConfig(
+            BASE . 'Toolkit/Members/Billing/config.ini',
+            'IniFile'
+        );
+        $this->config = $root;
+        $this->flexyOptions = array(
+            'templateDir'  => BASE . "{$this->templateBase}{$this->templatesDir}",
+            'compileDir'   => BASE . "{$this->templateBase}{$this->compiledDir}",
+            'forceCompile' => 1,
+            'debug'        => 0,
+            'locale'       => 'en',
+        );
+    }
+
+    /**
+     * Generate a statement for a member
+     * This should be for the current year only
+     *
+     * @param PDO     $dbh       Database Connection
+     * @param mixed   $member_id member id
+     * @param boolean $all       Description of $all
+     * 
+     * @todo need to work this out for multilpe accounts
+     * 
+     * @return string
+     * @access public
+     */
+    public function createMemberStatements(
+        PDO $dbh,
+        $member_id,
+        $all = false
+    ) {
+        $template = new HTML_Template_Flexy($this->flexyOptions);
+        $page = new stdClass();
+        if (!is_numeric($member_id)) {
+            throw new InvalidArgumentException('member_id must be numeric');
+        }
+        $billingTypes
+            = $this->config
+                ->getItem('section', 'conf')
+                ->getItem('directive', 'billingType')
+                ->getContent();
+        $paymentMethods
+            = $this->config
+                ->getItem('section', 'conf')
+                ->getItem('directive', 'paymentMethod')
+                ->getContent();
+        $page->canEditBillings
+            = $this->config
+                ->getItem('section', 'conf')
+                ->getItem('directive', 'canEditBillings')
+                ->getContent();
+        unset($paymentMethods[2]);
+        $paymentTypes = $this->getPaymentTypes($dbh);
+        try {
+            $sql = "
+              SELECT id,payment_type
+                FROM member_account
+               WHERE member_id = :member_id
+            ORDER BY id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $member_id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        $accounts = array();
+        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+            $accounts[$row['id']]['paymentType']
+                = $paymentTypes[$row['payment_type']];
+            if ($all) {
+                $transactions = $this->getAllMemberBillings(
+                    $dbh,
+                    $member_id,
+                    $row['id']
+                );
+            } else {
+                $transactions = $this->getMemberBillings(
+                    $dbh,
+                    $member_id,
+                    $row['id']
+                );
+            }
+            
+            $count = 1;
+            if (is_array($transactions)) {
+                $records = array();
+                foreach ($transactions as $transaction) {
+                    $invoiceLink
+                        = BASE_URL . "admin/members.php"
+                        . "?rt=Members"
+                        . "&ac=editMember"
+                        . "&id={$member_id}"
+                        . "&tab=invoices"
+                        . "&invoice_id=" . $transaction->getId()
+                        . "&returnPdf=1";
+                    $editLink = BASE_URL . 'admin/members.php'
+                        . "?rt=Members"
+                        . "&ac=editMember"
+                        . "&id={$member_id}"
+                        . "&tab=invoices"
+                        . "&invoice_id=" . $transaction->getId()
+                        . "&editBilling=1";
+                    $deleteLink = BASE_URL . 'Toolkit/Members/Billing/'
+                        . "deleteBilling.php"
+                        . "?member_id=" . $member_id
+                        . "&billing_id=" . $transaction->getId();
+                    $resetUrl = BASE_URL . 'admin/members.php'
+                        . "?rt=Members"
+                        . "&ac=editMember"
+                        . "&id={$member_id}"
+                        . "&tab=invoices";
+                    $records[] = array(
+                        'id' => $transaction->getId(),
+                        'deleteLink' => $deleteLink,
+                        'editUrl' => (($transaction->getBilling_type() == 1)
+                            ? $editLink : ''),
+                        'resetUrl' => $resetUrl,
+                        'transaction_time' => date(
+                            "m/d/Y H:i:s",
+                            strtotime($transaction->getTransaction_time())
+                        ),
+                        'transaction_date'
+                            => $transaction->getTransaction_date(),
+                        'billing_type'
+                            => $billingTypes[$transaction->getBilling_type()],
+                        'payment_method'
+                            => $paymentMethods[$transaction->getPayment_method()],
+                        'payment_data' => $transaction->getPayment_data(),
+                        'notes' => $transaction->getNotes(),
+                        'amount' => $transaction->getAmount(),
+                        'balance' => $transaction->getBalance(),
+                        'className' => ((++$count % 2 == 0) ? 'even': 'odd'),
+                        'invoice' =>
+                            (($transaction->getBilling_type() == 1)
+                             ? $invoiceLink
+                             : ''
+                            )
+                    );
+                }
+                $accounts[$row['id']]['records'] = $records;
+            }
+            $accounts[$row['id']]['balanceDue']
+                = $this->getBalanceDue(
+                    $dbh,
+                    $_REQUEST['id'],
+                    $row['id']
+                );
+        }
+        $page->accounts = $accounts;
+        $template->compile($this->template);
+               $html = $template->bufferedOutputObject($page);
+        return $html;
+    }
+
+    /**
+     * Get the member balance due.
+     * Taken from the last billing record inserted into the billing table
+     *
+     * @param PDO $dbh        Database Connection
+     * @param int $member_id  Member id
+     * @param int $account_id Account id
+     *
+     * @return float
+     * @access public
+     */
+    public function getBalanceDue(
+        PDO $dbh,
+        $member_id,
+        $account_id
+    ) {
+        if (!is_numeric($member_id)) {
+            throw new InvalidArgumentException('member id must be numeric');
+        }
+        try {
+            $sql = "
+              SELECT id
+                FROM billing
+               WHERE member_id = :member_id
+                 AND account_id = :account_id
+            ORDER BY id DESC
+               LIMIT 1
+              OFFSET 0";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $member_id,
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':account_id',
+                $account_id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            $row = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($row) {
+                $balance = Toolkit_Members_Billing_Factory::createDbObjectById(
+                    $dbh,
+                    'Toolkit_Members_Billing_Billing',
+                    $row['id']
+                )->getBalance();
+            } else {
+                $balance = (float)'0.00';
+            }
+            return (float)((float)$balance + (float)'0.00');
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    
+    /**
+     * Description of getOriginalInvoice
+     * 
+     * @param PDO $dbh        Database handler
+     * @param int $member_id  Member ID
+     * @param int $account_id Account ID
+     * 
+     * @return object|boolean
+     * @access public
+     * @throws InvalidArgumentException
+     */
+    public function getOriginalInvoice(
+        PDO $dbh,
+        $member_id,
+        $account_id
+    ) {
+        if (!is_numeric($member_id)) {
+            throw new InvalidArgumentException('member id must be numeric');
+        }
+        if (!is_numeric($account_id)) {
+            throw new InvalidArgumentException('account id must be numeric');
+        }
+        try {
+            $sql = "
+              SELECT id
+                FROM billing
+               WHERE member_id = :member_id
+                 AND account_id = :account_id
+                 AND billing_type = 1
+            ORDER BY id DESC
+               LIMIT 1
+              OFFSET 0";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $member_id,
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':account_id',
+                $account_id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            $row = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($row) {
+                return Toolkit_Members_Billing_Factory::createDbObjectById(
+                    $dbh,
+                    'Toolkit_Members_Billing_Billing',
+                    $row['id']
+                );
+            }
+            return false;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Description of getAllMemberBillings()
+     * 
+     * @param PDO $dbh        Database Handler
+     * @param int $member_id  Member ID
+     * @param int $account_id Account ID
+     * 
+     * @return array
+     * @access public
+     */
+    public function getAllMemberBillings(
+        PDO $dbh,
+        $member_id,
+        $account_id
+    ) {
+        //$invoice            = new Toolkit_Members_Billing_Invoices();
+        //$nextInvoiceDate    = date('m/d/Y', $invoice->getNextInvoiceDate());
+        //$currentInvoiceDate = date('m/d/Y', $invoice->getCurrentInvoiceDate());
+        try {
+            // all statements
+            $sql = "
+              SELECT id
+                FROM billing
+               WHERE member_id = :member_id
+                 AND account_id = :account_id
+            ORDER BY id";
+            $stmt = $dbh->prepare($sql);
+            //$stmt->bindParam(':startDate', $currentInvoiceDate);
+            //$stmt->bindParam(':endDate', $nextInvoiceDate);
+            $stmt->bindParam(
+                ':member_id',
+                $member_id,
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':account_id',
+                $account_id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $transactions[]
+                    = Toolkit_Members_Billing_Factory::createDbObjectById(
+                        $dbh,
+                        'Toolkit_Members_Billing_Billing',
+                        $row['id']
+                    );
+            }
+            return $transactions;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    /**
+     * return all member billing records for the current year.
+     * plus any unpaid ones from previous years
+     *
+     * @param PDO $dbh        Database Connection
+     * @param int $member_id  Member id
+     * @param int $account_id Account id
+     *
+     * @return array
+     * @access public
+     */
+    public function getMemberBillings(
+        PDO $dbh,
+        $member_id,
+        $account_id
+    ) {
+        $invoice            = new Toolkit_Members_Billing_Invoices();
+        $nextInvoiceDate    = date('m/d/Y', $invoice->getNextInvoiceDate());
+        $currentInvoiceDate = date('m/d/Y', $invoice->getCurrentInvoiceDate());
+        try {
+            // see if this member has a balance due from previous year
+            // previous billing statement
+            $sql = "
+              SELECT id
+                FROM billing
+               WHERE member_id = :member_id
+                 AND account_id = :account_id
+                 AND transaction_date < :date
+                 AND billing_type IN (1, 2, 3)
+            ORDER BY id DESC
+               LIMIT 1
+              OFFSET 0";
+            $stmtB = $dbh->prepare($sql);
+            $stmtB->bindParam(
+                ':member_id',
+                $member_id,
+                PDO::PARAM_INT
+            );
+            $stmtB->bindParam(
+                ':account_id',
+                $account_id,
+                PDO::PARAM_INT
+            );
+            $stmtB->bindParam(':date', $currentInvoiceDate);
+            $stmtB->execute();
+            while ($row = $stmtB->fetch(PDO::FETCH_ASSOC)) {
+                $transactions[]
+                    = Toolkit_Members_Billing_Factory::createDbObjectById(
+                        $dbh,
+                        'Toolkit_Members_Billing_Billing',
+                        $row['id']
+                    );
+            }
+            // current year statements
+            $sql = "
+              SELECT id
+                FROM billing
+               WHERE member_id = :member_id
+                 AND account_id = :account_id
+                 AND transaction_date BETWEEN :startDate AND :endDate
+            ORDER BY id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':startDate', $currentInvoiceDate);
+            $stmt->bindParam(':endDate', $nextInvoiceDate);
+            $stmt->bindParam(
+                ':member_id',
+                $member_id,
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':account_id',
+                $account_id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $transactions[]
+                    = Toolkit_Members_Billing_Factory::createDbObjectById(
+                        $dbh,
+                        'Toolkit_Members_Billing_Billing',
+                        $row['id']
+                    );
+            }
+            return $transactions;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Get all payment types for a select list
+     * 
+     * @param PDO $dbh Database Handler
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getPaymentTypes(PDO $dbh)
+    {
+        $paymentTypes = array();
+        try {
+            $sql = "
+               SELECT *
+                FROM payment_types
+            ORDER BY name";
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $paymentTypes[$row['id']] = $row['name'] . ' ($'.$row['amount'].')';
+            }
+            return $paymentTypes;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
+
diff --git a/Toolkit/Members/Billing/billing.css b/Toolkit/Members/Billing/billing.css
new file mode 100644 (file)
index 0000000..a77cb8b
--- /dev/null
@@ -0,0 +1,21 @@
+fieldset {margin:0;padding:0;width:100%;}
+legend {margin-left: 100px;}
+table.statement {width:100%;background-color: #D6DFC3;}
+table.statement thead tr {background-color: white;}
+table.statement * td {padding: 3px 1px;}
+.even {background-color: #D6DFC3;}
+.odd {background-color: white;}
+.balanceline {background-color: white;border: solid 1px #D6DFC3;}
+#form-payment_types {width:220px;float: left;}
+#form-billing_types {width:150px;float: right;}
+#form-counties {width:150px;float: left;clear: both;}
+#form-report_type {width:100px;float: right;padding-right: 50px;}
+#button-submit {width:50px;margin-left: auto;margin-right: auto;clear: both;}
+table.dataGrid {width:740px;background-color: #D6DFC3;}
+table.dataGrid thead tr {background-color: white;}
+table.dataGrid * td {padding: 3px 1px;}
+#search-reports * img {display:inline;}
+#search-billing-form {width:580px;margin-left: auto;margin-right: auto;}
+#form-member_name {width:580px;margin-left: auto;margin-right: auto;}
+#form-account_number {width:580px;margin-left: auto;margin-right: auto;}
+#form-transaction_date {width:580px;margin-left: auto;margin-right: auto;padding-bottom: 20px;}
diff --git a/Toolkit/Members/Billing/checkInvestmentType.php b/Toolkit/Members/Billing/checkInvestmentType.php
new file mode 100644 (file)
index 0000000..e31844c
--- /dev/null
@@ -0,0 +1,35 @@
+<?php
+/**
+ * Billing.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+require_once '../../../setup.phtml';
+
+$dbh = Toolkit_Database::getInstance();
+if (is_numeric($_GET['account_id'])) {
+    try {
+        $sql = "
+        SELECT pt.dynamic_amount
+          FROM payment_types pt 
+               LEFT OUTER JOIN member_account ma
+               ON (ma.payment_type = pt.id)
+         WHERE ma.id = :account_id";
+        $stmt = $dbh->prepare($sql);
+        $stmt->bindParam(':account_id', $_GET['account_id'], PDO::PARAM_INT);
+        $stmt->execute();
+        $dynamicAmount = $stmt->fetchColumn();
+    } catch(PDOException $e) {
+        Toolkit_Common::handleError($e);
+    }
+    echo (bool)$dynamicAmount;
+} else {
+    echo (bool)false;
+}
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/config.ini b/Toolkit/Members/Billing/config.ini
new file mode 100644 (file)
index 0000000..298d492
--- /dev/null
@@ -0,0 +1,38 @@
+; Member Billing configuration file
+[conf]
+; invoice day
+invoiceDay = 1
+; invoice month
+invoiceMonth = 7
+
+; if admin can edit the billings
+canEditBillings = Off
+
+; billingTypes
+billingType[] = ""
+billingType[] = "Invoice"   ; 1
+billingType[] = "Payment"   ; 2
+billingType[] = "Adjustment"; 3
+billingType[] = "Comment"   ; 4
+
+; payment Methods
+paymentMethod[] = ""
+paymentMethod[] = "Check"      ; 1
+paymentMethod[] = "Credit Card"; 2
+paymentMethod[] = "Cash"       ; 3
+paymentMethod[] = "Other"      ; 4
+
+; Company and PDF Info
+companyLogo       = "images/logo.gif"
+companyLogoHeight = "50"
+companyName       = SITENAME
+companyName2      = "Demo"
+companyAddr1      = "demo address"
+companyAddr2      = "P.O. Box 150"
+companyCity       = "Petoskey"
+companyState      = "MI"
+companyZip        = "49770"
+companyPhone      = "1-800-OUR-DEMO"
+companyEmail      = "info@gaslightmedia.com"
+; url do not put in http://
+companyUrl        = "demo.gaslightmedia.com"
diff --git a/Toolkit/Members/Billing/deleteBilling.php b/Toolkit/Members/Billing/deleteBilling.php
new file mode 100644 (file)
index 0000000..a671c3f
--- /dev/null
@@ -0,0 +1,87 @@
+<?php
+/**
+ * deleteBilling.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+require_once '../../../setup.phtml';
+
+$memberId = filter_input(
+    INPUT_GET,
+    'member_id',
+    FILTER_SANITIZE_NUMBER_INT
+);
+$billingId = filter_input(
+    INPUT_GET,
+    'billing_id',
+    FILTER_SANITIZE_NUMBER_INT
+);
+if ($billingId) {
+    $dbh = Toolkit_Database::getInstance();
+    try {
+        //$dbh->beginTransaction();
+        $factory = new Toolkit_Members_Billing_Factory();
+        $billing = $factory->createDBObjectById(
+            $dbh,
+            'Toolkit_Members_Billing_Billing',
+            $billingId
+        );
+
+        // need to also delete any items
+        // related to the billing item after
+        // say like payments adjustment
+        $sql = "
+        DELETE
+          FROM billing
+         WHERE invoice_id = :invoice_id
+           AND member_id = :member_id";
+        $stmt1 = $dbh->prepare($sql);
+        $stmt1->bindParam(
+            ':invoice_id',
+            $billing->getInvoice_id(),
+            PDO::PARAM_INT
+        );
+        $stmt1->bindParam(
+            ':member_id',
+            $memberId,
+            PDO::PARAM_INT
+        );
+        $stmt1->execute();
+
+        // new delete record
+        $sql = "
+        DELETE
+          FROM billing
+         WHERE id = :billing_id
+           AND member_id = :member_id";
+        $stmt2 = $dbh->prepare($sql);
+        $stmt2->bindParam(
+            ':billing_id',
+            $billingId,
+            PDO::PARAM_INT
+        );
+        $stmt2->bindParam(
+            ':member_id',
+            $memberId,
+            PDO::PARAM_INT
+        );
+        $stmt2->execute();
+
+        // and commit transaction
+        //$dbh->commit();
+    } catch(PDOException $e) {
+        Toolkit_Common::handleError($e);
+    }
+}
+$resetUrl = BASE_URL . 'admin/members.php'
+    . "?rt=Members"
+    . "&ac=editMember"
+    . "&id={$memberId}"
+    . "&tab=invoices";
+header('Location: ' . $resetUrl);
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/js/edit-billing.js b/Toolkit/Members/Billing/js/edit-billing.js
new file mode 100644 (file)
index 0000000..32d90be
--- /dev/null
@@ -0,0 +1,53 @@
+/**
+ * When we are adding an region we want to focus on the first text field
+ * of the form.
+ */
+var MemberBilling =
+{
+    calImg: 'http://app.gaslightmedia.com/assets/icons/calendar.png',
+    today: new Date(),
+       init: function()
+       {
+               if ($("#transDate").length > 0) {
+            var transImg = '&nbsp;<img id="transDateCal"' +
+                ' height="16"' +
+                ' style="verticle-align:middle;"' +
+                ' src="' + MemberBilling.calImg + '">';
+            $("#transDate").after(transImg);
+            var month = (MemberBilling.today.getMonth()) + 1;
+            var day = MemberBilling.today.getDate();
+            var year = MemberBilling.today.getFullYear();
+            var transCal = new Zapatec.Calendar.setup({
+               weekNumbers : false,
+               ifFormat    : '%m/%d/%Y',
+               button      : 'transDateCal',
+               onUpdate    : MemberBilling.updateTransactionDateField,
+               showsTime   : false,
+               range       : [MemberBilling.today.getFullYear(), MemberBilling.today.getFullYear() + 1],
+               date        :  '7/1/' + year
+            });
+        }
+        if ($(".delete-billing").length > 0) {
+            $(".delete-billing").click(
+                function () {
+                    var ret = confirm(
+                        'This action cannot be undone!\nAre you sure?'
+                    );
+                    return ret;
+                }
+            );
+        }
+       },
+    updateTransactionDateField: function(cal)
+    {
+        var date = cal.date;
+        var month = date.getMonth() + 1;
+        var day = date.getDate();
+        var year = date.getFullYear();
+
+        $("#transDate").val(month + '/' + day + '/' + year);
+    }
+
+}
+
+$(document).ready(MemberBilling.init);
diff --git a/Toolkit/Members/Billing/pdfInvoice.php b/Toolkit/Members/Billing/pdfInvoice.php
new file mode 100644 (file)
index 0000000..ea518f8
--- /dev/null
@@ -0,0 +1,318 @@
+<?php
+/**
+ *  GLM PDF Forms
+ *  Invoice #1 - Invoice with payment return
+ *
+ *  PHP version 5
+ *
+ * @category  GLM_PDF_Forms
+ * @package   None
+ * @author    Chuck Scott <cscott@gaslightmedia.com>
+ * @copyright 2010-2010 Gaslight Media
+ * @license   http://app.gaslightmedia.com/license.php Gaslight Media
+ * @link      http://www.gaslightmedia.com www.gaslightmedia.com
+ * @since     $Date: 2011/03/18 12:33:47 $
+ */
+
+define('GLMPDF_DEBUG', false);
+
+// Setup border parameters
+define('BORDER_WIDTH', 0);
+define('BORDER_COLOR', 'black');
+
+// Set paper size
+define('PAPER_SIZE', 'US Letter');
+
+// Set system parameters
+define('GLM_PDF_ROOT', GLM_APP_BASE . "pdf/pdf_lib_8/");
+
+// putenv("PDFLIBSERIAL=L40300-102733-2200XX-5B12E1");    // PDFLib License Number
+
+require_once GLM_PDF_ROOT . "glmPdf.php";
+
+/**
+ * money()
+ *
+ * Format a number using conventions for money.
+ *
+ * @param float  $value  Value to be formatted
+ * @param string $option Comma or space separated options controlling format
+ *
+ * Options:
+ *     NOPREFIX  Do not prefix the number with a $.
+ *     NEG_PAREN Use parenthesis instead of "-" to designate a negative number.
+ *
+ * @return string
+ * @access public
+ */
+function money($value, $option = "")
+{
+
+    // Check if the "NOPREFIX" option is specified
+    if (strstr($option, 'NOPREFIX')) {
+        $prefix = "";
+    } else {
+        $prefix = "$";
+    }
+
+    // Check if it's a negative value. If so, save that and make it positive.
+    $neg = false;
+    if ($value < 0) {
+        $neg = true;
+        $value *= -1;
+    }
+
+    // Do value sanity check
+    if (!is_numeric($value)) {
+        return( $prefix."0.00" );
+    }
+
+    // Format number and add prefix
+    $r = $prefix.number_format($value, 2, ".", ",");
+
+    // Check if the value was negative.
+    if ($neg) {
+        if (strstr($option, 'NEG_PAREN')) {
+            $r = '('.$r.')';
+        } else {
+            $r = '-'.$r;
+        }
+    }
+
+    return $r;
+}
+
+
+/**
+ * glmpdf_invoice()
+ *
+ * Create an invoice (style 1) and return as a PDF.
+ *
+ * @param array $inv An array specifying invoice contents
+ *
+ * Format of $inv. A sample follows...
+ *
+ * array(
+ *    'company_logo'          => GLM_PDF_ROOT."forms/invoices/gaslight.gif",
+ *    'company_logo_height'   => 70,
+ *    'comany_name_in_header' => false,
+ *    'company_name'          => 'Gaslight Media',
+ *    'company_addr1'         => '120 E. Lake St.',
+ *    'company_addr2'         => '',
+ *    'company_city'          => 'Petoskey',
+ *    'company_state'         => 'MI',
+ *    'company_zip'           => '49770',
+ *    'company_phone'         => '231-487-0692',
+ *    'company_email'         => 'info@gaslightmedia.com',
+ *    'invoice_date'          => 'February 25, 2011',
+ *    'invoice_number'        => '1001',
+ *    'invoice_balance'       => 123.42,
+ *    'invoice_file_name'     => 'invoice_1001.pdf',
+ *    'member_billing_no'     => '123456',
+ *    'member_name'           => 'Fred Jones Digging',
+ *    'member_addr1'          => '123 E. West St.',
+ *    'member_addr2'          => 'Suite 35A',
+ *    'member_city'           => 'Eagle Mountain',
+ *    'member_state'          => 'MI',
+ *    'member_zip'            => '49110',
+ *    'member_phone'          => '123-123-1234',
+ *    'member_email'          => 'info@fjdig.com',
+ *    'payment_terms'         => 'Payable upon receipt',
+ *    'items' => array(
+ *        array(
+ *            'type' => 1,        // Invoice
+ *            'date' => '01/01/2011',
+ *            'descr' => 'Yearly Member Billing',
+ *            'amount' => 123.12,
+ *            'balance' => 123.12
+ *        ),
+ *        array(
+ *            'type' => 2,        // Payment
+ *            'date' => '01/01/2011',
+ *            'descr' => 'Check # 12345',
+ *            'amount' => 123.12,
+ *            'balance' => 0
+ *        )
+ *    )
+ * );
+ *
+ * @return string (pdf)
+ * @access public
+ */
+function glmpdf_invoice_1($inv)
+{
+    $glmPdf = new glmPdf();
+    /*
+     * Setup Forms Form layout
+     *
+     * x = bottom, y = left, xs = horz size, ys = vert size
+     *
+     * Invoice form is single form per page full page
+     */
+    $invoice_forms = array(
+        1 => array( 'x' => 0, 'y' => 0, 'xs' => 612,  'ys' => 792 )
+    );
+
+    // Initialize Forms
+    $r = $glmPdf->glmpdf_set_forms(
+        count($invoice_forms),
+        $voucher_forms,
+        $glmPdf->glmpdf_standard_page[PAPER_SIZE]['x'],
+        $glmPdf->glmpdf_standard_page[PAPER_SIZE]['y']
+    );
+    if (!$r) {
+        echo "ERROR: Unable to set PDF forms layout.";
+        exit;
+    }
+
+    // Start PDF Generation - (Creator, Author, Title)
+    $glmPdf->glmpdf_start("GLM PDF", "Gaslight Media", "Standard Invoice with Payment Form");
+//var_dump($glmPdf->glmpdf_pdf);
+//    exit;
+    // Load barcode font
+    if (!$glmPdf->glmpdf_add_font('barcode', 'barcode/FREE3OF9.TTF')) {
+        throw new Exception('ERROR: Unable to add barcode font.<P>
+            Did you place the barcode font into a system fonts directory
+            (/usr/share/fonts/ttf) and set the fonts directory correctly in the
+            pdf_functions.inc file?');
+        exit;
+    }
+
+
+
+    // Create new form
+    $glmPdf->glmpdf_next_form();
+
+    // Create Company Header
+    if (trim($inv['company_logo']) != '') {
+        $logo_y = 760 - $inv['company_logo_height'];
+        $logoImage = $glmPdf->glmpdf_open_image($inv['company_logo']);
+        $glmPdf->glmpdf_place_image($logoImage, 20, $logo_y, 1);
+    }
+    $glmPdf->glmpdf_set_font("Helvetica-Bold", 12.0);
+    $glmPdf->glmpdf_place_text($inv['company_name'], 20, 660, "left", 'black');
+    $glmPdf->glmpdf_set_font("Helvetica", 12.0);
+    $glmPdf->glmpdf_place_text($inv['company_addr1'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    if (trim($inv['company_addr2']) != '') {
+        $glmPdf->glmpdf_place_text($inv['company_addr2'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    }
+    $city_state = $inv['company_city'].', '.$inv['company_state'].' '.$inv['company_zip'];
+    $glmPdf->glmpdf_place_text($city_state, 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['company_phone'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['company_email'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+
+    // Invoice Header
+    $glmPdf->glmpdf_set_font("Helvetica-Bold", 26.0);
+    $glmPdf->glmpdf_place_text('INVOICE', 570, 710, "right", 'black');
+    $glmPdf->glmpdf_set_font("Helvetica", 12.0);
+    $glmPdf->glmpdf_place_text('Date:', 350, 650, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['invoice_date'], 450, $glmPdf->glmpdf_last_y, "left", 'black');
+    $glmPdf->glmpdf_place_text('Invoice #:', 350, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['invoice_number'], 450, $glmPdf->glmpdf_last_y, "left", 'black');
+    $glmPdf->glmpdf_place_text('Member Billing #:', 350, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_billing_no'], 450, $glmPdf->glmpdf_last_y, "left", 'black');
+
+    // Member Info
+    $glmPdf->glmpdf_set_font("Helvetica-Bold", 22.0);
+    $glmPdf->glmpdf_place_text('Bill To:', 20, 570, "left", 'black');
+    $glmPdf->glmpdf_set_font("Helvetica", 12.0);
+    $glmPdf->glmpdf_place_text($inv['member_name'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_addr1'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    if (trim($inv['member_addr2']) != '') {
+        $glmPdf->glmpdf_place_text($inv['member_addr2'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    }
+    $city_state = $inv['member_city'].', '.$inv['member_state'].' '.$inv['member_zip'];
+    $glmPdf->glmpdf_place_text($city_state, 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_phone'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_email'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+
+    // Terms
+    $glmPdf->glmpdf_place_box(1, 20, 470, 550, 20, 'gray', 'gray', 'round');
+    $glmPdf->glmpdf_set_font("Helvetica-Bold", 12.0);
+    $glmPdf->glmpdf_place_text('Payment Terms', 30, 455, "left", 'white');
+    $glmPdf->glmpdf_set_font("Helvetica", 12.0);
+    $glmPdf->glmpdf_place_text($inv['payment_terms'], 30, 430, "left", 'black');
+
+    // Items Header
+    $glmPdf->glmpdf_place_box(1, 20, 420, 550, 20, 'gray', 'gray', 'round');
+    $glmPdf->glmpdf_set_font("Helvetica-Bold", 12.0);
+    $glmPdf->glmpdf_place_text('Date', 30, 405, "left", 'white');
+    $glmPdf->glmpdf_place_text('Description', 110, $glmPdf->glmpdf_last_y, "left", 'white');
+    $glmPdf->glmpdf_place_text('Amount', 490, $glmPdf->glmpdf_last_y, "right", 'white');
+    $glmPdf->glmpdf_place_text('Balance', 560, $glmPdf->glmpdf_last_y, "right", 'white');
+
+    // Items
+    $glmPdf->glmpdf_set_font("Helvetica", 12.0);
+    $glmPdf->glmpdf_place_text('', 30, 380, "left", 'black');
+    foreach ($inv['items'] as $item) {
+        switch ($item['type']) {
+        // Type 1 - Invoice
+        case 1;
+            $glmPdf->glmpdf_place_text($item['date'], 30, $glmPdf->glmpdf_current_y, "left", 'black');
+            $glmPdf->glmpdf_place_text($item['descr'], 110, $glmPdf->glmpdf_last_y, "left", 'black');
+            $glmPdf->glmpdf_place_text(money($item['amount']), 490, $glmPdf->glmpdf_last_y, "right", 'black');
+            $glmPdf->glmpdf_place_text(money($item['balance']), 560, $glmPdf->glmpdf_last_y, "right", 'black');
+            break;
+
+        // Type 2 - Payment
+        case 2:
+            $glmPdf->glmpdf_place_text($item['date'], 30, $glmPdf->glmpdf_current_y, "left", 'black');
+            $glmPdf->glmpdf_place_text('Payment - Thank You!', 110, $glmPdf->glmpdf_last_y, "left", 'black');
+            $glmPdf->glmpdf_place_text(money($item['amount']*-1), 490, $glmPdf->glmpdf_last_y, "right", 'black');
+            $glmPdf->glmpdf_place_text(money($item['balance']), 560, $glmPdf->glmpdf_last_y, "right", 'black');
+            break;
+
+        }
+    }
+
+
+    // Tear-off Payment Form
+    $glmPdf->glmpdf_place_line(1, 20, 150, 570, 150, 'black', true, 4, 14);
+    $glmPdf->glmpdf_set_font("Helvetica", 10.0);
+    $glmPdf->glmpdf_place_text('Please return this coupon below with your payment.', 300, 154, 'center', 'black');
+    $glmPdf->glmpdf_place_text('Make checks payable to:', 20, 140, 'left', 'red');
+    $glmPdf->glmpdf_set_font("Helvetica", 12.0);
+
+    $glmPdf->glmpdf_place_text($inv['company_name'], 20, 128, "left", 'black');
+    $addr = $inv['company_addr1'];
+    if (trim($inv['company_addr2']) != '') {
+        $addr .= ', '.$inv['company_addr2'];
+    }
+    $addr .= ', '.$inv['company_city'].', '.$inv['company_state'].' '.$inv['company_zip'];
+    $glmPdf->glmpdf_place_text($addr, 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['company_phone'].'  -  '.$inv['company_email'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+
+    $glmPdf->glmpdf_place_text($inv['member_name'], 20, 80, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_addr1'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    if (trim($inv['member_addr2']) != '') {
+        $glmPdf->glmpdf_place_text($inv['member_addr2'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    }
+    $city_state = $inv['member_city'].', '.$inv['member_state'].' '.$inv['member_zip'];
+    $glmPdf->glmpdf_place_text($city_state, 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_phone'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_email'], 20, $glmPdf->glmpdf_current_y, "left", 'black');
+
+    $glmPdf->glmpdf_set_font("Helvetica-Bold", 12.0);
+    $glmPdf->glmpdf_place_text('Please Pay:', 450, 80, "right", 'black');
+    $glmPdf->glmpdf_place_text(money($inv['invoice_balance']), 560, $glmPdf->glmpdf_last_y, "right", 'black');
+
+    $glmPdf->glmpdf_set_font("Helvetica-Bold", 12.0);
+    if (($inv['invoice_balance']-0) > 0) {
+        $glmPdf->glmpdf_place_text('Payment Amount:', 450, 60, "right", 'black');
+        $glmPdf->glmpdf_place_box(1, 460, 75, 100, 20, 'black', 'white');
+    } else {
+        $glmPdf->glmpdf_place_text('NO PAYMENT REQUIRED', 560, 60, "right", 'black');
+    }
+
+    $glmPdf->glmpdf_set_font("Helvetica", 12.0);
+    $glmPdf->glmpdf_place_text('Member Billing #:', 450, 30, "right", 'black');
+    $glmPdf->glmpdf_place_text($inv['member_billing_no'], 560, $glmPdf->glmpdf_last_y, "right", 'black');
+
+    $barcode = $inv['member_billing_no'].'-'.$inv['invoice_number'];
+    $glmPdf->glmpdf_set_font('barcode', 40);
+    $glmPdf->glmpdf_place_text("*$barcode*", 560, 110, 'right', 'black');
+    $glmPdf->glmpdfDrawGrid(1, 1);
+
+        // Close PDF setup and send to user's browser
+    $glmPdf->glmpdf_send_to_browser('', $inv['invoice_file_name']);
+}
diff --git a/Toolkit/Members/Billing/recreateInvoices.php b/Toolkit/Members/Billing/recreateInvoices.php
new file mode 100644 (file)
index 0000000..d874eea
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+/**
+ * recreateInvoices.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Members
+ * @package  Billing
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+require_once '../../../setup.phtml';
+
+$dbh = Toolkit_Database::getInstance();
+
+try {
+    $sql = "
+    SELECT *
+      FROM billing
+     WHERE invoice != ''";
+    $stmt = $dbh->query($sql);
+    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+        $invoice = Toolkit_Members_Billing_Factory::createDbObjectById(
+            $dbh,
+            'Toolkit_Members_Billing_Billing',
+            $row['id']
+        );
+        //var_dump($invoice);
+        $pdf = new Toolkit_Members_Billing_InvoicePdf();
+        $pdfInvoice = $pdf->createPdfInvoice(
+            $dbh,
+            $row['member_id'],
+            $row['invoice_id'],
+            $row['account_id']
+        );
+
+        $invoice->setInvoice(base64_encode($pdfInvoice));
+        $invoice->save($dbh);
+    }
+} catch(PDOException $e) {
+    Toolkit_Common::handleError($e);
+}
+echo 'done';
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/templates/editBilling.html b/Toolkit/Members/Billing/templates/editBilling.html
new file mode 100644 (file)
index 0000000..675cb4c
--- /dev/null
@@ -0,0 +1,42 @@
+
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- CheckBoxes go here. -->
+                    {if:elem.isType(#checkbox#)}                        
+                        <td class="labelcell"> {elem.label:h} </td>
+                        <td class="fieldcell"> {elem.html:h} </td>
+                    {else:}
+                        <!-- All regular elements go here. -->
+                        <td class="labelcell">
+                            <span flexy:if="elem.required" class="req">*</span>
+                            {if:elem.error}<span class="req">{end:}
+                                {elem.label}
+                            {if:elem.error}</span>{end:}
+                        </td>
+                        <td class="fieldcell">
+                            <div flexy:if="elem.error" class="req">
+                                {elem.error}
+                            </div>
+                            {elem.html:h}
+                        </td>
+                    {end:}
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea" style="height:30px;width:400px;">
+        <b style="width:200px;float:left;">
+            <input type="submit" class="submit" value="Save">
+        </b>
+       </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/Billing/templates/editPaymentTypes.html b/Toolkit/Members/Billing/templates/editPaymentTypes.html
new file mode 100644 (file)
index 0000000..f5f1b46
--- /dev/null
@@ -0,0 +1,48 @@
+
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- CheckBoxes go here. -->
+                    {if:elem.isType(#checkbox#)}                        
+                        <td class="labelcell"> {elem.label:h} </td>
+                        <td class="fieldcell"> {elem.html:h} </td>
+                    {else:}
+                        <!-- All regular elements go here. -->
+                        <td class="labelcell">
+                            <span flexy:if="elem.required" class="req">*</span>
+                            {if:elem.error}<span class="req">{end:}
+                                {elem.label}
+                            {if:elem.error}</span>{end:}
+                        </td>
+                        <td class="fieldcell">
+                            <div flexy:if="elem.error" class="req">
+                                {elem.error}
+                            </div>
+                            {elem.html:h}
+                        </td>
+                    {end:}
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea" style="height:30px;width:400px;">
+        <b style="width:200px;float:left;">
+            <input type="submit" class="submit" value="Save Payment Type">
+        </b>
+               {if:isEdit()}
+        <b style="width:200px;float:left;">
+                       <input type="submit" name="delete" class="submit" value="Remove Payment Type"
+                   onClick="return(confirm('This cannot be undone! Are You Sure?'));">
+        </b>
+               {end:}
+       </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/Billing/templates/invoiceFilterForm.html b/Toolkit/Members/Billing/templates/invoiceFilterForm.html
new file mode 100644 (file)
index 0000000..01e0987
--- /dev/null
@@ -0,0 +1,39 @@
+
+<div>
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <div>
+               <fieldset flexy:foreach="form.sections,sec">
+                       <legend>{sec.header}</legend>
+                <div flexy:foreach="sec.elements,elem" style="float:left;width:200px;">
+                    <!-- CheckBoxes go here. -->
+                    {if:elem.isType(#checkbox#)}                        
+                        {elem.label:h}
+                        {elem.html:h}
+                    {else:}
+                        <!-- All regular elements go here. -->
+                            <span flexy:if="elem.required" class="req">*</span>
+                            {if:elem.error}<span class="req">{end:}
+                                <div>{elem.label}</div>
+                            {if:elem.error}</span>{end:}
+                            <div flexy:if="elem.error" class="req">
+                                {elem.error}
+                            </div>
+                            <div>{elem.html:h}</div>
+                    {end:}
+                </div>
+               </fieldset>
+       </div>
+       <div style="height:30px;width:400px;">
+        <b style="width:100px;float:left;">
+            <input type="submit" class="submit" value="Filter">
+        </b>
+        {if:task}
+        <b style="width:100px;float:left;">
+                       <input type="submit" name="submit" class="submit" value="{task:h}">
+        </b>
+        {end:}
+       </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/Billing/templates/memberList.html b/Toolkit/Members/Billing/templates/memberList.html
new file mode 100644 (file)
index 0000000..5636f73
--- /dev/null
@@ -0,0 +1,26 @@
+<table id="dataGrid" class="dataGrid">
+  <thead>
+    <tr>
+      <th>Member Name</th>
+      <th>Account Number</th>
+      <th>Payment Type</th>
+      <th>Balance Due</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr flexy:foreach="members,member" class="{member[classStyle]}">
+      <td>
+          <a href="{member[member_url]:h}">{member[member_name]:h}</a>
+      </td>
+      <td>
+          {member[account_number]:h}
+      </td>
+      <td>
+          {member[payment_type]:h}
+      </td>
+      <td>
+          {member[balanceDue]:h}
+      </td>
+    </tr>
+  </tbody>
+</table>
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/templates/memberStatements.html b/Toolkit/Members/Billing/templates/memberStatements.html
new file mode 100644 (file)
index 0000000..caaeecd
--- /dev/null
@@ -0,0 +1,44 @@
+
+<fieldset flexy:foreach="accounts,accountData">
+  <legend>{accountData[paymentType]:h} Statement</legend>
+    <table class="statement">
+      <thead>
+        <tr>
+          <td flexy:if="canEditBillings">&nbsp;</td>
+          <td>Date</td>
+          <td nowrap="nowrap">Transaction Time</td>
+          <td>Type</td>
+          <td>Method</td>
+          <td>Details</td>
+          <td>Notes</td>
+          <td>Invoice</td>
+          <td>Amount</td>
+          <td>Balance</td>
+          <td flexy:if="canEditBillings">&nbsp;</td>
+        </tr>
+      </thead>
+      <tr flexy:foreach="accountData[records],row" class="{row[className]:h}">
+          <td flexy:if="canEditBillings"><a flexy:if="row[editUrl]" class="edit-billing" rel="{row[id]}" href="{row[editUrl]:h}">Edit</a></td>
+        <td>{row[transaction_date]:h}</td>
+        <td nowrap="nowrap">{row[transaction_time]:h}</td>
+        <td>{row[billing_type]:h}</td>
+        <td>{row[payment_method]:h}</td>
+        <td>{row[payment_data]:h}</td>
+        <td>{row[notes]:h}</td>
+        <td><a flexy:if="row[invoice]" target="_blank" href="{row[invoice]:h}">Invoice</a></td>
+        <td align="right">${row[amount]:h}</td>
+        <td align="right">${row[balance]:h}</td>
+        <td flexy:if="canEditBillings"><a flexy:if="row[editUrl]" class="delete-billing" href="{row[deleteLink]:h}">Delete</a></td>
+      </tr>
+      <tr class="balanceline">
+        {if:canEditBillings}
+        <td colspan="9" align="right">Balance Due:</td>
+        {else:}
+        <td colspan="8" align="right">Balance Due:</td>
+        {end:}
+        
+        <td align="right">${accountData[balanceDue]:h}</td>
+        <td flexy:if="canEditBillings">&nbsp;</td>
+      </tr>
+  </table>
+</fieldset>
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/templates/paymentForm.html b/Toolkit/Members/Billing/templates/paymentForm.html
new file mode 100644 (file)
index 0000000..04eef40
--- /dev/null
@@ -0,0 +1,39 @@
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- CheckBoxes go here. -->
+                    {if:elem.isType(#checkbox#)}
+                        <td class="labelcell"> {elem.html:h} </td>
+                        <td class="fieldcell"> {elem.label:h} </td>
+                    {else:}
+                        <!-- All regular elements go here. -->
+                        <td class="labelcell">
+                            <span flexy:if="elem.required" class="req">*</span>
+                            {if:elem.error}<span class="req">{end:}
+                                {elem.label}
+                            {if:elem.error}</span>{end:}
+                        </td>
+                        <td class="fieldcell">
+                            <div flexy:if="elem.error" class="req">
+                                {elem.error}
+                            </div>
+                            {elem.html:h}
+                        </td>
+                    {end:}
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Make Payment">
+       </div>
+       </form>
+</div>
\ No newline at end of file
diff --git a/Toolkit/Members/Billing/templates/reportSearch.html b/Toolkit/Members/Billing/templates/reportSearch.html
new file mode 100644 (file)
index 0000000..d0ef998
--- /dev/null
@@ -0,0 +1,54 @@
+\r
+{form.javascript:h}\r
+{form.outputHeader():h}\r
+{form.hidden:h}\r
+<!-- Error or Success Message -->\r
+{validated():h}\r
+<div id="search-billing-form">\r
+{foreach:form.sections,sec} \r
+        <h2>Report Generator</h2>\r
+\r
+        {foreach:sec.elements,elem} \r
+            {if:elem.style}\r
+              {elem.outputStyle():h}\r
+            {else:}\r
+                {if:elem.isButton()}\r
+                    {if:elem.notFrozen()}\r
+                        <div id="button-submit">{elem.html:h}</div>\r
+                    {end:}\r
+                {else:}\r
+                    <div id="form-{elem.name}">\r
+                    {if:elem.isType(#textarea#)}\r
+                        <!-- <td colspan="2"> -->\r
+                            {if:elem.required}<span class="error">*</span>{end:}\r
+                            {if:elem.error}<span class="error">{end:}\r
+                            <b>{elem.label:h}:</b><br />\r
+                            {if:elem.error}</span>{end:}\r
+                    {else:}\r
+                        <!-- <td align="right" valign="top"> -->\r
+                            {if:elem.required}<span class="error">*</span>{end:}\r
+                            {if:elem.error}<span class="error">{end:}\r
+                            <b>{elem.label:h}:</b>\r
+                            {if:elem.error}</span>{end:}\r
+                        <!-- </td>\r
+                        <td> -->\r
+                    {end:}\r
+                    {if:elem.error}<div class="error">{elem.error}</div>{end:}\r
+                    {if:elem.isType(#group#)}\r
+                        {foreach:elem.elements,gitem}\r
+                            {gitem.label:h}\r
+                            {gitem.html:h}{if:gitem.required}<span class="error">*</span>*</span>{end:}\r
+                            {if:elem.separator}{elem.separator:h}{end:}\r
+                        {end:}\r
+                    {else:}\r
+                        {elem.html:h}\r
+                    {end:}\r
+                        <!-- </td> -->\r
+                    </div>\r
+                {end:}\r
+            {end:}\r
+        {end:}\r
+ {end:}\r
+        \r
+</div>\r
+</form>\r
diff --git a/Toolkit/Members/Billing/templates/sendEmailInvoice.html b/Toolkit/Members/Billing/templates/sendEmailInvoice.html
new file mode 100644 (file)
index 0000000..1d955e6
--- /dev/null
@@ -0,0 +1,21 @@
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+  <head>
+    <title></title>
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+  </head>
+  <body>      
+      <p>
+          Attached is your membership invoice for {member_name:h}.
+      </p>
+      <p>
+        {companyName}<br>
+        {companyName2}<br>
+        {companyAddr1}<br>
+        {companyCity}, {companyState} {companyZip}<br>
+        {companyPhone}<br>
+        <a href="http://{companyUrl}">{companyUrl}</a><br>
+      </p>
+  </body>
+</html>
diff --git a/Toolkit/Members/Billing/testMember.php b/Toolkit/Members/Billing/testMember.php
new file mode 100644 (file)
index 0000000..79e70f3
--- /dev/null
@@ -0,0 +1,170 @@
+<?php
+/**
+ * testMember.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+require_once '../../../setup.phtml';
+
+/**
+ * memberObj
+ * 
+ * Description of memberObj
+ * 
+ * @category  Toolkit
+ * @package   Members_Billing
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class memberObj extends Toolkit_Common
+{
+
+    /**
+     * Table name
+     * 
+     * @var string
+     * @access protected
+     */
+    protected $tableName = 'member';
+    
+    /**
+     * Class constructor
+     * 
+     * @param PDO $dbh Database handler
+     * 
+     * @access public
+     */
+    public function __construct(PDO $dbh)
+    {
+        $this->dbh = $dbh;
+    }
+}
+$members = array();
+$dbh = Toolkit_Database::getInstance();
+$dbh2 = new PDO(
+    'pgsql:host=ds3 user=nobody dbname=uptravel',
+    null,
+    null,
+    array(
+        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+    )
+);
+$sql = "
+SELECT member_name,type
+  FROM member
+ WHERE member_id = :member_id";
+$matchStmt = $dbh2->prepare($sql);
+$newMemberFields = array(
+    'member_id',
+    'member_name',
+    'member_login',
+    'member_passwd',
+    'active',
+    'street',
+    'lat',
+    'lon',
+    'phone',
+    'process_email',
+    'url',
+    'city_id',
+    'state_id',
+    'description',
+    'create_date',
+    'zip',
+    'toll_free',
+    'member_contact_email',
+    'state_id',
+    'mailing_address',
+    'mailing_city_id',
+    'mailing_state_id',
+    'mailing_zip',
+    'region',
+    'type',
+    'account_number'
+);
+$sql = "
+SELECT ".implode(',', $newMemberFields)."
+  FROM member
+ WHERE account_number IS NOT NULL
+ORDER BY account_number";
+$stmt = $dbh->query($sql);
+$sql = "
+UPDATE member
+   SET account_number = :account_number,
+       type = :type
+ WHERE member_id = :member_id";
+$updateMember = $dbh2->prepare($sql);
+$format = "<tr>
+        <td>%s</td>
+        <td>%s</td>
+        <td>%s</td>
+        <td>%s</td>
+        <td>%s</td>
+        <td>%s</td>
+      </tr>";
+echo '<table border="1">';
+$memberDat = new memberObj($dbh2);
+
+while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+    $matchStmt->bindParam(
+        ':member_id',
+        $row['member_id'],
+        PDO::PARAM_INT
+    );
+    $matchStmt->execute();
+    $matchData = $matchStmt->fetch();
+    if ($matchData) {
+        printf(
+            $format,
+            $row['member_id'],
+            $row['member_name'],
+            (($matchData['member_name'])
+                ? $matchData['member_name']
+                : '<b style="color:red;">Not Found</b>'),
+            $row['type'],
+            $matchData['type'],
+            $row['account_number']
+        );
+        $dbh2->beginTransaction();
+        $updateMember->bindParam(
+            ':account_number',
+            $row['account_number'],
+            PDO::PARAM_STR
+        );
+        $updateMember->bindParam(
+            ':type',
+            $row['type'],
+            PDO::PARAM_STR
+        );
+        $updateMember->bindParam(
+            ':member_id',
+            $row['member_id'],
+            PDO::PARAM_INT
+        );
+        $updateMember->execute();
+        $dbh2->rollBack();
+    } else {
+        $notFound[] = $row;
+        $sql = $memberDat->createSQLInsert('member', array_keys($row));
+        var_dump($sql);
+        $dbh2->beginTransaction();
+        $insertStmt = $memberDat->prepareQuery($dbh2, $sql, $row);
+        $insertStmt->execute();
+        $dbh2->rollBack();
+    }
+}
+
+echo '</table>';
+var_dump($notFound);
diff --git a/Toolkit/Members/BreadCrumbs.php b/Toolkit/Members/BreadCrumbs.php
new file mode 100644 (file)
index 0000000..262af93
--- /dev/null
@@ -0,0 +1,134 @@
+<?php
+/**
+ * NewsletterController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Admin_NewsletterController
+ * 
+ * Description of Toolkit_Members_Admin_NewsletterController
+ * 
+ * @category  Toolkit
+ * @package   Members_Admin
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_BreadCrumbs
+       extends Toolkit_Template_BreadCrumbs
+{
+       //      {{{     properties
+
+    /**
+     * PDO
+     * @var PDO
+     * @access private
+     */
+       private $_dbh;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Class constructor
+     * 
+     * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway
+     * @param PDO                                 $dbh     Database Handler
+     * 
+     * @access public
+     */
+       public function __construct(
+               Toolkit_Toolbox_PageGatewayAbstract $gateway,
+               PDO $dbh
+       ) {
+               $this->pageGateway = $gateway;
+               $this->_dbh        = $dbh;
+       }
+
+       //      }}}
+       //      {{{     getBreadCrumbsArray()
+
+    /**
+     * Description of getBreadCrumbsArray()
+     * 
+     * @param int $id Description for $id
+     * 
+     * @return array 
+     * @access protected
+     */
+       protected function getBreadCrumbsArray($id)
+       {
+               if ($id == HOME_ID) {
+                       return array();
+               }
+
+               $stack = array();
+               $memberName = $this->_getMemberName($_GET['member_id']);
+               array_unshift($stack, $memberName);
+               $searchId = $id;
+               do {
+                       $page = $this->pageGateway->find($searchId);
+                       $seoUrl = Toolkit_Template_Page::getSeoUrl(
+                               $this->pageGateway,
+                               $searchId
+                       );
+                       $anchor = '<a href="'.$seoUrl.'">'.$page['navigation_name'].'</a>';
+                       array_unshift($stack, $anchor);
+                       $searchId = $page['parent'];
+               } while ($page['parent'] != 0);
+
+               $anchor = '<a href="' . BASE_URL . 'index.php">Home</a>';
+               array_unshift($stack, $anchor);
+
+               return $stack;
+       }
+
+       //      }}}
+
+       //      {{{     _getMemberName()
+
+       /**
+        * Get the name of a member via memberId
+        *
+        * @param integer $mid Member id
+        *
+        * @return string member name
+        * @access private
+        * @throws Toolkit_Members_Exception upon error retrieving member name
+        */
+       private function _getMemberName($mid)
+       {
+               try {
+                       $sql = "
+                SELECT member_name
+                  FROM member
+                 WHERE member_id = :mid";
+
+                       $stmt = $this->_dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       return $row['member_name'];
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               "Unable to fetch member name for breadcrumbs for member `$mid`"
+                       );
+               }
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/CategoriesIterator.php b/Toolkit/Members/CategoriesIterator.php
new file mode 100644 (file)
index 0000000..db9e54d
--- /dev/null
@@ -0,0 +1,215 @@
+<?php
+
+/**
+ * Member categories to iterate
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id: CategoriesIterator.php,v 1.7 2010/06/29 19:15:23 jamie Exp $
+ * @link      <>
+ */
+
+
+/**
+ * Member categories to iterate
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @link      <>
+ */
+class Toolkit_Members_CategoriesIterator implements IteratorAggregate
+{
+    //  {{{ properties
+
+
+    /**
+     * Categories to iterate
+     * @var    array
+     * @access private
+     */
+       private $_categories;
+
+    //  }}}
+    //  {{{ __construct()
+
+
+    /**
+     * Constructor
+     *
+     * @return void
+     * @access private
+     */
+       private function __construct()
+       {
+               $this->_categories = array();
+       }
+
+    //  }}}
+
+    //  {{{ add()
+
+
+    /**
+     * Add a category to the collection
+     *
+     * @param Toolkit_Members_Category $c Category
+     *
+     * @return void
+     * @access public
+     */
+       public function add(Toolkit_Members_Category $c)
+       {
+               $this->_categories[] = $c;
+       }
+
+    //  }}}
+
+    //  {{{ create()
+
+
+    /**
+     * Create a new category iterator
+     *
+     * @return Toolkit_Members_CategoriesIterator An instance of an iteratorable object containing member categories
+     * @access public
+     * @static
+     */
+       public static function create()
+       {
+               return new self();
+       }
+
+    //  }}}
+
+    //  {{{ fetchAll()
+
+
+    /**
+     * Fetch all the categories
+     *
+     * @param PDO $pdo Database handler
+     *
+     * @return void
+     * @access public
+     */
+       public function fetchAll(PDO $pdo)
+       {
+               $this->_categories = array();
+
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM category";
+
+                       $this->_categories = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+    //  }}}
+
+    //  {{{ getAllIdsAsArray()
+
+
+    /**
+     * Gets all the categories ids as an array
+     *
+     * @return array  Member category ids
+     * @access public
+     */
+       public function getAllIdsAsArray()
+       {
+               $catIds = array();
+
+               foreach ($this->_categories as $i) {
+                       $catIds[] = $i->getId();
+               }
+
+               return $catIds;
+       }
+
+    //  }}}
+    //  {{{ getCategory()
+
+
+    /**
+     * Get a category object based on its database id
+     *
+     * @param integer $catid Member category database id
+     *
+     * @return Toolkit_Members_Category member category
+     * @access public
+     * @throws InvalidArgumentException if $catid is not an integer
+     */
+       public function getCategory($catid)
+       {
+               if (!ctype_digit((string)$catid)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $catid must be an integer.')
+                       ;
+               }
+
+               foreach ($this->_categories as $i) {
+                       if ($i->getId() == $catid) {
+                               return $i;
+                       }
+               }
+
+               return false;
+       }
+
+    //  }}}
+    //  {{{ getIterator()
+
+
+    /**
+     * Set an external iterator
+     *
+     * @return Traversable An instance of an object implementing Iterator or Traversable
+     * @access public
+     */
+       public function getIterator()
+       {
+               return new ArrayIterator($this->_categories);
+       }
+
+    //  }}}
+    //  {{{ getTree()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param PDO        $pdo  Database handler
+     * @param integer $root root of tree
+     *
+     * @return array Nested set keys from tree
+     * @access public
+     */
+       public function getTree(PDO $pdo, $root)
+       {
+               $tree = Toolkit_Common::getHierarchicalTreeStructure(
+                       $pdo,
+                       'category',
+                       'category_id',
+                       'parent_id',
+                       'pos',
+                       $root
+               );
+
+               return array_keys($tree);
+       }
+
+    //  }}}
+}
diff --git a/Toolkit/Members/Category.php b/Toolkit/Members/Category.php
new file mode 100644 (file)
index 0000000..17175e3
--- /dev/null
@@ -0,0 +1,521 @@
+<?php
+
+/**
+ * Member Category object
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id: Category.php,v 1.4 2010/02/12 21:22:17 jamie Exp $
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Member Category object
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Category
+{
+       //      {{{     properties
+
+    /**
+     * Category id
+     * @var    integer
+     * @access private
+     */
+       private $_id;
+
+    /**
+     * Category name
+     * @var    string
+     * @access private
+     */
+       private $_name;
+
+    /**
+     * Parent Id
+     * @var    integer
+     * @access private
+     */
+       private $_parentId;
+
+    /**
+     * Category is an accommodations category
+     * @var    boolean
+     * @access private
+     */
+       private $_accommodations;
+
+    /**
+     * Category is a restaurant category
+     * @var    boolean
+     * @access private
+     */
+       private $_restaurant;
+
+    /**
+     * Category is a golf category
+     * @var    boolean
+     * @access private
+     */
+       private $_golf;
+
+    /**
+     * Category code
+     * @var    integer
+     * @access private
+     */
+       private $_code;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * constructor
+     *
+     * @param string  $name           Category name
+     * @param integer $parent         Parent Id
+     * @param boolean $accommodations is accommodations category
+     * @param boolean $restaurant     is restaurant category
+     * @param boolean $golf           is golf category
+     * @param integer $code           category code
+     * @param integer $id             category id
+        *
+     * @return void
+     * @access private
+     */
+       private function __construct(
+               $name,
+               $parent,
+               $accommodations,
+               $restaurant,
+               $golf,
+               $code,
+               $id = null
+       ) {
+               $this->_name = $name;
+               $this->_parentId = $parent;
+               $this->_accommodations = $accommodations;
+               $this->_restaurant = $restaurant;
+               $this->_golf = $golf;
+               $this->_code = $code;
+               $this->_id = $id;
+       }
+
+       //      }}}
+       //      {{{     create()
+
+    /**
+     * Create a new category
+     *
+     * @param string  $name           Category name
+     * @param integer $parent         Parent Id
+     * @param boolean $accommodations is accommodations category
+     * @param boolean $restaurant     is restaurant category
+     * @param boolean $golf           is golf category
+     * @param integer $code           category code
+        *
+     * @return Toolkit_Members_Category new category object
+     * @access public
+     * @throws InvalidArgumentException if $parent is not an integer
+     * @throws InvalidArgumentException if $accommodations is not boolean
+     * @throws InvalidArgumentException if $restaurant is not boolean
+     * @throws InvalidArgumentException if $golf is not boolean
+     * @throws InvalidArgumentException if $code is not an integer
+     * @static
+     */
+       public static function create(
+               $name,
+               $parent = 0,
+               $accommodations = false,
+               $restaurant = false,
+               $golf = false,
+               $code = null
+       ) {
+               if (!ctype_digit((string)$parent)) {
+                       throw new InvalidArgumentException('Invalid Argument: $parent must be an integer.');
+               }
+               if (!is_bool($accommodations)) {
+                       throw new InvalidArgumentException('Invalid Argument: $accommodations must be boolean.');
+               }
+               if (!is_bool($restaurant)) {
+                       throw new InvalidArgumentException('Invalid Argument: $restaurant must be boolean.');
+               }
+               if (!is_bool($golf)) {
+                       throw new InvalidArgumentException('Invalid Argument: $golf must be boolean.');
+               }
+               if (!is_null($code) && !ctype_digit((string) $code)) {
+                       throw new InvalidArgumentException('Invalid Argument: $code must be an integer.');
+               }
+
+               return new self(
+                       $name,
+                       $parent,
+                       $accommodations,
+                       $restaurant,
+                       $golf,
+                       $code
+               );
+       }
+
+       //      }}}
+       //      {{{     fetch()
+
+    /**
+     * Fetch a category from the database
+     *
+     * @param PDO     $pdo Database handler
+     * @param integer $id  Category id to fetch
+        *
+     * @return Toolkit_Members_Category new object
+     * @access public
+     * @throws InvalidArgumentException if $id is not an integer
+     */
+       public function fetch(PDO $pdo, $id)
+       {
+               if (!ctype_digit((string)$id)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $categoryId must be an integer.'
+                       );
+               }
+
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM category
+                                WHERE category_id = :id";
+
+                       $stmt = $pdo->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       return new self(
+                               $row['name'],
+                               $row['parent_id'],
+                               (bool) $row['accommodations'],
+                               (bool) $row['restaurant'],
+                               (bool) $row['golf'],
+                               (bool) $row['code'],
+                               $row['category_id']
+                       );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getAccommodations()
+
+    /**
+     * Get accommodations
+     *
+     * @return boolean
+     * @access public
+     */
+       public function getAccommodations()
+       {
+               return $this->_accommodations;
+       }
+
+       //      }}}
+       //      {{{     getCode()
+
+    /**
+     * Get code
+     *
+     * @return integer
+     * @access public
+     */
+       public function getCode()
+       {
+               return $this->_code;
+       }
+
+       //      }}}
+       //      {{{     getGolf()
+
+    /**
+     * Get golf
+     *
+     * @return boolean
+     * @access public
+     */
+       public function getGolf()
+       {
+               return $this->_golf;
+       }
+
+       //      }}}
+       //      {{{     getId()
+
+    /**
+     * Get category id
+     *
+     * @return integer
+     * @access public
+     */
+       public function getId()
+       {
+               return $this->_id;
+       }
+
+       //      }}}
+       //      {{{     getName()
+
+    /**
+     * Get category name
+     *
+     * @return string
+     * @access public
+     */
+       public function getName()
+       {
+               return $this->_name;
+       }
+
+       //      }}}
+       //      {{{     getParentId()
+
+    /**
+     * Get categories parent id
+     *
+     * @return integer
+     * @access public
+     */
+       public function getParentId()
+       {
+               return $this->_parentId;
+       }
+
+       //      }}}
+       //      {{{     getRestaurant()
+
+    /**
+     * Get restaurant
+     *
+     * @return boolean
+     * @access public
+     */
+       public function getRestaurant()
+       {
+               return $this->_restaurant;
+       }
+
+       //      }}}
+       //      {{{     save()
+
+    /**
+     * Save a category to the database
+     *
+     * @param PDO $dbh Database handler
+        *
+     * @return boolean result of inserting the category to the db
+     * @access public
+     */
+       public function save(PDO $dbh)
+       {
+               $data = array(
+                       'name' => $this->_name,
+                       'parent_id' => $this->_parentId,
+                       'accommodations' => $this->_accommodations,
+                       'restaurant' => $this->_restaurant,
+                       'golf' => $this->_golf,
+                       'code' => $this->_code
+               );
+               try {
+                       $sql = Toolkit_Common::createSQLInsert(
+                               'category',
+                               array_keys($data)
+                       );
+
+                       $dbh->beginTransaction();
+
+                       $res = Toolkit_Common::processQuery(
+                               $dbh,
+                               'category',
+                               $sql,
+                               $data
+                       );
+
+                       $sql = "
+                               SELECT *
+                                 FROM category
+                                ORDER BY category_id DESC
+                                LIMIT 1";
+
+                       $row = $dbh->query($sql)->fetch();
+
+                       $this->_id = $row['category_id'];
+                       $dbh->commit();
+
+                       return $res;
+               } catch (PDOException $e) {
+                       $dbh->rollback();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setname()
+
+    /**
+     * Set the category name
+     *
+     * @param string $name new category name
+        *
+     * @return void
+     * @access public
+     */
+       public function setName($name)
+       {
+               $this->_name = $name;
+       }
+
+       //      }}}
+       //      {{{     setAccommodations()
+
+    /**
+     * Set if category is an accommodation
+     *
+     * @param boolean $accommodations if category is an accommodations
+        *
+     * @return void
+     * @access public
+     * @throws InvalidArgumentException if $accommodations is not a boolean
+     */
+       public function setAccommodations($accommodations)
+       {
+               if (!is_bool($accommodations)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $accommodations must be boolean.'
+                       );
+               }
+
+               $this->_accommodations = $accommodations;
+       }
+
+       //      }}}
+       //      {{{     setRestaurant()
+
+    /**
+     * Set if a category is a restaurant
+     *
+     * @param boolean $restaurant if category is a restaurant
+        *
+     * @return void
+     * @access public
+     * @throws InvalidArgumentException if $restuarant is not a boolean
+     */
+       public function setRestaurant($restaurant)
+       {
+               if (!is_bool($restaurant)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $restaurant must be boolean.'
+                       );
+               }
+
+               $this->_restaurant = $restaurant;
+       }
+
+       //      }}}
+       //      {{{     setGolf()
+
+    /**
+     * Set if category is a golf category
+     *
+     * @param boolean $golf if category is a golf category
+        *
+     * @return void
+     * @access public
+     * @throws InvalidArgumentException if $golf is not a boolean
+     */
+       public function setGolf($golf)
+       {
+               if (!is_bool($golf)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $golf must be boolean.'
+                       );
+               }
+
+               $this->_golf = $golf;
+       }
+
+       //      }}}
+       //      {{{     setCode()
+
+    /**
+     * Set the category code
+     *
+     * @param integer $code categories new code
+        *
+     * @return void
+     * @access public
+     * @throws InvalidArgumentException if $code is not an integer
+     */
+       public function setCode($code)
+       {
+               if (!ctype_digit((string)$code)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $code must be an integer.'
+                       );
+               }
+
+               $this->_code = $code;
+       }
+
+       //      }}}
+       //      {{{     update()
+
+    /**
+     * Sync the database w/ the category object
+     *
+     * @param PDO $pdo Database handler
+        *
+     * @return boolean true on success, false on error
+     * @access public
+     */
+       public function update(PDO $pdo)
+       {
+               try {
+                       $data = array(
+                               'name' => $this->_name,
+                               'parent_id' => $this->_parentId,
+                               'accommodations' => $this->_accommodations,
+                               'restaurant' => $this->_restaurant,
+                               'golf' => $this->_golf,
+                               'code' => $this->_code
+                       );
+
+                       $sql = Toolkit_Common::createSQLUpdate(
+                               'category',
+                               array_keys($data),
+                               array('category_id = :category_id')
+                       );
+                       $data['category_id'] = $this->_id;
+
+                       return Toolkit_Common::processQuery($pdo, 'category', $sql, $data);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/CategoryTree.php b/Toolkit/Members/CategoryTree.php
new file mode 100644 (file)
index 0000000..19c0c60
--- /dev/null
@@ -0,0 +1,71 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Short description for file
+ *
+ * Long description (if any) ...
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: CategoryTree.php,v 1.6 2010/05/25 14:01:16 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Short description for class
+ *
+ * Long description (if any) ...
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_CategoryTree extends Toolkit_Tree
+{
+       //      {{{ addChildren()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+    protected function addChildren()
+    {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM category
+                                WHERE parent_id = :parent
+                                ORDER BY name";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':parent', $this->catid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $this->children[] = new Toolkit_Members_CategoryTree($row['category_id'],
+                                                                                                                                        $row['name'],
+                                                                                                                                        $this->dbh,
+                                                                                                                                        $row['parent_id']);
+                       }
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/City.php b/Toolkit/Members/City.php
new file mode 100644 (file)
index 0000000..3854355
--- /dev/null
@@ -0,0 +1,556 @@
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * City Object
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.comm>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: City.php,v 1.5 2009/12/29 14:17:48 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handle City functionality
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2008 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: City.php,v 1.5 2009/12/29 14:17:48 jamie Exp $
+ * @link      http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members.php?page=citiesList&module=listCities
+ */
+class Toolkit_Members_City
+{
+       //      {{{      properties
+
+    /**
+     * Description of $name
+     * @var string
+     * @access protected
+     */
+    protected $name;
+
+    /**
+     * Description of $region
+     * @var int
+     * @access protected
+     */
+    protected $county;
+
+    /**
+     * Description of $state
+     * @var int
+     * @access protected
+     */
+    protected $state;
+
+    /**
+     * Description of $image
+     * @var string
+     * @access protected
+     */
+    protected $image;
+
+    /**
+     * Description of $description
+     * @var string
+     * @access protected
+     */
+    protected $description;
+
+    /**
+     * Description of $lat
+     * @var double
+     * @access protected
+     */
+    protected $lat;
+
+    /**
+     * Description of $lon
+     * @var double
+     * @access protected
+     */
+    protected $lon;
+
+    /**
+     * Table name in DB
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'city';
+
+    /**
+     * Image Server
+     * @var    object
+     * @access protected
+     */
+    protected $is;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO $pdo PHP Data Object
+        *
+        * @access public
+        */
+       public function __construct(PDO $pdo)
+       {
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+    //  {{{ createNewCity()
+
+    /**
+     * Creates a new city in the DB
+     *
+     * @return mixed
+     * @access public
+     */
+    public function createNewCity()
+    {
+        //  Minimum required fields to have an array
+        if (!is_numeric($this->state) || empty($this->name)) {
+            return false;
+        }
+
+        if ($this->_isDuplicate()) {
+            return PEAR::raiseError('This city already exists');
+        }
+
+        $this->setLatLonCoordinates();
+
+        $values = array(
+            'city_name'   => $this->name,
+            'state_id'    => $this->state,
+            'county_id'   => $this->county,
+            'description' => $this->description,
+            'image'       => $this->image,
+            'lat'         => $this->lat,
+            'lon'         => $this->lon
+        );
+
+        $sql = Toolkit_Common::createSQLInsert(
+            $this->tableName,
+            array_keys($values)
+        );
+
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+    //  {{{ deleteCity()
+
+    /**
+     * delete a city from the DB
+     *
+     * @param integer $id city record to delete
+     *
+     * @return mixed
+     * @access public
+     */
+    public function deleteCity($id)
+    {
+        if (!is_numeric($id)) {
+            return false;
+        }
+
+        $sql = "
+            DELETE FROM {$this->tableName}
+             WHERE city_id = :id";
+
+        try {
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            return $stmt->execute();
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+    //  {{{ getName()
+
+    /**
+     * get the name of the city
+     *
+     * @return string
+     * @access public
+     */
+    public function getName()
+    {
+        return $this->name;
+    }
+
+    //  }}}
+    /**
+     * Description for setLatLonCoordinates()
+     *
+     * @access protected
+     * @return void
+     */
+    protected function setLatLonCoordinates()
+    {
+        $cityName = $this->getName();
+        try {
+            $sql = "
+            SELECT state_abb
+              FROM state
+             WHERE state_id = :state_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':state_id',
+                $this->getState(),
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            $stateName = $stmt->fetchColumn();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        $geocoder = new GeocodeYahoo();
+        $address = array(
+                       'city'  => $cityName,
+                       'state' => $stateName
+               );
+        try {
+            $response = $geocoder->geocodeAddress($address);
+            $responseArray = unserialize($response);
+            if ($responseArray['ResultSet']['Result'][0]['Latitude']) {
+                $lat = $responseArray['ResultSet']['Result'][0]['Latitude'];
+                $lon = $responseArray['ResultSet']['Result'][0]['Longitude'];
+            } else {
+                $lat = $responseArray['ResultSet']['Result']['Latitude'];
+                $lon = $responseArray['ResultSet']['Result']['Longitude'];
+            }
+        } catch (BadMethodCallException $e) {
+            Toolkit_Logger::logException('Invalid Arg', $e);
+        } catch (Exception $e) {
+            Toolkit_Logger::logException('Yahoo GeoCode', $e);
+        }
+        if ($lat) {
+            $this->setLat($lat);
+        }
+        if ($lon) {
+            $this->setLon($lon);
+        }
+    }
+    //  {{{ getState()
+
+    /**
+     * get the state the city belongs in
+     *
+     * @return string
+     * @access public
+     */
+    public function getState()
+    {
+        return $this->state;
+    }
+
+    //  }}}
+    //  {{{ getRegion()
+
+    /**
+     * get the Region the city belongs in
+     *
+     * @return string
+     * @access public
+     */
+    public function getCounty()
+    {
+        return $this->county;
+    }
+
+    //  }}}
+    //  {{{ getImage()
+
+    /**
+     * get the city image
+     *
+     * @param string $uri URI location to find the image at
+     *
+     * @return string file name of image, or html img tag of image
+     * @access public
+     */
+    public function getImage($uri = null)
+    {
+        if (is_null($uri)) {
+            return $this->image;
+        } else {
+            $path = $uri . $this->image;
+            $imageSize = $this->is->getImageSize($path);
+            $img = "<img {$imageSize[2]} src=\"{$path}\">";
+            return $img;
+        }
+    }
+
+    //  }}}
+    //  {{{ getDesc()
+
+    /**
+     * get the description of the city
+     *
+     * @return string city description
+     * @access public
+     */
+    public function getDescription()
+    {
+        return $this->description;
+    }
+
+    //  }}}
+
+    //  {{{ _isDuplicate()
+
+    /**
+     * get the description of the city
+     *
+     * @param integer $ignore city records to not include in count
+     *
+     * @return mixed city description, error, bool
+     * @access private
+     */
+    private function _isDuplicate($ignore = null)
+    {
+        $sql = "
+            SELECT count(*) AS total
+              FROM {$this->tableName}
+             WHERE city_name = :name
+               AND state_id = :state";
+
+        if (is_numeric($ignore)) {
+            $sql .= " AND city_id <> $ignore";
+        }
+
+        try {
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':name', $this->name, PDO::PARAM_STR);
+            $stmt->bindParam(':state', $this->state, PDO::PARAM_INT);
+            $stmt->execute();
+            $stmt->bindColumn('total', $total);
+            $stmt->fetch();
+
+            return (bool) $total;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+    //  {{{ setName()
+
+    /**
+     * set the name of the city
+     *
+     * @param string $name City Name
+     *
+     * @return string
+     * @access public
+     */
+    public function setName($name)
+    {
+        $this->name = $name;
+    }
+
+    //  }}}
+    /**
+     * Set latitude of the city
+     *
+     * @param int $lat City latitude
+     *
+     * @return void
+     * @access public
+     */
+    public function setLat($lat)
+    {
+        $newLat = (float) $lat;
+               if ($newLat >= -90.0 && $newLat <= 90.0) {
+            $this->lat = $newLat;
+        }
+    }
+
+    /**
+     * Set longitude of the city
+     *
+     * @param int $lng City longitude
+     *
+     * @return void
+     * @access public
+     */
+    public function setLon($lng)
+    {
+        $newLng = (float) $lng;
+               if ($newLng >= -180.0 && $newLng <= 180.0) {
+            $this->lon = $newLng;
+        }
+    }
+    //  {{{ setState()
+
+    /**
+     * set the state the city belongs in
+     *
+     * @param integer $state state id from db
+     *
+     * @return void
+     * @access public
+     * @throws PEAR_Error
+     */
+    public function setState($state)
+    {
+        if (!is_numeric($state)) {
+            return PEAR::raiseError('Invalid state id');
+        }
+
+        $this->state = $state;
+    }
+
+    //  }}}
+    //  {{{ setRegion()
+
+    /**
+     * set the Region the city belongs in
+     *
+     * @param integer $county region id from db
+     *
+     * @return void
+     * @access public
+     * @throws PEAR_Error
+     */
+    public function setCounty($county)
+    {
+        if (!is_numeric($county)) {
+            return PEAR::raiseError('Invalid county id');
+        }
+        $this->county = $county;
+    }
+
+    //  }}}
+    //  {{{ setImage()
+
+    /**
+     * set the city image
+     *
+     * @param string $image the city image
+     *
+     * @return void
+     * @access public
+     */
+    public function setImage($image)
+    {
+        $this->image = $image;
+    }
+
+    //  }}}
+    //  {{{ setImageServer()
+
+    /**
+     * set the image server to use
+     *
+     * @param Toolkit_Image_Server $is Image Server Instance
+     *
+     * @return void
+     * @access public
+     */
+    public function setImageServer(Toolkit_Image_Server $is)
+    {
+        $this->is = $is;
+    }
+
+    //  }}}
+    //  {{{ setDesc()
+
+    /**
+     * set the description of the city
+     *
+     * @param string $desc City Description
+     *
+     * @return void
+     * @access public
+     */
+    public function setDescription($desc)
+    {
+        $this->description = $desc;
+    }
+
+    //  }}}
+
+    //  {{{ updateCity()
+
+    /**
+     * update a city in the DB
+     *
+     * @param integer $id record id to update
+     *
+     * @return mixed
+     * @access public
+     * @throws PEAR_Error
+     */
+    public function updateCity($id)
+    {
+        //  Minimum required fields to have an array
+        if (!is_numeric($this->state) || empty($this->name)) {
+            return false;
+        }
+
+        if ($this->_isDuplicate($id)) {
+            return PEAR::raiseError('This city already exists');
+        }
+
+        $this->setLatLonCoordinates();
+
+        $values = array(
+            'city_name'   => $this->name,
+            'state_id'    => $this->state,
+            'county_id'   => $this->county,
+            'description' => $this->description,
+            'image'       => $this->image,
+            'lat'         => $this->lat,
+            'lon'         => $this->lon
+        );
+
+        $sql = Toolkit_Common::createSQLUpdate(
+            $this->tableName,
+            array_keys($values),
+            array('city_id = :city_id')
+        );
+
+        $values['city_id'] = $id;
+
+        try {
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/Members/Contact.php b/Toolkit/Members/Contact.php
new file mode 100644 (file)
index 0000000..9616e32
--- /dev/null
@@ -0,0 +1,508 @@
+<?php
+/**
+ * Contact.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_Contact
+ *
+ * Description for Toolkit_Members_Contact
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_Contact
+{
+       //      {{{     properties
+
+    /**
+     * Contact title
+     * @var string
+     * @access private
+     */
+       private $_title;
+
+    /**
+     * Contact first name
+     * @var string
+     * @access private
+     */
+       private $_fname;
+
+    /**
+     * Contact last name
+     * @var string
+     * @access private
+     */
+       private $_lname;
+
+    /**
+     * Contact email
+     * @var string
+     * @access private
+     */
+       private $_email;
+
+    /**
+     * Contact phone number
+     * @var string
+     * @access private
+     */
+       private $_phone;
+
+    /**
+     * Whether contact can receive mail
+     * @var boolean
+     * @access private
+     */
+       private $_canReceiveMail;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Class constructor
+     * 
+     * @param string  $fname          Contact first name
+     * @param string  $lname          Contact last name
+     * @param string  $title          Contact title
+     * @param string  $email          Contact email
+     * @param string  $phone          Contact phone number
+     * @param boolean $canReceiveMail Contact can Receive Mail
+     * 
+     * @access public
+     */
+       public function __construct(
+               $fname,
+               $lname,
+               $title = null,
+               $email = null,
+               $phone = null,
+               $canReceiveMail = false
+       ) {
+               $this->_fname = $fname;
+               $this->_lname = $lname;
+               $this->_title = $title;
+               $this->_email = $email;
+               $this->_phone = $phone;
+               $this->_canReceiveMail = (bool) $canReceiveMail;
+       }
+
+       //      }}}
+       //      {{{     __toString()
+
+    /**
+     * Description of __toString()
+     * 
+     * @return string
+     * @access public 
+     */
+       public function __toString()
+       {
+               if (!is_null($this->_email)) {
+                       $format = '<a href="mailto:%s">%s %s</a>';
+                       $name = sprintf(
+                               $format,
+                               $this->_email,
+                               $this->_fname,
+                               $this->_lname
+                       );
+               } else {
+                       $name = "{$this->_fname} {$this->_lname}";
+               }
+
+               $string = $name;
+               if (!is_null($this->_title)) {
+                       $string .= " {$this->_title}";
+
+                       if (!is_null($this->_phone)) {
+                               $string .= ", ";
+                       }
+               }
+
+               if (!is_null($this->_phone)) {
+                       $string .= " {$this->_phone}";
+               }
+
+               return $string;
+       }
+
+       //      }}}
+
+       //      {{{     delete()
+
+       /**
+        * Delete a contact
+        *
+        * @param PDO     $pdo Database handler
+        * @param integer $cid Contact id to delete
+        *
+        * @return Toolkit_Members_Contact instance of contact that was deleted
+        * @access public
+        * @static
+        * @throws InvalidArgumentException if $cid is not an integer
+        */
+       public static function delete(PDO $pdo, $cid)
+       {
+               if (!ctype_digit((string)$cid)) {
+                       throw new InvalidArgumentException(
+                               'InvalidArgument: $cid must be an integer.'
+                       );
+               }
+
+               $contact = self::fetch($pdo, $cid);
+
+               try {
+                       $sql = "
+                               DELETE FROM member_contacts
+                                WHERE id = :id";
+                       $stmt = $pdo->prepare($sql);
+                       $stmt->bindParam(':id', $cid, PDO::PARAM_INT);
+                       $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+               return $contact;
+       }
+
+       //      }}}
+       //      {{{     fetch()
+
+       /**
+        * Fetch a contact from the database
+        *
+        * @param PDO     $pdo Database handler
+        * @param integer $cid Contact id
+        *
+        * @return Toolkit_Members_Contact|false contact object or error
+        * @access public
+        * @static
+        * @throws InvalidArgumentException if $cid is not an integer
+        */
+       public static function fetch(PDO $pdo, $cid)
+       {
+               if (!ctype_digit((string)$cid)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $cid must be an integer.'
+                       );
+               }
+
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM member_contacts
+                                WHERE id = :id";
+                       $stmt = $pdo->prepare($sql);
+                       $stmt->bindParam(':id', $cid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                       return new self(
+                               $row['fname'],
+                               $row['lname'],
+                               $row['title'],
+                               $row['email'],
+                               $row['phone'],
+                               (bool) $row['send_mail']
+                       );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     getTitle()
+
+       /**
+        * Get the contact title
+        *
+        * @return string title
+        * @access public
+        */
+       public function getTitle()
+       {
+               return $this->_title;
+       }
+
+       //      }}}
+       //      {{{     getFname()
+
+       /**
+        * Get the contact first name
+        *
+        * @return string fname
+        * @access public
+        */
+       public function getFname()
+       {
+               return $this->_fname;
+       }
+
+       //      }}}
+       //      {{{     getLname()
+
+       /**
+        * Get the contact last name
+        *
+        * @return string lname
+        * @access public
+        */
+       public function getLname()
+       {
+               return $this->_lname;
+       }
+
+       //      }}}
+       //      {{{     getEmail()
+
+       /**
+        * Get the contact email address
+        *
+        * @return string email
+        * @access public
+        */
+       public function getEmail()
+       {
+               return $this->_email;
+       }
+
+       //      }}}
+       //      {{{     getPhone()
+
+       /**
+        * Get the contact phone number
+        *
+        * @return string phone
+        * @access public
+        */
+       public function getPhone()
+       {
+               return $this->_phone;
+       }
+
+       //      }}}
+       //      {{{     getCanReceiveMail()
+
+       /**
+        * Get if the contact can receive mail
+        *
+        * @return boolean canReceiveMail
+        * @access public
+        */
+       public function getCanReceiveMail()
+       {
+               return $this->_canReceiveMail;
+       }
+
+       //      }}}
+       //      {{{     setFname()
+
+       /**
+        * Set the contact first name
+        *
+        * @param string $fname first name
+        *
+        * @return void
+        * @access public
+        */
+       public function setFname($fname)
+       {
+               $this->_fname = $fname;
+       }
+
+       //      }}}
+       //      {{{     setLname()
+
+       /**
+        * Set the contact last name
+        *
+        * @param string $lname last name
+        *
+        * @return void
+        * @access public
+        */
+       public function setLname($lname)
+       {
+               $this->_lname = $lname;
+       }
+
+       //      }}}
+       //      {{{     setTitle()
+
+       /**
+        * Set the contact title
+        *
+        * @param string $title contact title
+        *
+        * @return void
+        * @access public
+        */
+       public function setTitle($title)
+       {
+               $this->_title = $title;
+       }
+
+       //      }}}
+       //      {{{     setEmail()
+
+       /**
+        * Set the contact email address
+        *
+        * @param string $email email address
+        *
+        * @return void
+        * @access public
+        */
+       public function setEmail($email)
+       {
+               $this->_email = $email;
+       }
+
+       //      }}}
+       //      {{{     setPhone()
+
+       /**
+        * Set the contact phone
+        *
+        * @param string $phone phone number
+        *
+        * @return void
+        * @access public
+        */
+       public function setPhone($phone)
+       {
+               $this->_phone = $phone;
+       }
+
+       //      }}}
+       //      {{{     setCanReceiveMail()
+
+       /**
+        * Set if the contact can receive mail or not
+        *
+        * @param boolean $mail if the contact can receive mail or not
+        *
+        * @return void
+        * @access public
+        * @throws InvalidArgumentException if $mail is not a boolean value
+        */
+       public function setCanReceiveMail($mail)
+       {
+               if (!is_bool($mail)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $mail must be a boolean.'
+                       );
+               }
+
+               $this->_canReceiveMail = $mail;
+       }
+
+       //      }}}
+
+       //      {{{     save()
+
+       /**
+        * Save a contact to a member in the database
+        *
+        * @param PDO     $pdo    Database handler
+        * @param integer $member Member to assign contact to
+        *
+        * @return boolean Result of save query
+        * @access public
+        * @throws InvalidArgumentException if $member is not an integer
+        */
+       public function save(PDO $pdo, $member)
+       {
+               if (!ctype_digit((string)$member)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $member must be an integer.'
+                       );
+               }
+
+               $data = array(
+                       'member_id' => $member,
+                       'fname'         => $this->_fname,
+                       'lname'         => $this->_lname,
+                       'title'         => $this->_title,
+                       'email'         => $this->_email,
+                       'phone'         => $this->_phone,
+                       'send_mail' => $this->_canReceiveMail
+               );
+               $sql = Toolkit_Common::createSQLInsert(
+                       'member_contacts',
+                       array_keys($data)
+               );
+
+               try {
+                       return Toolkit_Common::processQuery(
+                               $pdo,
+                               'member_contacts',
+                               $sql,
+                               $data
+                       );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     update()
+
+       /**
+        * Update a contact in the databse
+        *
+        * @param PDO     $pdo Database handler
+        * @param integer $cid Contact id to update in the database
+        *
+        * @return boolean Result of update query
+        * @access public
+        * @throws InvalidArgumentException if $cid is not an integer
+        */
+       public function update(PDO $pdo, $cid)
+       {
+               if (!ctype_digit((string)$cid)) {
+                       throw new InvalidArgumentException(
+                               'Invalid Argument: $cid must be an integer.'
+                       );
+               }
+
+               $data = array(
+                       'fname' => $this->_fname,
+                       'lname' => $this->_lname,
+                       'email' => $this->_email,
+                       'title' => $this->_title,
+                       'phone' => $this->_phone,
+                       'send_mail' => $this->_canReceiveMail
+               );
+
+               $sql = Toolkit_Common::createSQLUpdate(
+                       'member_contacts',
+                       array_keys($data),
+                       array('id = :id')
+               );
+               $data['id'] = $cid;
+
+               try {
+                       return Toolkit_Common::processQuery(
+                               $pdo,
+                               'member_contacts',
+                               $sql,
+                               $data
+                       );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+}
+?>
diff --git a/Toolkit/Members/ContactsDataGrid.php b/Toolkit/Members/ContactsDataGrid.php
new file mode 100644 (file)
index 0000000..8641a8d
--- /dev/null
@@ -0,0 +1,174 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabsstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @release  CVS: $Id: ContactsDataGrid.php,v 1.2 2010/07/18 16:44:33 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Datagrid of search results of member db
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_ContactsDataGrid extends Toolkit_FlexyDataGridBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       private $queryParams = array();
+
+    /**
+     * Description for $template
+     * @var string
+     * @access protected
+     */
+       protected $template = 'listContacts.html';
+
+       //      }}}
+
+       //      {{{ configureColumns()
+
+       /**
+        * Configures the columns that will be used in our datagrid renderer.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureColumns()
+       {
+               $id = new Structures_DataGrid_Column(
+                       'Contact Id',
+                       'id',
+                       'id'
+               );
+               $this->addColumn($id);
+
+               $fname = new Structures_DataGrid_Column(
+                       'First Name',
+                       'fname',
+                       'fname'
+               );
+               $this->addColumn($fname);
+
+               $lname = new Structures_DataGrid_Column(
+                       'Last Name',
+                       'lname',
+                       'lname'
+               );
+               $this->addColumn($lname);
+
+               $title = new Structures_DataGrid_Column(
+                       'Member Name',
+            'title',
+            'title'
+               );
+               $this->addColumn($title);
+
+               $phone = new Structures_DataGrid_Column(
+                       'Phone',
+            'phone',
+            'phone'
+        );
+               $this->addColumn($phone);
+
+               $email = new Structures_DataGrid_Column(
+                       'Email',
+            'email',
+            'email'
+               );
+               $this->addColumn($email);
+
+               $canReceiveMail = new Structures_DataGrid_Column(
+                       'Can Mail',
+            'send_mail',
+            'send_mail'
+               );
+               $this->addColumn($canReceiveMail);
+    }
+
+    //    }}}
+
+       //      {{{ phone()
+
+       /**
+        * Returns the phone # for a member.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the phone for the member
+        *
+     * @param array $data tuple record from db
+     *
+        * @return mixed false when empty, member phone number if not empty
+        * @access public
+        */
+       public function email($data)
+       {
+        extract($data['record']);
+               return empty($phone) ? false : $phone;
+       }
+
+       //      }}}
+
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery()
+    {
+               $sql = "
+                       SELECT *
+                         FROM member_contacts";
+
+               if ($memberId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $this->queryParams = array("member_id = $memberId");
+               }
+
+               if (!empty($this->queryParams)) {
+                       $sql .= ' WHERE ' . implode(' AND ', $this->queryParams);
+               }
+
+        parent::setQuery($sql);
+    }
+
+    //  }}}
+       //      {{{     setControlObject()
+
+    /**
+     * These are the objects that will be inserted into the template.
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setControlObject()
+       {
+               $this->ctrlObj['baseUrl'] = BASE_URL;
+               if ($memberId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $this->ctrlObj['member'] = $memberId;
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Coupons/EditCouponForm.php b/Toolkit/Members/Coupons/EditCouponForm.php
new file mode 100644 (file)
index 0000000..b9a5779
--- /dev/null
@@ -0,0 +1,786 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * EditCouponForm.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Coupons
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditCouponForm.php,v 1.8 2010/08/12 18:07:21 matrix Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+require_once BASE . 'Toolkit/Forms/Rules/Date.php';
+
+/**
+ * Banner Ad Application
+ *
+ * Description of Toolkit_Members_Coupons_EditCouponForm
+ *
+ * @category  Toolkit
+ * @package   Members_Coupons
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Coupons_EditCouponForm extends Toolkit_FormBuilder
+{
+    //  {{{ properties
+
+       /**
+        * What do you want the success msg to be if the form validates successfully
+        *
+        * @var string
+        * @access protected
+        */
+       protected $successMsg
+               = '<div id="form-success-top">Your new coupon or coupon update has been
+            submitted and is pending approval by the Web site administrator.</div>';
+
+       /**
+        * The default rules to register for validating
+        *
+        * We have to register these rules, or any others we want, before
+        * we are able to use them in our forms.
+        *
+        * @var array
+        * @access protected
+        */
+       protected $registeredRules = array(
+               array(
+                       'checkURI',
+                       'callback',
+                       'uri',
+                       'Validate'
+               )
+       );
+
+    //  }}}
+
+       //      {{{     checkDates()
+
+       /**
+        * Check that start date does not come before end date
+        *
+        * @param array $dates Multi-Dimensional array of dates.
+        *
+        * @return boolean false if start is after end, else true
+        * @access public
+        */
+       public function checkDates(array $dates)
+       {
+               extract($dates[0], EXTR_PREFIX_ALL, 'start');
+               extract($dates[1], EXTR_PREFIX_ALL, 'end');
+
+
+               $sdate = new Date();
+               $sdate->setDate("$start_Y-$start_m-$start_d");
+               $edate = new Date();
+               $edate->setDate("$end_Y-$end_m-$end_d");
+
+               return (Date::compare($sdate, $edate) < 1);
+       }
+
+       //      }}}
+    //  {{{ configureConstants()
+
+       /**
+        * Configure form constants
+        *
+        * @return void
+        * @access public
+        */
+    public function configureConstants()
+    {
+        $c = array();
+
+        //     If we are adding a new banner
+        if (!ctype_digit($_GET['id'])) {
+               $c['current_image_rmv'] = 'Coupon not yet uploaded';
+               $c['pending'] = true;
+        }
+
+        //     If the form has been submitted and a new image was uploaded
+        $currImg = $this->getSubmitValue('image');
+        if ($this->isSubmitted() && !empty($currImg)) {
+               $img = '<img src="%s%s">';
+                       $path = THUMB;
+               $c['current_image_rmv'] = sprintf($img, $path, $currImg);
+        }
+
+        $this->setupConstants($c);
+    }
+
+    //  }}}
+    //  {{{ configureDefaults()
+
+       /**
+        * Configure the initial default values for the form
+        *
+        * @param PDO $dbh Database handler
+        *
+     * @return void
+        * @access protected
+        */
+    public function configureDefaults(PDO $dbh)
+    {
+               if (ctype_digit($_GET['id'])) {
+                       try {
+                               $sql = "
+                               SELECT *
+                                 FROM coupons
+                                WHERE id = :id";
+                               $stmt = $dbh->prepare($sql);
+                               $stmt->bindParam(":id", $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $d = $stmt->fetch(PDO::FETCH_ASSOC);
+                if ($d['image']) {
+                    $d['current_image_rmv'] = '<img src="'
+                        . THUMB
+                        . $d['image']
+                        . '"><br><label>'
+                        . '<input type="hidden" name="old_image_rmv" value="'
+                        . $d['image']
+                        . '">'
+                        . '<input type="checkbox" name="del_image_rmv" value="1">'
+                        . 'Delete Image?'
+                        . '</label>';
+                } else {
+                    $d['current_image_rmv'] = 'Nothing uploaded yet';
+                }
+                               //echo '<pre>'.print_r($d, true).'</pre>';
+                       } catch(PDOException $e) {
+                               Toolkit_Common::handleError($e);
+                       }
+                       //die('fix configure defaults');
+               } else {
+                       $date = new Date();
+                       $sdateMonth = $date->getMonth();
+                       $sdateDay   = $date->getDay();
+                       $sdateYear  = $date->getYear();
+
+                       $date->addMonths(6);
+
+                       $edateMonth = $date->getMonth();
+                       $edateDay   = $date->getDay();
+                       $edateYear  = $date->getYear();
+                       $d = array(
+                               'sdate' => array(
+                    'm' => $sdateMonth,
+                    'd' => $sdateDay,
+                    'Y' => $sdateYear
+                ),
+                               'edate' => array(
+                    'm' => $edateMonth,
+                    'd' => $edateDay,
+                    'Y' => $edateYear
+                ),
+                               'expiration' => array(
+                    'm' => $edateMonth,
+                    'd' => $edateDay,
+                    'Y' => $edateYear
+                ),
+                       );
+               }
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+    //  {{{ configureElements()
+
+       /**
+        * Configure how the form elements should look
+        *
+     * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+        * @access public
+        */
+       public function configureElements(PDO $dbh, Config_Container $c)
+       {
+        $e = array();
+
+               $categories = $this->_getCategories($dbh);
+
+        //  Get reference to [conf] section of config file
+        $conf =& $c->getItem('section', 'conf');
+
+               $minYear = $c->getItem('section', 'conf')
+                       ->getItem('directive', 'dateStartYear')
+                       ->getContent();
+
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'html',
+            'req' => false,
+            'name' => '<tr><td colspan="2"><b>Creating a Coupon:</b>The Start date is when you expect the coupon to appear on our website. The End date is when it will automatically be removed from display to visitors. The expiration date is printed with the coupon, so be sure to set your expiration date correctly.</td></tr>',
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'active',
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'pending',
+        );
+        $e[] = array(
+               'type' => 'hidden',
+               'req' => false,
+               'name' => 'member',
+        );
+        $e[] = array(
+               'type' => 'select',
+               'req' => true,
+               'name' => 'category',
+               'display' => 'Category',
+                       'opts' => array('' => '-- Select --') + $categories
+        );
+        $e[] = array(
+               'type' => 'text',
+               'req' => true,
+               'name' => 'title',
+               'display' => 'Title',
+                       'opts' => array('class' => 'text')
+        );
+        $e[] = array(
+               'type' => 'textarea',
+               'req' => false,
+               'name' => 'description',
+               'display' => 'Description <span id="charleft">600</span> characters left',
+            'opts' => array('id' => 'description')
+        );
+        $e[] = array(
+               'type' => 'text',
+               'req' => false,
+               'name' => 'url',
+               'display' => 'Website Link',
+        );
+               $e[] = array(
+                'type' => 'static',
+                'req' => false,
+                'name' => 'current_image_rmv',
+                'display' => 'Current Coupon Image'
+        );
+               $e[] = array(
+                'type' => 'hidden',
+                'req' => false,
+                'name' => 'image'
+        );
+               $e[] = array(
+            'type' => 'file',
+            'req' => false,
+            'name' => 'file_rmv',
+            'display' => 'New Coupon Image'
+        );
+               $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'img_instructions_rmv',
+            'opts' => '.jpg or .gif images only'
+        );
+               $e[] = array(
+            'type' => 'date',
+            'req' => true,
+            'name' => 'sdate',
+            'display' => 'Start Date',
+            'opts' => array(
+               'format' => 'm / d / Y',
+               'minYear' => $minYear,
+               'maxYear' => date('Y') + 5,
+               'addEmptyOption' => true,
+               'emptyOptionText' => array(
+                       'm' => 'mm',
+                       'd' => 'dd',
+                       'Y' => 'yyyy'
+                               )
+                       ),
+            'att' => array('id' => 'sdate')
+        );
+               $e[] = array(
+            'type' => 'date',
+            'req' => true,
+            'name' => 'edate',
+            'display' => 'End Date',
+            'opts' => array(
+               'format' => 'm / d / Y',
+               'minYear' => $minYear,
+               'maxYear' => date('Y') + 5,
+               'addEmptyOption' => true,
+               'emptyOptionText' => array(
+                       'm' => 'mm',
+                       'd' => 'dd',
+                       'Y' => 'yyyy'
+                               )
+                       ),
+            'att' => array('id' => 'edate')
+        );
+               $e[] = array(
+            'type' => 'date',
+            'req' => true,
+            'name' => 'expiration',
+            'display' => 'Expire Date',
+            'opts' => array(
+               'format' => 'm / d / Y',
+               'minYear' => $minYear,
+               'maxYear' => date('Y') + 5,
+               'addEmptyOption' => true,
+               'emptyOptionText' => array(
+                       'm' => 'mm',
+                       'd' => 'dd',
+                       'Y' => 'yyyy'
+                               )
+                       ),
+            'att' => array('id' => 'expire')
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit_rmv',
+            'display' => 'Submit Coupon',
+            'opts' => array('id' => 'submit')
+        );
+        if (ctype_digit($_GET['id'])) {
+            $e[] = array(
+                'type'    => 'submit',
+                'req'     => false,
+                'name'    => 'delete_rmv',
+                'display' => 'Delete Coupon',
+                'opts'    => array(
+                    'id'      => 'delete',
+                    'onClick' => 'return confirm(\'This will delete the Coupon\nAre You Sure?\');'
+                )
+            );
+        }
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+       /**
+        * Configure how the form elements should act when being submitted
+        *
+     * @return void
+        * @access protected
+        */
+       public function configureFilters()
+       {
+        $f   = array();
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+        $f[] = array(
+            'element' => 'url',
+                       'filter' => array('Toolkit_Common', 'filterURI')
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+       //      {{{     configureForm()
+
+       /**
+        * Configure a form so we can use it
+        *
+        * @param PDO              $dbh Database handler
+        * @param Config_Container $c   Application configuration settings
+        *
+        * @return void
+        * @access public
+        */
+       public function configureForm(
+               PDO $dbh,
+               Config_Container $c
+       ) {
+               $this->configureElements($dbh, $c);
+               $this->configureFilters();
+               $this->configureRules();
+               $this->configureDefaults($dbh);
+               $this->configureConstants();
+       }
+
+       //      }}}
+       //      {{{     configureRules()
+
+       /**
+        * Configure how the form elements should act
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+        $r = array();
+
+               $mimeTypes = array(
+                       'image/jpe',
+                       'image/jpeg',
+                       'image/jpg',
+                       'image/jfif',
+                       'image/pjpeg',
+                       'image/pjp',
+                       'image/gif',
+                       'image/png',
+               );
+
+               $r[] = array(
+                       'element'    => 'url',
+                       'message'    => 'ERROR: Invalid URL format (http, https only)',
+                       'type'       => 'checkURI',
+                       'format'     => array(
+                               'allowed_schemes' => array('http', 'https'),
+                               'strict' => true
+                       ),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+            'element' => 'sdate',
+            'message' => 'ERROR: Invalid Date!',
+            'type' => 'Date',
+            'format' => array('format' => '%m-%d-%Y'),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'edate',
+            'message' => 'ERROR: Invalid Date!',
+            'type' => 'Date',
+            'format' => array('format' => '%m-%d-%Y', 'allowEmpty' => true),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'expire',
+            'message' => 'ERROR: Invalid Date!',
+            'type' => 'Date',
+            'format' => array('format' => '%m-%d-%Y', 'allowEmpty' => true),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => array('sdate', 'edate'),
+            'message' => 'ERROR: Invalid Start Date!',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDates'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => array('edate', 'expire'),
+            'message' => 'ERROR: Expire date ends before end date!',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDates'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               if (is_uploaded_file($_FILES['file_rmv']['tmp_name'])) {
+                       $r[] = array(
+                'element' => 'file_rmv',
+                'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                'type' => 'mimetype',
+                'format' => $mimeTypes,
+                'validation' => $this->validationType,
+                'reset' => false,
+                'force' => false
+            );
+               }
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+    //  {{{ _getCategories()
+
+       /**
+        * Get the array of coupon categories used for the select list
+        *
+        * @param PDO $dbh Database handler
+        *
+        * @return array categories used to populate a select list element
+        * @access protected
+        */
+       private function _getCategories(PDO $dbh)
+       {
+               //  Get only the active categories from
+               //  the nav structure for our select list.
+               $sql = "
+                       SELECT *
+                         FROM coupon_category
+                        ORDER BY name";
+
+               $categories = array();
+               foreach ($dbh->query($sql, PDO::FETCH_ASSOC) as $row) {
+                       $categories[$row['name']] = $row['name'];
+               }
+               return $categories;
+       }
+
+    //  }}}
+
+       //      {{{     _processData()
+
+       /**
+        * Determine how the form should be handled (insert new data or update old)
+        *
+     * @param PDO                           $dbh                       Database handler
+     * @param array                         $values                    Submitted form values
+     * @param Toolkit_Coupons_CouponFactory $cFactory                  Coupon
+     * @param stdClass                      &$couponMailerTemplateData Coupon mailer template data
+     *
+     * @return boolean Result of insert or update function
+        * @access private
+        */
+    private function _processData(
+        PDO $dbh,
+        array $values,
+               Toolkit_Coupons_CouponFactory $cFactory,
+               stdClass &$couponMailerTemplateData
+    ) {
+               unset($values['MAX_FILE_SIZE']);
+
+        $deleteImage = ($_POST['del_image_rmv']) ? true: false;
+               foreach ($values as $k => $v) {
+            if (   $k != 'uploaded_file_rmv'
+                && preg_match('/^.+_rmv$/', $k)
+            ) {
+                               unset($values[$k]);
+                       }
+               }
+
+               $sdateStr = implode('/', $values['sdate']);
+               $sdateTS = strtotime($sdateStr);
+               $sdate = new Date();
+               $sdate->setDate($sdateTS, DATE_FORMAT_TIMESTAMP);
+               $values['sdate'] = $sdate;
+
+               $edateStr = implode('/', $values['edate']);
+               $edateTS = strtotime($edateStr);
+               $edate = new Date();
+               $edate->setDate($edateTS, DATE_FORMAT_TIMESTAMP);
+               $values['edate'] = $edate;
+
+               $exdateStr = implode('/', $values['expiration']);
+               $exdateTS = strtotime($exdateStr);
+               $exdate = new Date();
+               $exdate->setDate($exdateTS, DATE_FORMAT_TIMESTAMP);
+               $values['expiration'] = $exdate;
+        if ($deleteImage) {
+                   $values['image'] = null;
+        } else {
+                   $values['image'] = Toolkit_Coupons_ImageFactory::getImage($values);
+        }
+        $values['member'] = $_SESSION['_authsession']['data']['member_id'];
+        $values['active'] = 0;
+               if (ctype_digit((string)$_GET['id'])) {
+                       //      Editing a banner
+                       $coupon =& $cFactory->fetch($dbh, $_GET['id']);
+               } else {
+                       $coupon =& $cFactory->createCoupon($values);
+               }
+
+               if (filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $coupon->setPending(true);
+                       $res = $coupon->update($dbh, $values);
+               } else {
+                       $res = $coupon->save($dbh);
+               }
+               $couponMailerTemplateData->couponId = $coupon->getId();
+
+               return $res;
+       }
+
+    //  }}}
+
+    //  {{{ sendCouponToImageServer()
+
+    /**
+     * Send a coupon image to the image server
+     *
+     * Sets the image name in the submit values, so when saving
+     * the banner, we keep the image that was uploaded.
+     *
+     * Injects the thumbnail image of this uploaded coupon into
+     * the form, this way if validation fails, the thumbnail will
+     * be shown on the form so the user knows they don't have to
+     * re-upload the coupon.
+     *
+     * @param Toolkit_Image_Server $is   Image server
+     * @param string                      $file key of upload in $_FILES super array
+     *
+     * @return void
+     * @access protected
+     */
+       protected function sendCouponToImageServer(
+        Toolkit_Image_Server $is,
+        $file
+    ) {
+               $oldCoupon =& $this->getSubmitValue('image');
+               if (!empty($oldCoupon)) {
+                       $is->imageDelete($oldCoupon);
+               }
+
+               $imgTag = '<img src="%s%s">';
+               $name = $is->imageUpload($file);
+
+               $htmlImg = sprintf($imgTag, COUPON_THUMB, $name);
+
+               $currImg =& $this->getElement('current_image_rmv');
+               $currImg->setValue($htmlImg);
+
+               $fileName =& $this->getElement('image');
+               $fileName->setValue($name);
+               $this->_submitValues['image'] = $name;
+       }
+
+    //  }}}
+       //      {{{     setupRenderers()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $required
+                       = "<!-- BEGIN required -->\n
+                       <span class=\"req\"> * </span>\n
+                       <!-- END required -->";
+               $error
+                       = "<!-- BEGIN error -->\n
+                       <div class=\"req\"> {error} </div>\n
+                       <!-- END error -->";
+               $renderer->setElementTemplate(
+                       "<tr>\n
+                               <td colspan=\"2\">$required{label}$error{element}</td>\n
+                       </tr>",
+                       'description'
+               );
+               $renderer->setElementTemplate(
+                       "<tr align=\"center\">\n
+                               <td colspan=\"2\">$required{label}$error{element}</td>\n
+                       </tr>",
+                       'submit_rmv'
+               );
+               $renderer->setElementTemplate(
+                       "<tr align=\"center\">\n
+                               <td colspan=\"2\">$required{label}$error{element}</td>\n
+                       </tr>",
+                       'delete_rmv'
+               );
+
+       }
+
+    //  @codeCoverageIgnoreEnd
+       //      }}}
+
+    //  {{{ toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+        *
+        * @param PDO                            $dbh                       Database handler
+        * @param Toolkit_Image_Server           $is                        Image Server
+     * @param Toolkit_Coupons_CouponFactory  $cFactory                  Coupon
+     * @param Toolkit_Members_Coupons_Mailer $mailer                    Mailer
+     * @param stdClass                       &$couponMailerTemplateData Coupon mailer template data
+        *
+        * @return string $output The Form to be rendered or success msg.
+        * @access protected
+        */
+       public function toHtml(
+               PDO $dbh,
+               Toolkit_Image_Server $is,
+               Toolkit_Coupons_CouponFactory $cFactory,
+               Toolkit_Members_Coupons_Mailer $mailer,
+               stdClass &$couponMailerTemplateData
+       ) {
+               //$GLOBALS['styleSheets'][] = BASE_URL . 'css/contactform.css';
+               $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/textlimit.js';
+               $GLOBALS['bottomScripts'][] = BASE_URL . 'libjs/couponLimitText.js';
+
+        //  Handle Deleting coupon.
+        if (   $this->isSubmitted()
+            && ctype_digit($_GET['id'])
+        ) {
+            if ($this->getSubmitValue('delete_rmv')) {
+                $coupon = $cFactory->fetch($dbh, $_GET['id']);
+                if ($coupon instanceof Toolkit_Coupons_Coupon) {
+                    if ($coupon->delete($dbh, $is)) {
+                        return 'Coupon successfully deleted.';
+                    }
+                } else {
+                    //  the coupon has already been deleted or doesn't exist.
+                    return "The coupon has already been deleted or doesn't exists.";
+                }
+            }
+        }
+
+               $this->setupRenderers();
+               $uploadedNewCouponImg
+                       = (   $this->isSubmitted()
+                          && is_uploaded_file($_FILES['file_rmv']['tmp_name'])
+               );
+        if ($_POST['del_image_rmv'] && $_POST['old_image_rmv']) {
+            $is->imageDelete($_POST['old_image_rmv']);
+        }
+               if ($uploadedNewCouponImg) {
+                       $this->sendCouponToImageServer($is, 'file_rmv');
+               }
+               if ($this->validate()) {
+                       $this->cleanForm();
+
+                       $submitValues = $this->getSubmitValues();
+                       if ($this->_processData(
+                               $dbh,
+                               $submitValues,
+                               $cFactory,
+                               $couponMailerTemplateData
+                       )
+                       ) {
+                               if ('' != MEMBERS_COUPON_NOTIFICATION_EMAIL) {
+                                       $mailer->sendNotification(
+                                               array(MEMBERS_COUPON_NOTIFICATION_EMAIL),
+                                               $couponMailerTemplateData
+                                       );
+                               }
+                               $this->freeze();
+                               $output = $this->successMsg;
+                       }
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHTML();
+               } else {
+                       $output = parent::toHTML();
+               }
+               return $output;
+       }
+
+    //  }}}
+}
diff --git a/Toolkit/Members/Coupons/Mailer.php b/Toolkit/Members/Coupons/Mailer.php
new file mode 100644 (file)
index 0000000..dd0d217
--- /dev/null
@@ -0,0 +1,129 @@
+<?php
+
+/**
+ * Updated member coupon notification mailer
+ *
+ * Sends email to site admin when a member add / updates a coupon
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id:$
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Updated member coupon notification mailer
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Coupons_Mailer
+{
+       //      {{{     properties
+
+    /**
+     * Templating engine
+     * @var    HTML_Template_Flexy
+     * @access private
+     */
+       private $_tEngine;
+
+    /**
+     * Mail Mime object
+     * @var    Mail_mime
+     * @access private
+     */
+       private $_mailMime;
+
+    /**
+     * mailer
+     * @var    Mail
+     * @access private
+     */
+       private $_mailer;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * constructor
+     *
+     * @param HTML_Template_Flexy $tEngine   Templating engine to generate html email
+     * @param Mail_mime           &$mailMime class to create MIME messages
+     * @param Mail                &$mailer   internal PHP-mail() implementation of the PEAR Mail:: interface.
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+               HTML_Template_Flexy $tEngine,
+               Mail_mime &$mailMime,
+               Mail &$mailer
+       ) {
+               $this->_tEngine  = $tEngine;
+               $this->_mailMime = $mailMime;
+               $this->_mailer   = $mailer;
+       }
+
+       //      }}}
+    /**
+     * Sends notification of member coupon updates
+     *
+     * @param array    $recipients                array of recipients to send mail to
+     * @param stdClass &$couponMailerTemplateData template data object used to populate template variables
+        *
+     * @return boolean True or False depending on result of mailing
+     * @access public
+     * @throws RuntimeException if no recipients present
+     */
+       public function sendNotification(
+               array $recipients,
+               stdClass &$couponMailerTemplateData
+       ) {
+               if (empty($recipients)) {
+                       throw new RuntimeException('Array of recipients cannot be empty');
+               }
+               $page = new stdClass();
+
+               $page->email_from = DO_NOT_REPLY_EMAIL;
+               $page->subject = 'Member Coupon Notification from ' . SITENAME;
+               $page->member_name = $couponMailerTemplateData->memberName;
+               $page->coupon_id = $couponMailerTemplateData->couponId;
+               $page->edit = $couponMailerTemplateData->editingCoupon;
+               $page->baseUrl = BASE_URL;
+
+               $this->_mailMime->setHTMLBody($this->_tEngine->bufferedOutputObject($page));
+
+               $body = $this->_mailMime->get();
+               $hdrs = $this->_mailMime->headers(
+                       array(
+                               'From' => DO_NOT_REPLY_EMAIL,
+                               'Subject' => 'Member Coupon from ' . SITENAME,
+                               'Reply-To' => DO_NOT_REPLY_EMAIL
+                       )
+               );
+
+               $res = $this->_mailer->send($recipients, $hdrs, $body);
+               if (!PEAR::isError($res)) {
+                       return true;
+               } else {
+                       $logger =& Toolkit_Logger::getLogger();
+                       $logger->warning("Unable to mail coupon notification {$res->getMessage()}");
+                       return false;
+               }
+       }
+}
diff --git a/Toolkit/Members/Database/application.sql b/Toolkit/Members/Database/application.sql
new file mode 100644 (file)
index 0000000..5152ffb
--- /dev/null
@@ -0,0 +1,55 @@
+CREATE SCHEMA members;
+GRANT ALL ON SCHEMA members TO nobody;
+
+--
+-- Tables
+--
+\i ./tables/state.sql
+\i ./tables/region.sql
+\i ./tables/county.sql
+\i ./tables/city.sql
+\i ./tables/ccard_type.sql
+\i ./tables/member.sql
+\i ./tables/member_accommodations.sql
+\i ./tables/amenity.sql
+\i ./tables/member_amenity.sql
+\i ./tables/category.sql
+\i ./tables/category_amenities.sql
+\i ./tables/bus_cat_member.sql
+\i ./tables/member_category.sql
+\i ./tables/member_ccard_type.sql
+\i ./tables/member_contacts.sql
+\i ./tables/member_files.sql
+\i ./tables/member_golf.sql
+\i ./tables/member_packages.sql
+\i ./tables/member_photos.sql
+\i ./tables/member_restaurants.sql
+\i ./tables/member_updates.sql
+\i ./tables/member_session.sql
+\i ./tables/exploded_members_name.sql
+\i ./tables/member_newsletters.sql
+\i ./tables/member_last_updates.sql
+\i ./tables/exposure.sql
+\i ./tables/member_categories2toolbox_pages.sql
+\i ./tables/member_categories2toolbox_pages_draft.sql
+\i ./tables/banners2membercategories.sql
+\i ./tables/member_leads.sql
+\i ./tables/member_regions2toolbox_pages.sql
+\i ./tables/member_regions2toolbox_pages_draft.sql
+\i ./tables/streamsend.sql
+
+--
+-- Utilities
+--
+\i ./utilities/unnest.sql
+--
+-- Procedures
+--
+\i ./procedures/last_record_update_timestamp.sql
+\i ./procedures/explode_members_name_PRE_8.3.sql
+
+--
+-- Modules
+--
+\i /usr/share/postgresql/8.4/contrib/tablefunc.sql
+\i /usr/share/postgresql/8.4/contrib/fuzzystrmatch.sql
diff --git a/Toolkit/Members/Database/procedures/explode_members_name_POST_8.3.sql b/Toolkit/Members/Database/procedures/explode_members_name_POST_8.3.sql
new file mode 100644 (file)
index 0000000..a13e23d
--- /dev/null
@@ -0,0 +1,49 @@
+--DROP LANGUALGE plpgsql;
+CREATE LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS explode_members_name ON members.member;
+
+--
+-- Function and trigger to split the member names on INSERT and UPDATE
+-- so we can do reverse name search lookups ie("john doe" vs "doe john").
+--
+CREATE OR REPLACE FUNCTION members.explode_members_name() RETURNS TRIGGER AS $explode_members_name$
+       DECLARE
+               noPunct    text;
+               alNumSpace text;
+       BEGIN
+
+               noPunct = regexp_replace(NEW.member_name, '[[:punct:]]', '', 'g');
+               alNumSpace = regexp_replace(noPunct, '[^[:alnum:] ]', '', 'g');
+
+               IF (TG_OP = 'INSERT') THEN
+
+                       INSERT INTO members.exploded_members_name (part, mid)
+                       SELECT regexp_split_to_table(alNumSpace, E'\\s+'), NEW.member_id;
+
+               ELSEIF (TG_OP = 'UPDATE') THEN
+
+                       --
+                       -- Only update the member name if they are not the same.
+                       --
+                       IF NEW.member_name != OLD.member_name THEN
+
+                               --
+                               -- Remove old name parts first so we can load a fresh copy.
+                               --
+                               DELETE FROM members.exploded_members_name
+                                WHERE mid = NEW.member_id;
+
+                               INSERT INTO members.exploded_members_name (part, mid)
+                               SELECT regexp_split_to_table(alNumSpace, E'\\s+'), NEW.member_id;
+
+                       END IF;
+
+               END IF;
+               RETURN NULL;
+       END;
+$explode_members_name$ LANGUAGE plpgsql;
+
+CREATE TRIGGER explode_members_name
+AFTER INSERT OR UPDATE ON members.member
+       FOR EACH ROW EXECUTE PROCEDURE members.explode_members_name();
diff --git a/Toolkit/Members/Database/procedures/explode_members_name_PRE_8.3.sql b/Toolkit/Members/Database/procedures/explode_members_name_PRE_8.3.sql
new file mode 100644 (file)
index 0000000..f96641a
--- /dev/null
@@ -0,0 +1,56 @@
+--
+-- This function requires the unnest utility function.
+-- That function can be found in the Members/Database/utilities folder
+--
+
+--DROP LANGUALGE plpgsql;
+CREATE LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS explode_members_name ON members.member;
+
+--
+-- Function and trigger to split the member names on INSERT and UPDATE
+-- so we can do reverse name search lookups ie("john doe" vs "doe john").
+--
+CREATE OR REPLACE FUNCTION members.explode_members_name() RETURNS TRIGGER AS $explode_members_name$
+       DECLARE
+               noPunct       text;
+               noMultiSpace text;
+               alNumSpace    text;
+       BEGIN
+
+               noPunct      = regexp_replace(NEW.member_name, '[[:punct:]]', '', 'g');
+               noMultiSpace = regexp_replace(noPunct, '[[:space:]]+', ' ', 'g');
+               alNumSpace   = regexp_replace(noMultiSpace, '[^[:alnum:] ]', '', 'g');
+
+               IF (TG_OP = 'INSERT') THEN
+
+                       INSERT INTO members.exploded_members_name (part, mid)
+                       SELECT unnest(string_to_array(alNumSpace, ' ')), NEW.member_id;
+
+               ELSEIF (TG_OP = 'UPDATE') THEN
+
+                       --
+                       -- Only update the member name if they are not the same.
+                       --
+                       IF NEW.member_name != OLD.member_name THEN
+
+                               --
+                               -- Remove old name parts first so we can load a fresh copy.
+                               --
+                               DELETE FROM members.exploded_members_name
+                                WHERE mid = NEW.member_id;
+
+                               INSERT INTO members.exploded_members_name (part, mid)
+                               SELECT unnest(string_to_array(alNumSpace, ' ')), NEW.member_id;
+
+                       END IF;
+
+               END IF;
+               RETURN NULL;
+       END;
+$explode_members_name$ LANGUAGE plpgsql;
+
+CREATE TRIGGER explode_members_name
+AFTER INSERT OR UPDATE ON members.member
+       FOR EACH ROW EXECUTE PROCEDURE members.explode_members_name();
diff --git a/Toolkit/Members/Database/procedures/last_record_update_timestamp.sql b/Toolkit/Members/Database/procedures/last_record_update_timestamp.sql
new file mode 100644 (file)
index 0000000..3c785b5
--- /dev/null
@@ -0,0 +1,77 @@
+--DROP LANGUAGE plpgsql;
+CREATE LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS last_record_update_timestamp ON members.member;
+DROP TRIGGER IF EXISTS last_record_update_timestamp ON members.member_photos;
+DROP TRIGGER IF EXISTS last_record_update_timestamp ON members.member_files;
+DROP TRIGGER IF EXISTS last_record_update_timestamp ON members.member_contacts;
+
+--
+-- Function and trigger adding a timestamp to the member record
+-- everytime it is updated.
+--
+CREATE OR REPLACE FUNCTION members.last_record_update_timestamp() RETURNS TRIGGER AS $last_record_update_timestamp$
+       DECLARE
+               mid INTEGER; -- Member ID
+               rid INTEGER; -- Record ID
+       BEGIN
+               -- Get the right member_id from the correct record variable OLD/NEW
+
+               IF (TG_OP = 'DELETE') THEN
+                       -- The variable NEW does not exist on DELETE operations
+                       -- need a special control structure to obtain the member_id
+                       mid := OLD.member_id;
+                       IF (TG_TABLE_NAME <> 'member') THEN
+                               rid := OLD.id;
+                       ELSE
+                               rid := NULL;
+                       END IF;
+               ELSE
+                       -- The variable OLD does not exist on INSERT operations
+                       -- need a special control structure to obtain the member_id
+                       mid := NEW.member_id;
+                       IF (TG_TABLE_NAME <> 'member') THEN
+                               rid := NEW.id;
+                       ELSE
+                               rid := NULL;
+                       END IF;
+               END IF;
+
+               INSERT INTO members.member_last_updates (
+                                       member_id,
+                                       timestamp,
+                                       "table",
+                                       operation,
+                                       record_id)
+             VALUES (
+                                        mid,
+                                        CURRENT_TIMESTAMP,
+                                        TG_TABLE_NAME,
+                                        TG_OP,
+                                        rid
+                                       );
+
+               -- Return the correct record variable
+               IF (TG_OP = 'DELETE') THEN
+                       RETURN OLD;
+               ELSE
+                       RETURN NEW;
+               END IF;
+       END;
+$last_record_update_timestamp$ LANGUAGE plpgsql;
+
+CREATE TRIGGER last_record_update_timestamp 
+AFTER INSERT OR UPDATE ON members.member
+       FOR EACH ROW EXECUTE PROCEDURE members.last_record_update_timestamp();
+
+CREATE TRIGGER last_record_update_timestamp
+AFTER INSERT OR UPDATE ON members.member_photos
+       FOR EACH ROW EXECUTE PROCEDURE members.last_record_update_timestamp();
+
+CREATE TRIGGER last_record_update_timestamp
+AFTER INSERT OR UPDATE ON members.member_files
+       FOR EACH ROW EXECUTE PROCEDURE members.last_record_update_timestamp();
+
+CREATE TRIGGER last_record_update_timestamp
+AFTER INSERT OR UPDATE ON members.member_contacts
+       FOR EACH ROW EXECUTE PROCEDURE members.last_record_update_timestamp();
diff --git a/Toolkit/Members/Database/removeApplication.sql b/Toolkit/Members/Database/removeApplication.sql
new file mode 100644 (file)
index 0000000..cd8b76d
--- /dev/null
@@ -0,0 +1,11 @@
+--
+--     This will drop everything in the members schema.
+--     Nothing better be in here except members related objects
+--     or it will be dropped
+--
+--     The force is strong w/ this one, use it wisely.
+--
+DROP SCHEMA IF EXISTS members CASCADE;
+
+DROP TABLE IF EXISTS toolbox.member_categories2toolbox_pages;
+DROP TABLE IF EXISTS toolbox.member_categories2toolbox_pages_draft;
diff --git a/Toolkit/Members/Database/tables/amenity.sql b/Toolkit/Members/Database/tables/amenity.sql
new file mode 100644 (file)
index 0000000..486833f
--- /dev/null
@@ -0,0 +1,12 @@
+DROP TABLE IF EXISTS members.amenity CASCADE;
+
+CREATE TABLE members.amenity
+(amenity_id SERIAL,
+ amenity_name TEXT,
+ amenity_icon TEXT,
+ display_form BOOLEAN,
+ PRIMARY KEY (amenity_id)
+);
+
+GRANT ALL ON members.amenity_amenity_id_seq TO nobody;
+GRANT ALL ON members.amenity TO nobody;
diff --git a/Toolkit/Members/Database/tables/banners2membercategories.sql b/Toolkit/Members/Database/tables/banners2membercategories.sql
new file mode 100644 (file)
index 0000000..09f6d2c
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS members.banners2membercategories CASCADE;
+
+CREATE TABLE members.banners2membercategories
+(bid INTEGER NOT NULL
+       REFERENCES banners.banners (id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ catid INTEGER NOT NULL
+       REFERENCES members.category (category_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE);
+
+GRANT ALL ON members.banners2membercategories TO nobody;
diff --git a/Toolkit/Members/Database/tables/category.sql b/Toolkit/Members/Database/tables/category.sql
new file mode 100644 (file)
index 0000000..b6d5eeb
--- /dev/null
@@ -0,0 +1,26 @@
+DROP TABLE IF EXISTS members.category CASCADE;
+--
+-- This table requires the connectby module found in the
+-- /usr/share/postgresql/*/contrib/tablefunc.sql file
+--
+
+CREATE TABLE members.category
+(category_id SERIAL,
+ name TEXT NOT NULL,
+ parent_id INTEGER DEFAULT 0,
+ pos INTEGER DEFAULT 1,
+ accommodations BOOLEAN DEFAULT FALSE,
+ restaurant BOOLEAN DEFAULT FALSE,
+ golf BOOLEAN DEFAULT FALSE,
+ code INTEGER,
+ PRIMARY KEY (category_id));
+
+DELETE FROM members.category;
+ALTER SEQUENCE members.category_category_id_seq RESTART WITH 1;
+INSERT INTO members.category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Parent', 0, 1, true, true, true);
+INSERT INTO members.category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Child', 1, 1, false, false, false);
+INSERT INTO members.category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Sibling', 1, 2, false, true, false);
+INSERT INTO members.category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Grand Child', 2, 1, false, false, true);
+
+GRANT ALL ON members.category_category_id_seq TO nobody;
+GRANT ALL ON members.category TO nobody;
diff --git a/Toolkit/Members/Database/tables/category_amenities.sql b/Toolkit/Members/Database/tables/category_amenities.sql
new file mode 100644 (file)
index 0000000..b7d2a70
--- /dev/null
@@ -0,0 +1,14 @@
+DROP TABLE IF EXISTS members.category_amenities CASCADE;
+
+CREATE TABLE members.category_amenities
+(category_id INTEGER NOT NULL
+       REFERENCES members.category(category_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ amenity_id INTEGER NOT NULL
+       REFERENCES members.amenity(amenity_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (category_id, amenity_id));
+
+GRANT ALL ON members.category_amenities TO nobody;
diff --git a/Toolkit/Members/Database/tables/ccard_type.sql b/Toolkit/Members/Database/tables/ccard_type.sql
new file mode 100644 (file)
index 0000000..905c37b
--- /dev/null
@@ -0,0 +1,18 @@
+DROP TABLE IF EXISTS members.ccard_type CASCADE;
+
+CREATE TABLE members.ccard_type
+(ccard_type_id SERIAL,
+ ccard_type_name TEXT,
+ ccard_type_icon TEXT,
+ PRIMARY KEY (ccard_type_id));
+
+DELETE FROM members.ccard_type;
+ALTER SEQUENCE members.ccard_type_ccard_type_id_seq RESTART WITH 1;
+INSERT INTO members.ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Visa', 'cardvisa.gif');
+INSERT INTO members.ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Master Card', 'cardmaster.gif');
+INSERT INTO members.ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Discover', 'carddiscover.gif');
+INSERT INTO members.ccard_type(ccard_type_name, ccard_type_icon) VALUES ('American Express', 'cardamex.gif');
+INSERT INTO members.ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Diners', 'carddiner.gif');
+
+GRANT ALL ON members.ccard_type_ccard_type_id_seq TO nobody;
+GRANT ALL ON members.ccard_type TO nobody;
diff --git a/Toolkit/Members/Database/tables/city.sql b/Toolkit/Members/Database/tables/city.sql
new file mode 100644 (file)
index 0000000..3192c42
--- /dev/null
@@ -0,0 +1,30 @@
+DROP TABLE IF EXISTS members.city CASCADE;
+
+CREATE TABLE members.city
+(city_id SERIAL,
+ state_id INTEGER NOT NULL
+       REFERENCES members.state(state_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ city_name TEXT,
+ county_id INTEGER
+       REFERENCES members.county(county_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ region_id INTEGER
+       REFERENCES members.region(region_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ description TEXT,
+ image TEXT,
+ lat DOUBLE PRECISION,
+ lon DOUBLE PRECISION,
+ UNIQUE (state_id, city_name),
+ PRIMARY KEY (city_id));
+
+DELETE FROM members.city;
+ALTER SEQUENCE members.city_city_id_seq RESTART WITH 1;
+INSERT INTO members.city (state_id, city_name, county_id, region_id) VALUES (1, 'Default Temp City', 1, 1);
+
+GRANT ALL ON members.city_city_id_seq TO nobody;
+GRANT ALL ON members.city TO nobody;
diff --git a/Toolkit/Members/Database/tables/county.sql b/Toolkit/Members/Database/tables/county.sql
new file mode 100644 (file)
index 0000000..8d87f53
--- /dev/null
@@ -0,0 +1,22 @@
+DROP TABLE IF EXISTS members.county CASCADE;
+
+CREATE TABLE members.county
+(county_id SERIAL,
+ state_id INTEGER NOT NULL
+       REFERENCES members.state(state_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ county_name TEXT,
+ region_id INTEGER
+       REFERENCES members.region(region_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (county_id)
+);
+
+DELETE FROM members.county;
+ALTER SEQUENCE members.county_county_id_seq RESTART WITH 1;
+INSERT INTO members.county(state_id, county_name, region_id) VALUES (1, 'Default Temp County', 1);
+
+GRANT ALL ON members.county_county_id_seq TO nobody;
+GRANT ALL ON members.county TO nobody;
diff --git a/Toolkit/Members/Database/tables/exploded_members_name.sql b/Toolkit/Members/Database/tables/exploded_members_name.sql
new file mode 100644 (file)
index 0000000..e3c7177
--- /dev/null
@@ -0,0 +1,20 @@
+DROP TABLE IF EXISTS members.exploded_members_name CASCADE;
+
+--
+-- This table requires the procedures/explode_members_name.sql function
+-- and trigger as well as the metaphone and soundex module found in
+-- /usr/share/postgres/*/contrib/fuzzystrmatch.sql
+--
+
+DROP TABLE IF EXISTS members.exploded_members_name;
+
+CREATE TABLE members.exploded_members_name
+(part TEXT NOT NULL,
+ mid INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON DELETE CASCADE
+       ON UPDATE CASCADE);
+
+CREATE INDEX member_name_part_idx ON members.exploded_members_name (part);
+
+GRANT ALL ON members.exploded_members_name TO nobody;
diff --git a/Toolkit/Members/Database/tables/exposure.sql b/Toolkit/Members/Database/tables/exposure.sql
new file mode 100644 (file)
index 0000000..3b16b55
--- /dev/null
@@ -0,0 +1,18 @@
+DROP TABLE IF EXISTS members.exposure CASCADE;
+
+CREATE TABLE members.exposure
+(exposure_id SERIAL,
+ list INTEGER DEFAULT 0,
+ click INTEGER DEFAULT 0,
+ detail INTEGER DEFAULT 0,
+ edate DATE DEFAULT CURRENT_DATE,
+ member_id INTEGER,
+ PRIMARY KEY (exposure_id));
+
+CREATE INDEX exposure_edate_idx ON members.exposure (edate);
+CREATE INDEX exposure_edate_month_idx ON members.exposure (date_part('month', edate));
+CREATE INDEX exposure_edate_year_idx ON members.exposure (date_part('year', edate));
+CREATE INDEX exposure_member_id_idx ON members.exposure (member_id);
+
+GRANT ALL ON members.exposure_exposure_id_seq TO nobody;
+GRANT ALL ON members.exposure TO nobody;
diff --git a/Toolkit/Members/Database/tables/member.sql b/Toolkit/Members/Database/tables/member.sql
new file mode 100644 (file)
index 0000000..c72352b
--- /dev/null
@@ -0,0 +1,82 @@
+DROP TABLE IF EXISTS members.member CASCADE;
+
+--
+-- This table requires the procedures/last_record_update_timestamp.sql
+-- function and trigger
+--
+
+CREATE TABLE members.member
+(member_id SERIAL,
+ member_name TEXT UNIQUE,
+ member_login TEXT UNIQUE,
+ member_passwd TEXT,
+ street TEXT,
+ lat DOUBLE PRECISION,
+ lon DOUBLE PRECISION,
+ country TEXT,
+ phone TEXT,
+ fax TEXT,
+ process_email TEXT,
+ url TEXT,
+ city TEXT,
+ city_id INTEGER
+       REFERENCES members.city(city_id)
+       ON UPDATE CASCADE
+       ON DELETE SET NULL,
+ state TEXT,
+ state_id INTEGER
+       REFERENCES members.state(state_id)
+       ON UPDATE CASCADE
+       ON DELETE SET NULL,
+ description TEXT,
+ create_date DATE DEFAULT CURRENT_DATE,
+ zip TEXT,
+ toll_free TEXT,
+ member_contact_email TEXT,
+ spotlight BOOLEAN,
+ logo TEXT,
+ mailing_address TEXT,
+ primary_contact TEXT,
+ primary_contact_fname TEXT,
+ primary_contact_lname TEXT,
+ active BOOLEAN DEFAULT FALSE,
+ mailing_city TEXT,
+ mailing_city_id INTEGER
+       REFERENCES members.city(city_id)
+       ON UPDATE CASCADE
+       ON DELETE SET NULL,
+ mailing_state_id INTEGER
+       REFERENCES members.state(state_id)
+       ON UPDATE CASCADE
+       ON DELETE SET NULL,
+ mailing_zip TEXT,
+ join_date DATE,
+ region INTEGER
+       REFERENCES members.region(region_id)
+       ON UPDATE CASCADE
+       ON DELETE SET NULL,
+ new_member BOOLEAN DEFAULT FALSE,
+ facebook TEXT,
+ twitter TEXT,
+ myspace TEXT,
+ linkedin TEXT,
+ blog TEXT,
+ youtube TEXT,
+ pinterest TEXT,
+ last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ reviewed BOOLEAN,
+ paypal TEXT,
+ distance TEXT,
+ trailtype TEXT,
+ terrain TEXT,
+ dogs TEXT,
+ difficulty TEXT,
+ county INTEGER,
+ PRIMARY KEY (member_id)
+);
+
+CREATE INDEX member_state_id ON members.member (state_id);
+CREATE INDEX member_city_id ON members.member (city_id);
+
+GRANT ALL ON members.member_member_id_seq TO nobody;
+GRANT ALL ON members.member TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_accommodations.sql b/Toolkit/Members/Database/tables/member_accommodations.sql
new file mode 100644 (file)
index 0000000..b651ff9
--- /dev/null
@@ -0,0 +1,17 @@
+DROP TABLE IF EXISTS members.member_accommodations CASCADE;
+
+CREATE TABLE members.member_accommodations
+(id SERIAL,
+ reservation_url TEXT,
+ reservation_id        TEXT,
+ num_rooms INTEGER,
+ year_round BOOLEAN    DEFAULT FALSE,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id)
+);
+
+GRANT ALL ON members.member_accommodations_id_seq TO nobody;
+GRANT ALL ON members.member_accommodations TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_amenity.sql b/Toolkit/Members/Database/tables/member_amenity.sql
new file mode 100644 (file)
index 0000000..5b8031d
--- /dev/null
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS members.member_amenity CASCADE;
+
+CREATE TABLE members.member_amenity
+(member_amenity_id SERIAL,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ amenity_id INTEGER NOT NULL
+       REFERENCES members.amenity(amenity_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (member_amenity_id));
+
+GRANT ALL ON members.member_amenity_member_amenity_id_seq TO nobody;
+GRANT ALL ON members.member_amenity TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_categories2toolbox_pages.sql b/Toolkit/Members/Database/tables/member_categories2toolbox_pages.sql
new file mode 100644 (file)
index 0000000..b2b274a
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS toolbox.member_categories2toolbox_pages CASCADE;
+
+CREATE TABLE toolbox.member_categories2toolbox_pages
+(page INTEGER NOT NULL
+       REFERENCES toolbox.pages (id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ category INTEGER NOT NULL
+       REFERENCES members.category (category_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE);
+
+GRANT ALL ON toolbox.member_categories2toolbox_pages TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_categories2toolbox_pages_draft.sql b/Toolkit/Members/Database/tables/member_categories2toolbox_pages_draft.sql
new file mode 100644 (file)
index 0000000..8b8cd98
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS toolbox.member_categories2toolbox_pages_draft CASCADE;
+
+CREATE TABLE toolbox.member_categories2toolbox_pages_draft
+(page INTEGER NOT NULL
+       REFERENCES toolbox.pages_draft (id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ category INTEGER NOT NULL
+       REFERENCES members.category (category_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE);
+
+GRANT ALL ON toolbox.member_categories2toolbox_pages_draft TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_category.sql b/Toolkit/Members/Database/tables/member_category.sql
new file mode 100644 (file)
index 0000000..d5f99d5
--- /dev/null
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS members.member_category CASCADE;
+
+CREATE TABLE members.member_category
+(member_category_id    SERIAL,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ category_id INTEGER NOT NULL
+       REFERENCES members.category(category_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (member_category_id));
+
+GRANT ALL ON members.member_category_member_category_id_seq TO nobody;
+GRANT ALL ON members.member_category TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_ccard_type.sql b/Toolkit/Members/Database/tables/member_ccard_type.sql
new file mode 100644 (file)
index 0000000..1758637
--- /dev/null
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS members.member_ccard_type CASCADE;
+
+CREATE TABLE members.member_ccard_type
+(member_ccard_type_id SERIAL,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ ccard_type_id INTEGER NOT NULL
+       REFERENCES members.ccard_type(ccard_type_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (member_ccard_type_id));
+
+GRANT ALL ON members.member_ccard_type_member_ccard_type_id_seq TO nobody;
+GRANT ALL ON members.member_ccard_type TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_contacts.sql b/Toolkit/Members/Database/tables/member_contacts.sql
new file mode 100644 (file)
index 0000000..150be14
--- /dev/null
@@ -0,0 +1,18 @@
+DROP TABLE IF EXISTS members.member_contacts CASCADE;
+
+CREATE TABLE members.member_contacts
+(id SERIAL,
+ title TEXT,
+ fname TEXT NOT NULL,
+ lname TEXT NOT NULL,
+ email TEXT,
+ phone TEXT,
+ send_mail BOOLEAN DEFAULT FALSE,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id));
+
+GRANT ALL ON members.member_contacts_id_seq TO nobody;
+GRANT ALL ON members.member_contacts TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_files.sql b/Toolkit/Members/Database/tables/member_files.sql
new file mode 100644 (file)
index 0000000..5f8367f
--- /dev/null
@@ -0,0 +1,19 @@
+DROP TABLE IF EXISTS members.member_files CASCADE;
+
+CREATE TABLE members.member_files
+(id SERIAL,
+ file_contents TEXT,
+ create_date DATE DEFAULT CURRENT_DATE,
+ original_name TEXT NOT NULl,
+ "size" INTEGER NOT NULL,
+ file_name TEXT NOT NULL,
+ name_on_disk TEXT NOT NULL,
+ pending BOOLEAN DEFAULT true,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id));
+
+GRANT ALL ON members.member_files_id_seq TO nobody;
+GRANT ALL ON members.member_files TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_golf.sql b/Toolkit/Members/Database/tables/member_golf.sql
new file mode 100644 (file)
index 0000000..6e0b69f
--- /dev/null
@@ -0,0 +1,19 @@
+DROP TABLE IF EXISTS members.member_golf CASCADE;
+
+CREATE TABLE members.member_golf
+(id SERIAL,
+ par TEXT,
+ yardage TEXT,
+ course_rating TEXT,
+ slope_rating TEXT,
+ walking_course BOOLEAN DEFAULT FALSE,
+ holes18 TEXT,
+ holes9 TEXT,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id));
+
+GRANT ALL ON members.member_golf_id_seq TO nobody;
+GRANT ALL ON members.member_golf TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_last_updates.sql b/Toolkit/Members/Database/tables/member_last_updates.sql
new file mode 100644 (file)
index 0000000..5ea8541
--- /dev/null
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS members.member_last_updates CASCADE;
+
+CREATE TABLE members.member_last_updates
+(member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ "timestamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ "table"     TEXT NOT NULL,
+ operation TEXT NOT NULL,
+ record_id INTEGER);
+
+CREATE INDEX member_last_updates_member_id_idx ON members.member_last_updates (member_id);
+CREATE INDEX member_last_updates_timestamp_idx ON members.member_last_updates (timestamp);
+
+GRANT ALL ON members.member_last_updates TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_leads.sql b/Toolkit/Members/Database/tables/member_leads.sql
new file mode 100644 (file)
index 0000000..ddc903f
--- /dev/null
@@ -0,0 +1,10 @@
+CREATE TABLE members.member_leads (
+    id SERIAL,
+    member_id INT
+      REFERENCES members.member(member_id)
+      ON DELETE CASCADE,
+    query text
+);
+CREATE UNIQUE INDEX members.member_leads_member_id ON member_leads(member_id);
+GRANT ALL ON members.member_leads TO nobody;
+GRANT ALL ON members.member_leads_id_seq TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_newsletters.sql b/Toolkit/Members/Database/tables/member_newsletters.sql
new file mode 100644 (file)
index 0000000..3527932
--- /dev/null
@@ -0,0 +1,15 @@
+DROP TABLE IF EXISTS members.member_newsletters CASCADE;
+
+CREATE TABLE members.member_newsletters
+(id SERIAL,
+ subject TEXT,
+ response TEXT,
+ mailout date 
+    DEFAULT current_date,
+ last_update DATE 
+    DEFAULT current_date,
+ archived BOOLEAN,
+PRIMARY KEY (id));
+
+GRANT ALL ON members.member_newsletters TO nobody;
+GRANT ALL ON members.member_newsletters_id_seq TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_packages.sql b/Toolkit/Members/Database/tables/member_packages.sql
new file mode 100644 (file)
index 0000000..3103415
--- /dev/null
@@ -0,0 +1,20 @@
+DROP TABLE IF EXISTS members.member_packages CASCADE;
+
+CREATE TABLE members.member_packages
+(id SERIAL,
+ title TEXT,
+ description TEXT,
+ image TEXT,
+ "type" TEXT,
+ pending BOOLEAN DEFAULT TRUE,
+ pos INTEGER,
+ sdate DATE,
+ edate DATE,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id));
+
+GRANT ALL ON members.member_packages_id_seq TO nobody;
+GRANT ALL ON members.member_packages TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_photos.sql b/Toolkit/Members/Database/tables/member_photos.sql
new file mode 100644 (file)
index 0000000..08cc3cd
--- /dev/null
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS members.member_photos CASCADE;
+
+CREATE TABLE members.member_photos
+(id SERIAL,
+ image TEXT NOT NULL,
+ caption TEXT,
+ pending BOOLEAN DEFAULT TRUE,
+ pos INTEGER DEFAULT 1,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id));
+
+GRANT ALL ON members.member_photos_id_seq TO nobody;
+GRANT ALL ON members.member_photos TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_regions2toolbox_pages.sql b/Toolkit/Members/Database/tables/member_regions2toolbox_pages.sql
new file mode 100644 (file)
index 0000000..0a9e5dc
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS toolbox.member_regions2toolbox_pages CASCADE;
+
+CREATE TABLE toolbox.member_regions2toolbox_pages
+(page INTEGER NOT NULL
+       REFERENCES toolbox.pages (id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ region INTEGER NOT NULL
+       REFERENCES members.region (region_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE);
+
+GRANT ALL ON toolbox.member_regions2toolbox_pages TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_regions2toolbox_pages_draft.sql b/Toolkit/Members/Database/tables/member_regions2toolbox_pages_draft.sql
new file mode 100644 (file)
index 0000000..5696183
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS toolbox.member_regions2toolbox_pages_draft CASCADE;
+
+CREATE TABLE toolbox.member_regions2toolbox_pages_draft
+(page INTEGER NOT NULL
+       REFERENCES toolbox.pages (id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ region INTEGER NOT NULL
+       REFERENCES members.region (region_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE);
+
+GRANT ALL ON toolbox.member_regions2toolbox_pages_draft TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_restaurants.sql b/Toolkit/Members/Database/tables/member_restaurants.sql
new file mode 100644 (file)
index 0000000..40f40dc
--- /dev/null
@@ -0,0 +1,26 @@
+DROP TABLE IF EXISTS members.member_restaurants CASCADE;
+
+CREATE TABLE members.member_restaurants
+(id SERIAL,
+ breakfast BOOLEAN DEFAULT FALSE,
+ breakfast_from TEXT,
+ breakfast_to TEXT,
+ brunch BOOLEAN DEFAULT FALSE,
+ brunch_from TEXT,
+ brunch_to TEXT,
+ lunch BOOLEAN DEFAULT FALSE,
+ lunch_from TEXT,
+ lunch_to TEXT,
+ dinner BOOLEAN        DEFAULT FALSE,
+ dinner_from TEXT,
+ dinner_to TEXT,
+ alcohol BOOLEAN DEFAULT FALSE,
+ non_smoking BOOLEAN DEFAULT FALSE,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id));
+
+GRANT ALL ON members.member_restaurants_id_seq TO nobody;
+GRANT ALL ON members.member_restaurants TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_session.sql b/Toolkit/Members/Database/tables/member_session.sql
new file mode 100644 (file)
index 0000000..b42d491
--- /dev/null
@@ -0,0 +1,21 @@
+DROP TABLE IF EXISTS members.member_session CASCADE;
+
+CREATE TABLE members.member_session
+(id SERIAL,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member (member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ contact_id INTEGER NOT NULL
+       REFERENCES contacts.contact (id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ catid INTEGER NOT NULL
+       REFERENCES toolbox.pages (id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ PRIMARY KEY (id)
+);
+
+GRANT ALL ON members.member_session_id_seq TO nobody;
+GRANT ALL ON members.member_session TO nobody;
diff --git a/Toolkit/Members/Database/tables/member_updates.sql b/Toolkit/Members/Database/tables/member_updates.sql
new file mode 100644 (file)
index 0000000..78ed736
--- /dev/null
@@ -0,0 +1,20 @@
+DROP TABLE IF EXISTS members.member_updates CASCADE;
+
+CREATE TABLE members.member_updates
+(id SERIAL,
+ field TEXT,
+ "update" TEXT,
+ alter_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ db_table TEXT NOT NULL,
+ data_type TEXT,
+ label TEXT,
+ foreign_key INTEGER,
+ member_id INTEGER NOT NULL
+       REFERENCES members.member(member_id)
+       ON UPDATE CASCADE
+       ON DELETE CASCADE,
+ field_type TEXT,
+ PRIMARY KEY (id));
+
+GRANT ALL ON members.member_updates_id_seq TO nobody;
+GRANT ALL ON members.member_updates TO nobody;
diff --git a/Toolkit/Members/Database/tables/region.sql b/Toolkit/Members/Database/tables/region.sql
new file mode 100644 (file)
index 0000000..b0e4ea4
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS members.region CASCADE;
+
+CREATE TABLE members.region
+(region_id SERIAL,
+ region_name TEXT UNIQUE,
+ PRIMARY KEY (region_id));
+
+DELETE FROM members.region;
+ALTER SEQUENCE members.region_region_id_seq RESTART WITH 1;
+INSERT INTO members.region (region_name) VALUES ('Default Temp Region');
+
+GRANT ALL ON members.region_region_id_seq TO nobody;
+GRANT ALL ON members.region TO nobody;
diff --git a/Toolkit/Members/Database/tables/state.sql b/Toolkit/Members/Database/tables/state.sql
new file mode 100644 (file)
index 0000000..209a31f
--- /dev/null
@@ -0,0 +1,85 @@
+DROP TABLE IF EXISTS members.state CASCADE;
+
+CREATE TABLE members.state
+(state_id SERIAL,
+ state_name TEXT,
+ state_abb VARCHAR(2),
+ us_state BOOLEAN DEFAULT FALSE,
+ PRIMARY KEY (state_id));
+
+DELETE FROM members.state;
+ALTER SEQUENCE members.state_state_id_seq RESTART WITH 1;
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Alabama', 'AL');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Alaska', 'AK');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Arizona', 'AZ');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Arkansas', 'AR');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'California', 'CA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Colorado', 'CO');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Connecticut', 'CT');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Delaware', 'DE');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'District of Columbia', 'DC');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Florida', 'FL');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Georgia', 'GA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Hawaii', 'HI');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Idaho', 'ID');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Illinois', 'IL');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Indiana', 'IN');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Iowa', 'IA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Kansas', 'KS');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Kentucky', 'KY');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Louisiana', 'LA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Maine', 'ME');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Maryland', 'MD');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Massachusetts', 'MA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Michigan', 'MI');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Minnesota', 'MN');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Mississppi', 'MS');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Missouri', 'MO');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Montana', 'MT');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Nebraska', 'NE');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Nevada', 'NV');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'New Hampshire', 'NH');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'New Jersey', 'NJ');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'New Mexico', 'NM');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'New York', 'NY');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'North Carolina', 'NC');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'North Dakota', 'ND');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Ohio', 'OH');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Oklahoma', 'OK');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Oregon', 'OR');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Pennsylvania', 'PA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Rhode Island', 'RI');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'South Carolina', 'SC');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'South Dakota', 'SD');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Tennessee', 'TN');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Texas', 'TX');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Utah', 'UT');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Vermont', 'VT');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Virginia', 'VA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Washington', 'WA');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'West Virginia', 'WV');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Wisconsin', 'WI');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (true, 'Wyoming', 'WY');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Alberta', 'AB');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'American Samoa', 'AS');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'British Columbia', 'BC');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Federated States of Micronesia', 'FM');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Guam', 'GU');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Manitoba', 'MB');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Marshall Islands', 'MH');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'New Brunswick', 'NB');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Newfoundland', 'NF');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Northern Mariana Islands', 'MP');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Northwest Territories', 'NT');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Nova Scotia', 'NS');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Ontario', 'ON');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Palau', 'PW');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Prince Edward Island', 'PE');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Puerto Rico', 'PR');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Quebec', 'QC');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Saskatchewan', 'SK');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Virgin Islands', 'VI');
+INSERT INTO members.state (us_state, state_name, state_abb) VALUES (false, 'Yukon', 'YT');
+
+GRANT ALL ON members.state_state_id_seq TO nobody;
+GRANT ALL ON members.state TO nobody;
diff --git a/Toolkit/Members/Database/tables/streamsend.sql b/Toolkit/Members/Database/tables/streamsend.sql
new file mode 100644 (file)
index 0000000..7065c61
--- /dev/null
@@ -0,0 +1,21 @@
+CREATE TABLE members.streamsend (
+ id SERIAL,
+ field_id INT NOT NULL,
+ field_name TEXT NOT NULL,
+ option_id INT NOT NULL,
+ option_name TEXT NOT NULL,
+ category_id INT NOT NULL
+    REFERENCES members.category(category_id)
+    ON DELETE CASCADE,
+ parent INT NOT NULL
+    REFERENCES members.category(category_id)
+    ON DELETE CASCADE,
+ PRIMARY KEY (id)
+);
+
+GRANT ALL ON members.streamsend TO nobody;
+GRANT ALL ON members.streamsend_id_seq TO nobody;
+
+CREATE UNIQUE INDEX streamsend_category_id_uniq_inx on members.streamsend (category_id);
+CREATE UNIQUE INDEX streamsend_option_name_uniq_inx on members.streamsend (option_name);
+CREATE UNIQUE INDEX streamsend_option_id_uniq_inx on members.streamsend (option_id);
\ No newline at end of file
diff --git a/Toolkit/Members/Database/utilities/unnest.sql b/Toolkit/Members/Database/utilities/unnest.sql
new file mode 100644 (file)
index 0000000..7859d56
--- /dev/null
@@ -0,0 +1,5 @@
+CREATE OR REPLACE FUNCTION members.unnest(anyarray) RETURNS SETOF anyelement
+LANGUAGE SQL AS $$
+       SELECT $1[i] FROM generate_series(array_lower($1, 1),
+                                                                         array_upper($1, 1)) AS i;
+$$;
diff --git a/Toolkit/Members/Database/utilities/update_exploded_members_name_table_POST_8.3.sql b/Toolkit/Members/Database/utilities/update_exploded_members_name_table_POST_8.3.sql
new file mode 100644 (file)
index 0000000..a1e4cb0
--- /dev/null
@@ -0,0 +1,17 @@
+--
+-- This utility requires postgresq vrs >= 8.3 so you can utilize the
+-- regexp_split_to_table function.  If you don't have access to this version
+-- you can look into the Members/Database/utilities/string_to_rows.sql function
+-- for splitting a string to a table by space.
+--
+
+DELETE FROM exploded_members_name;
+
+INSERT INTO exploded_members_name (part, mid)
+SELECT regexp_split_to_table(
+                  regexp_replace(
+                          regexp_replace(member_name, '[[:punct:]]', '', 'g'),
+                          '[^[:alnum:] ]', '', 'g'
+                  ), E'\\s+'
+       ), member_id
+  FROM member;
diff --git a/Toolkit/Members/Database/utilities/update_exploded_members_name_table_PRE_8.3.sql b/Toolkit/Members/Database/utilities/update_exploded_members_name_table_PRE_8.3.sql
new file mode 100644 (file)
index 0000000..52a725e
--- /dev/null
@@ -0,0 +1,22 @@
+--
+-- This utility requires postgresq vrs >= 8.3 so you can utilize the
+-- regexp_split_to_table function.  If you don't have access to this version
+-- you can look into the Members/Database/utilities/unnest.sql function
+-- for splitting a string to a table by space.
+--
+
+DELETE FROM members.exploded_members_name;
+
+INSERT INTO members.exploded_members_name (part, mid)
+SELECT unnest(
+                string_to_array(
+                        regexp_replace(
+                                regexp_replace(
+                                        regexp_replace(
+                                                member_name, '[[:punct:]]', '', 'g'
+                                        ), '[[:space:]]+', ' ', 'g'
+                                ), '[^[:alnum:] ]', '', 'g'
+                        ), ' '
+                )
+        ), member_id
+FROM members.member;
diff --git a/Toolkit/Members/Display.php b/Toolkit/Members/Display.php
new file mode 100644 (file)
index 0000000..8af6737
--- /dev/null
@@ -0,0 +1,214 @@
+<?php
+
+/**
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Display.php,v 1.38 2010/05/25 14:01:16 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handles Displaying member lists and profile pages
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Display
+{
+       //      {{{     properties
+
+       /**
+        * The Database Handler
+        *
+        * @var object
+        * @access protected
+        */
+       public $dbh;
+
+       /**
+        * Search radius distance
+        * @var integer
+        * @access protected
+        */
+       protected $radius = 35;
+
+       /**
+        * Page catid
+        *
+        * @var integer
+        * @access private
+        */
+       private $_catid;
+
+       /**
+        * Number of records to show per page
+        *
+        * Set to NULL to show all records on one page.
+        *
+        * @var integer
+        * @access protected
+        */
+       protected $limit = 10;
+
+       /**
+        * The list of members
+        *
+        * @var string
+        * @access protected
+        */
+        protected $membersList;
+
+       /**
+        * Whether to randomize the list of members or not
+        *
+        * @var bool
+        * @access protected
+        */
+       protected $randomize = false;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param PDO $pdo PHP Data Object to use for DB calls
+     *
+     * @return void
+     * @access public
+     */
+       public function __construct(PDO $pdo)
+       {
+               $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+       //      {{{     hideUserSearchForm()
+
+       /**
+        * Get the status of displaying the search form for a page
+        *
+        * @return bool true if yes, false otherwise.
+        * @access public
+        */
+       public function hideUserSearchForm()
+       {
+               try {
+                       $sql = "
+                               SELECT CASE
+                                          WHEN no_search_form THEN 1 ELSE 0
+                                          END as no_search_form
+                                 FROM bus_category
+                                WHERE id = :catid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':catid', $this->_catid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+                       return $row['no_search_form'];
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     includeMemberMap()
+
+       /**
+        * include a google map of the members on the page
+        *
+        * @return bool
+        * @access public
+        */
+       public function includeMemberMap()
+       {
+               try {
+                       $sql = "
+                               SELECT CASE
+                                          WHEN include_member_map THEN 1 ELSE 0
+                                          END as include_member_map
+                                 FROM bus_category
+                                WHERE id = :catid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':catid', $this->_catid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+                       return $row['include_member_map'];
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ setCatId()
+
+    /**
+     * Set the catid for the page
+     *
+     * @param integer $catid page id from db
+     *
+     * @return void
+     * @access public
+     * @throws PEAR Error on invalid member id
+     */
+    public function setCatId($catid)
+    {
+               if (!ctype_digit((string)$catid)) {
+                       throw new InvalidArgumentException(
+                               '$catid must be an integer.'
+                       );
+               }
+
+               $this->_catid = $catid;
+    }
+
+    //  }}}
+       //      {{{     setMemberSections()
+
+    /**
+     * Sets an array with all the member category types assigned to a page
+     *
+        * Collects all member categories assigned to a page from the
+        * admin Toolbox.
+     *
+     * @return void
+     * @access public
+     */
+       public function setMemberSections()
+       {
+               try {
+                       $sql = "
+                               SELECT count(*) AS total, p.navigation_name
+                                 FROM member_categories2toolbox_pages mc2tp, pages p
+                                WHERE mc2tp.page = :catid
+                                  AND mc2tp.page = p.id
+                                GROUP BY p.navigation_name";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':catid', $this->_catid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+                       if ($row['total']) {
+                               $this->memberSections[$this->_catid] = $row['navigation_name'];
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditContactForm.php b/Toolkit/Members/EditContactForm.php
new file mode 100644 (file)
index 0000000..41913c0
--- /dev/null
@@ -0,0 +1,276 @@
+<?php
+/**
+ * EditContactForm.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_EditContactForm
+ *
+ * Description for Toolkit_Members_EditContactForm
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_EditContactForm
+       extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+       /**
+        * Some special forms dont utlize this stylesheet
+        * Allow classes to override this setting so it doesn't
+        * get included
+        *
+        * @var boolean
+        * @access protected
+        */
+       protected $includeContactStyleSheet = false;
+
+       //      }}}
+    
+    /**
+     * Description for addMembersContactsToStreamSend
+     * 
+     * @param PDO     $dbh Database handler
+     * @param unknown $mid Member ID
+     * 
+     * @return void
+     * @access public
+     */
+    public function addMemberContactsToStreamSend(PDO $dbh, $mid)
+    {
+        if (   defined('MEMBER_STREAMSEND_API')
+            && MEMBER_STREAMSEND_API
+        ) {
+            // send member to streamsend
+            $memberStreamSend = new Toolkit_Members_StreamSend($dbh);
+            $memberStreamSend->sendMemberContactsByMemberId($mid);
+        }
+    }
+    
+       //      {{{     configureDefaults()
+
+       /**
+        * Configure element default values
+        *
+        * Elements will only have a default value if we are editing
+        * an existing contact
+        *
+     * @param PDO $pdo Datbase handler
+     * 
+        * @return void
+        * @access public
+        */
+       public function configureDefaults(PDO $pdo)
+       {
+               $d = array();
+
+               if ($contactId = filter_input(INPUT_GET, 'cid', FILTER_VALIDATE_INT)) {
+                       $contact = Toolkit_Members_Contact::fetch($pdo, $contactId);
+                       $d['title'] = $contact->getTitle();
+                       $d['fname'] = $contact->getFname();
+                       $d['lname'] = $contact->getLname();
+                       $d['email'] = $contact->getEmail();
+                       $d['phone'] = $contact->getPhone();
+                       $d['send_mail'] = $contact->getCanReceiveMail();
+                       $d['id'] = $contactId;
+                       $d['submit'] = 'Update Contact';
+               } else {
+                       $d['submit'] = 'Create Contact';
+               }
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+       //      {{{     configureElements()
+
+       /**
+        * Configure the elements that will be used on the form
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+               $e = array();
+
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'id'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'title',
+            'display' => 'Title',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'fname',
+            'display' => 'First Name',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'lname',
+            'display' => 'Last Name',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'email',
+            'display' => 'Email',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'phone',
+            'display' => 'Phone',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'advcheckbox',
+            'req' => false,
+            'name' => 'send_mail',
+            'display' => 'Receive Mail',
+            'val' => array(0, 1)
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Submit',
+            'opts' => array('class' => 'submit')
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureForm()
+
+       /**
+        * Wrapper function to handle quickly setting up the form
+     * 
+     * @param PDO $pdo Database handler
+        *
+        * @return void
+        * @access public
+        */
+       public function configureForm(PDO $pdo)
+       {
+               $this->configureElements();
+               $this->configureRules();
+               $this->configureDefaults($pdo);
+       }
+
+       //      }}}
+       //      {{{     configureRules()
+
+       /**
+        *      Configure element rules for form validation
+        *
+        * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+               $this->registeredRules = array('email');
+
+               $r = array();
+               $r[] = array(
+                       'element' => 'email',
+                       'message' => 'ERROR: Invalid Email Address!',
+                       'type' => 'email'
+               );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{     createContact()
+
+    /**
+     * Description for createContact()
+     * 
+     * @param array $values Values array
+     * 
+     * @return \Toolkit_Members_Contact 
+     * @access public
+     */
+       protected function createContact(array $values)
+       {
+               return new Toolkit_Members_Contact(
+                       $values['fname'],
+                       $values['lname'],
+                       $values['title'],
+                       $values['email'],
+                       $values['phone'],
+                       $values['send_mail']
+               );
+       }
+
+       //      }}}
+       //      {{{     toHtml()
+
+    /**
+     * Description for toHtml()
+     * 
+     * @param PDO                            $pdo      database handler
+     * @param HTML_QuickForm_Renderer_Object $renderer Description of $renderer
+     * @param HTML_Template_Flexy            $tpl      Description of $tpl
+     * 
+     * @return string
+     * @access public
+     */
+       public function toHtml(
+               PDO $pdo,
+               HTML_QuickForm_Renderer_Object $renderer,
+               HTML_Template_Flexy $tpl
+       ) {
+               if ($this->validate()) {
+                       $contact = $this->process(array(&$this, 'createContact'));
+
+                       if (ctype_digit($this->getSubmitValue('id'))) {
+                               $contact->update($pdo, $this->getSubmitValue('id'));
+                       } else {
+                               $contact->save($pdo, $_GET['id']);
+                       }
+
+            $this->addMemberContactsToStreamSend($pdo, $_GET['id']);
+
+                       header('Location: ' . $this->getAttribute('action'));
+                       exit();
+               } elseif ($this->isSubmitted()) {
+                       $output = $this->errorMsg;
+               }
+
+               $this->accept($renderer);
+               $view = new stdClass;
+               $view->form = $renderer->toObject();
+               $tpl->compile('editContact.html');
+               $output .= $tpl->bufferedOutputObject($view);
+
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberAmenities.php b/Toolkit/Members/EditMemberAmenities.php
new file mode 100644 (file)
index 0000000..2063eb0
--- /dev/null
@@ -0,0 +1,304 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberAmenities.php,v 1.11 2009/11/16 12:11:39 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_EditMemberAmenities
+       extends Toolkit_Members_EditMemberInfo implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_amenity';
+
+       /**
+        * The name of the template used to render the business info form.
+        *
+        * @var string
+        * @access protected 
+        */
+       protected $formTemplate = 'editAmenities.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *                            
+        * @access public
+        * @see    Toolkit_Members_EditMemberInfo
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form.
+        *
+        * @return array form element default values
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               try {
+            $sql = "
+              SELECT *
+                FROM {$this->tableName}
+                          WHERE member_id = :id ";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $defaults[$row['amenity_id']] = true;
+                       }
+                       $this->setupDefaults($defaults);
+                       return $defaults;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the element definitions to use on the form.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+        //  Element definitions
+        $e = array();
+               $amenities = $this->getAmenities();
+               $half = floor(count($amenities) / 2);
+               $i = 0;
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'row1'
+        );
+               while ($i < $half) {
+                       $e[] = array(
+                'type' => 'checkbox',
+                'req' => false,
+                'name' => $amenities[$i]['amenity_id'],
+                'display' => $amenities[$i++]['amenity_name']
+            );
+               }
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'row2'
+        );
+               while ($i < count($amenities)) {
+                       $e[] = array(
+                'type' => 'checkbox',
+                'req' => false,
+                'name' => $amenities[$i]['amenity_id'],
+                'display' => $amenities[$i++]['amenity_name']
+            );
+               }
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+               $this->setupRules();
+       }
+
+       //      }}}
+
+       //      {{{ getAmenities()
+
+       /**
+        * Gets all the amentities
+        *
+        * @return $a array The array of amenities from the DB.
+        * @access protected
+        */
+       protected function getAmenities()
+       {
+        $a = array();
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM amenity
+                                ORDER BY amenity_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $a[] = $row;
+                       }
+               } catch (PDOException $e) {
+                       $this->handleError($e);
+               }
+               return $a;
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+        * Create a new record in the database from the data on the form
+     * 
+        * @param array $values Form values
+     *
+        * @return boolean False on error, True otherwise.
+     * @access public
+     */
+       public function insertData($values)
+       {
+               try {
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE member_id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $params = implode(', ', array_keys($values));
+                       $bindParams = ':' . implode(', :', array_keys($values));
+                       $sql = "
+                               INSERT INTO {$this->tableName} (member_id, amenity_id)
+                               VALUES (:member_id, :aid)";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       foreach ($values as $k => $v) {
+                               $stmt->bindParam(':aid', $k, PDO::PARAM_INT);
+                               $stmt->execute();
+                       }
+
+            $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+            $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+                       return true;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return array     Return description (if any) ...
+     * @access public
+     */
+       public function processData($values)
+       {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       default :
+                               if (preg_match('/^.+_rmv$/', $k)) {
+                                       unset($values[$k]);
+                               }
+                               break;
+                       }
+               }
+
+               return $this->insertData($values);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberContacts.php b/Toolkit/Members/EditMemberContacts.php
new file mode 100644 (file)
index 0000000..b9069d7
--- /dev/null
@@ -0,0 +1,719 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberContacts.php,v 1.11 2010/01/20 19:40:16 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handle associating contacts along with member records
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the business contacts. Form is not rendered until the user is added into
+ * the Database.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ * @see       Toolkit_Members
+ */
+class Toolkit_Members_EditMemberContacts
+       extends Toolkit_Members_EditMemberInfo implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data of the files
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_contacts';
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editContacts.tpl';
+
+       /**
+        * Message to return if the form successfully submits
+        *
+        * @var string
+        * @access protected
+        */
+    protected $successMsg = '
+        <div id="form-success-top">
+            You successfully updated your contact.
+        </div>';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        * @see    Toolkit_Members_EditMemberInfo
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               try {
+                       if (isset($_GET['cid'])) {
+                               $sql = "
+                                       select * from {$this->tableName} where id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':cid', $_GET['cid'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $defaults['id']                 = $row['id'];
+                               $defaults['title']              = $row['title'];
+                               $defaults['fname']              = $row['fname'];
+                               $defaults['lname']              = $row['lname'];
+                               $defaults['email']              = $row['email'];
+                               $defaults['phone']              = $row['phone'];
+                               $defaults['send_mail']  = $row['send_mail'];
+                       }
+            $sql = "
+              SELECT *, fname || ' ' || lname AS name,
+                     CASE send_mail
+                     WHEN 'true' THEN 'Can Mail'
+                     ELSE 'No Mail'
+                     END AS send_mail
+                FROM {$this->tableName}
+               WHERE member_id = :id
+                          ORDER BY id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $i = 0;
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $defaults["cid$i"]                      = $row['id'];
+                               $defaults["title$i"]            = $row['title'];
+                               $defaults["name$i"]             = $row['name'];
+                               $defaults["email$i"]            = $row['email'];
+                               $defaults["phone$i"]            = $row['phone'];
+                               $defaults["send_mail$i"]        = $row['send_mail'];
+                               ++$i;
+                       }
+                       $this->setupDefaults($defaults);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+        $e = array();
+               $contacts = $this->getMemberContacts();
+               //      All Grouped Elements are created here.
+               $submitText = (isset($_GET['cid'])) ? 'Update' : 'Submit';
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'fileHdr',
+            'display' => 'Contacts'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'id'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'title',
+            'display' => 'Title',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'fname',
+            'display' => 'First Name',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'lname',
+            'display' => 'Last Name',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'email',
+            'display' => 'Email',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'phone',
+            'display' => 'Phone',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'advcheckbox',
+            'req' => false,
+            'name' => 'send_mail',
+            'display' => 'Receive Mail',
+            'val' => array(0, 1)
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => $submitText,
+            'opts' => array('class' => 'submit')
+        );
+               if (is_array($contacts)) {
+                       foreach ($contacts as $k => $v) {
+                               $e[] = array(
+                    'type' => 'header',
+                    'req' => false,
+                    'name' => "fileHdr$k"
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "cid$k"
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "name$k",
+                    'display' => 'Name'
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "title$k"
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "email$k",
+                    'display' => 'Email'
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "phone$k",
+                    'display' => 'Phone'
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "send_mail$k",
+                    'display' => 'Receive Mail'
+                );
+                       }
+               }
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+        //  form rules
+        $r = array();
+               $this->registeredRules = array('phone', 'email');
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Invalid Email Address!',
+            'type' => 'email',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        /*
+               $r[] = array(
+            'element' => 'phone',
+            'message' => 'ERROR: Invalid Phone Number!',
+            'type' => 'phone',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        */
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     getDelUrl()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param object $sec Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+       public function getDelUrl($sec)
+       {
+               return $_SERVER['REQUEST_URI'] . "&d=t&cid={$sec->elements[0]->html}";
+       }
+
+       //      }}}
+       //      {{{     getEditUrl()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param object $sec Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+       public function getEditUrl($sec)
+       {
+               return $_SERVER['REQUEST_URI'] . "&cid={$sec->elements[0]->html}";
+       }
+
+       //      }}}
+       //      {{{     getMailIcon()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param object $sec Parameter description (if any) ...
+     *
+     * @return string Return description (if any) ...
+     * @access public
+     */
+       public function getMailIcon($sec)
+       {
+               if ($sec->elements[5]->html == 'No Mail') {
+                       $icon = 'delete';
+                       $title = 'Does not receive newsletters';
+               } else {
+                       $icon = 'add';
+                       $title = 'Receives newsletters';
+               }
+               return '<img width="16" height="16" title="'.$title.'"
+                          class="mail" alt="mail"
+                          src="'. GLM_APP_BASE_URL . "assets/icons/email_$icon.png" . '">';
+       }
+
+       //      }}}
+       //      {{{ getMemberContacts()
+
+       /**
+        * Get all the contacts data uploaded to a member into an array
+        *
+     * @return array member contacts
+        * @access protected
+        */
+       protected function getMemberContacts()
+       {
+        $c = array();
+               try {
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE member_id = :id
+                                ORDER BY id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch()) {
+                               $c[] = $row;
+                       }
+                       return $c;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access public
+     */
+       public function insertData($values)
+       {
+               unset(
+                       $values['id'],
+                       $values['target'],
+                       $values['submit']
+               );
+               $values['member_id'] = $_GET['id'];
+               try {
+                       $params = implode(', ', array_keys($values));
+                       $bindParams = ':' . implode(', :', array_keys($values));
+                       $sql = "
+                               INSERT INTO {$this->tableName} ($params)
+                               VALUES ($bindParams)";
+                       $stmt = $this->dbh->prepare($sql);
+                       foreach ($values as $k => $v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } elseif ($metaData == 'double precision') {
+                                       $dataType = null;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               $stmt->bindParam(":$k", $values[$k], $dataType);
+                       }
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ isForm()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $sec Parameter description (if any) ...
+     *
+     * @return unknown Return description (if any) ...
+     * @access public
+     */
+       public function isForm($sec)
+       {
+               return !$sec;
+       }
+
+       //      }}}
+       //      {{{     isName()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isName($name)
+       {
+               return (substr($name, 0, 4) == 'name');
+       }
+
+       //      }}}
+       //      {{{     isPhone()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isPhone($name)
+       {
+               return (substr($name, 0, 5) == 'phone');
+       }
+
+       //      }}}
+       //      {{{     isEmail()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isEmail($name)
+       {
+               return (substr($name, 0, 5) == 'email');
+       }
+
+       //      }}}
+       //      {{{     isTitle()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isTitle($name)
+       {
+               return (substr($name, 0, 5) == 'title');
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+       public function processData($values)
+       {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               if (empty($values['id'])) {
+                       $this->insertData($values);
+               } else {
+                       $this->updateData($values);
+               }
+               $listPage = BASE_URL .
+                       "admin/members.php?page=editMember&module=addMember&tab=contacts&id={$_GET['id']}";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ removeContact()
+
+    /**
+     * Remove a contact from a member record
+     *
+     * @param integer $cid contact id
+     * @param integer $mid member id
+     *
+     * @return void
+     * @access public
+     */
+       public function removeContact($cid, $mid)
+       {
+               try {
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE id = :cid
+                   AND member_id = :mid";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                       $stmt->bindParam(':mid', $mid, PDO::PARAM_INT);
+                       $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ show()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+       public function show()
+       {
+               if (isset($_GET['d'])) {
+                       $this->removeContact($_GET['cid']);
+                       $target = BASE_URL . 'admin/members.php?page=editMember&module=addMember&tab=contacts&id=';
+                       $target .= $_GET['id'];
+                       header("Location: $target");
+               }
+               Toolkit_Common::show();
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return boolean   Return description (if any) ...
+     * @access public
+     */
+       public function updateData($values)
+       {
+               if (array_key_exists('delete', $values)) {
+                       $this->deleteFile($values);
+               }
+
+               unset(
+                       $values['target'],
+                       $values['submit']
+               );
+
+               try {
+                       $params = array_keys($values);
+                       $length = count($params);
+                       for ($i = 0; $i < $length; ++$i) {
+                               $bindParams .= "{$params[$i]} = :{$params[$i]}";
+                if ($i < ($length - 1)) {
+                    $bindParams .= ', ';
+                }
+                       }
+                       $sql = "
+                               UPDATE {$this->tableName}
+                                  SET $bindParams
+                                WHERE id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $pid, PDO::PARAM_INT);
+                       foreach ($values as $k => $v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               $stmt->bindParam(":$k", $values[$k], $dataType);
+                       }
+                       $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+                       return false;
+               }
+               return true;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberFile.php b/Toolkit/Members/EditMemberFile.php
new file mode 100644 (file)
index 0000000..0e9b1a2
--- /dev/null
@@ -0,0 +1,606 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberFile.php,v 1.16 2010/07/16 20:52:15 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+require_once BASE . 'Toolkit/Members/Rules/MemberFile.php';
+
+define('MEMBER_UPLOADED_FILES', BASE . 'uploads/member_files/');
+
+/**
+ * Controls for uploading / editing files for a business record
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the business files. Form is not rendered until the user is added into the Database.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_EditMemberFile
+       extends Toolkit_Members_EditMemberInfo implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data of the files
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_files';
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editFile.tpl';
+
+       /**
+        * Message to return if the form successfully submits
+        *
+        * @var string
+        * @access protected
+        */
+    protected $successMsg = '
+        <div id="form-success-top">
+            You successfully updated your file.
+        </div>';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        * @see    Toolkit_Members_EditMemberInfo
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               //      Make sure we have the upload directory actually created so we can store our uploaded files.
+               if (!is_dir(MEMBER_UPLOADED_FILES)) {
+                       $oldUmask = umask(0);
+                       mkdir(MEMBER_UPLOADED_FILES, 0770, true);
+                       umask($oldUmask);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               try {
+            $sql = "
+              SELECT *
+                FROM {$this->tableName}
+               WHERE member_id = :id
+                          ORDER BY id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $i = 0;
+                       $imgTag = '<img src="'.BASE_URL.'images/file-ext/pdf.png"
+                               alt="pdf Image" style="display: inline;"> ';
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $defaults["file$i"] = $row['id'];
+                               $defaults["file_name$i"] = (empty($row['file_name'])) ?
+                                       $row['original_name'] : $row['file_name'];
+
+                               $oname = (empty($row['file_name'])) ?
+                                       $row['original_name'] : $row['file_name'];
+                               $defaults["original_name$i"] = '<div class="thumb">' .
+                                               $imgTag . $oname . '</div>';
+                               ++$i;
+                       }
+                       $this->setupDefaults($defaults);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+               $e = array();
+
+               $files = $this->getMemberFiles();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+                       'type' => 'header',
+                       'req' => false,
+                       'name' => 'fileHdr',
+                       'display' => 'Files'
+               );
+               if (isset($_POST['uploaded_file_rmv'])) {
+                       $e[] = array(
+                               'type' => 'hidden',
+                               'req' => false,
+                               'name' => 'uploaded_file_rmv'
+                       );
+               }
+               $e[] = array(
+                       'type' => 'text',
+                       'req' => false,
+                       'name' => 'file_name',
+                       'display' => 'File Name'
+               );
+               $e[] = array(
+                       'type' => 'file',
+                       'req' => false,
+                       'name' => 'file_rmv',
+                       'display' => 'Upload a File',
+                       'opts' => array('class' => 'submit')
+               );
+               $e[] = array(
+                       'type' => 'submit',
+                       'req' => false,
+                       'name' => 'submitNewFile',
+                       'display' => 'Upload new file',
+                       'opts' => array('class' => 'submit')
+               );
+
+               if (is_array($files)) {
+                       foreach ($files as $k => $v) {
+                               $e[] = array(
+                                       'type' => 'header',
+                                       'req' => false,
+                                       'name' => "fileHdr$k"
+                               );
+                               $e[] = array(
+                                       'type' => 'hidden',
+                                       'req' => false,
+                                       'name' => "file$k"
+                               );
+                               $e[] = array(
+                                       'type' => 'static',
+                                       'req' => false,
+                                       'name' => "original_name$k"
+                               );
+                               $e[] = array(
+                                       'type' => 'text',
+                                       'req' => false,
+                                       'name' => "file_name$k",
+                                       'display' => 'File Name',
+                                       'opts' => array('class' => 'text')
+                               );
+                               $e[] = array(
+                                       'type' => 'submit',
+                                       'req' => false,
+                                       'name' => 'update',
+                                       'display' => 'Update File Name',
+                                       'opts' => array('class' => 'submit')
+                               );
+                               $e[] = array(
+                                       'type' => 'submit',
+                                       'req' => false,
+                                       'name' => 'delete',
+                                       'display' => 'Delete File',
+                                       'opts' => array('class' => 'photoDelete fileDelete')
+                               );
+                       }
+               }
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+        $this->configureDefaults();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+               $mimeTypes = array(
+                       'application/pdf',
+                       'application/msword',
+            'application/force-download'
+               );
+
+        $r = array();
+
+               if ($_FILES['file_rmv']['error'] == UPLOAD_ERR_OK) {
+                       $r[] = array(
+                'element'    => 'file_rmv',
+                'message'    => 'ERROR: Incorrect File Type (.pdf, .doc) only!',
+                'type'       => 'mimetype',
+                'format'     => $mimeTypes,
+                'validation' => $this->validationType,
+                'reset'      => false,
+                'force'      => false
+            );
+               }
+               $r[] = array(
+            'element'    => 'file_rmv',
+            'message'    => 'ERROR: Invalid File!',
+            'type'       => 'MemberFile',
+            'format'     => array($this, false),
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{ deleteFile()
+
+       /**
+        * Remove the file from the disk and delet from the database
+        *
+        * @param string $values Form values
+     *
+        * @return boolean
+        * @access protected
+        */
+       protected function deleteFile($values)
+       {
+               try {
+                       $fid = $values["file{$values['target']}"];
+                       $this->dbh->beginTransaction();
+                       //      Get the file name so we know what to look for when we try to
+                       //      delete the file from the disk.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE id      = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $fid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $file = $stmt->fetch(PDO::FETCH_ASSOC);
+                       //      Make sure the file actually exists, then try to remove it.
+                       if (file_exists(BASE . $this->uploadDir . $file['name_on_disk'])) {
+                               unlink(BASE . $this->uploadDir . $file['name_on_disk']);
+                       }
+
+                       //      Remove the photo from the updates table if one is present.
+                       $sql = "
+                DELETE FROM {$this->pendingTable}
+                 WHERE db_table     = '{$this->tableName}'
+                   AND member_id    = :member_id
+                   AND foreign_key  = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':id', $fid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       //      Remove the file from the member.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $fid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ findTargetFile()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return integer   Return description (if any) ...
+     * @access protected
+     */
+       protected function findTargetFile($values)
+       {
+               foreach ($values as $k => $v) {
+                       if (preg_match('/^file_name.+$/', $k, $matches)) {
+                               return substr($k, 9);
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{ getMemberFiles()
+
+       /**
+        * Get all the file data uploaded to a member into an array
+        *
+     * @return array member files
+        * @access protected
+        * @see    Toolkit_FormBuilder::setupDefaults()
+        */
+       protected function getMemberFiles()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE member_id = :id
+                                ORDER BY id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $files[] = $row;
+                       }
+                       return $files;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array   $values  Parameter description (if any) ...
+     * @param boolean $pending Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access public
+     */
+       public function insertData($values, $pending = false)
+       {
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+               $insertData['name_on_disk'] = $values['uploaded_file_rmv'];
+               $insertData['member_id'] = $_GET['id'];
+               $insertData['size'] = $values['file_rmv']['size'];
+               $insertData['original_name'] = $values['file_rmv']['name'];
+               $insertData['file_name'] = $values['file_name'];
+               $insertData['pending'] = $pending;
+               try {
+                       $params = implode(', ', array_keys($insertData));
+                       $bindParams = ':' . implode(', :', array_keys($insertData));
+                       $sql = "
+                               INSERT INTO {$this->tableName} ($params)
+                               VALUES ($bindParams)";
+                       $stmt = $this->dbh->prepare($sql);
+                       foreach ($insertData as $k => &$v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               $stmt->bindParam(":$k", $v, $dataType);
+                       }
+
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+    }
+
+        //     }}}
+
+       //      {{{ processData()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+       public function processData($values)
+       {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               $values['target'] = $this->findTargetFile($values);
+
+               if (array_key_exists('submitNewFile', $values)) {
+                       $this->insertData($values);
+               } else {
+                       $this->updateData($values);
+               }
+               $listPage = BASE_URL .
+                       "admin/members.php?rt=Members&ac=editMember&tab=files&id={$_REQUEST['id']}";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ showFile()
+
+       /**
+        * Used in the template to determine when to show the File
+        *
+        * Since the file tag falls outside of the normal flow of the section loop
+        * we need to determine early if we should display the file or not. Since
+        * the file is the only element that uses a "static" quickform element,
+        * check to see if the first element type in a section is a static element
+        * and if so output the element (file).
+        *
+        * @param array $data The array of element objec
+     *
+        * @return boolean Whether an element is of type static or not.
+        * @access public
+        */
+       public function showFile($data)
+       {
+               return ($data->type == 'static');
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return mixed     Return description (if any) ...
+     * @access public
+     */
+       public function updateData($values)
+       {
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+               if (array_key_exists('delete', $values)) {
+                       return $this->deleteFile($values);
+               }
+               $target = $values['target'];
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       case "file_name$target" :
+                               $values['file_name'] = $v;
+                               unset($values[$k]);
+                               break;
+
+                       case "file$target" :
+                               $pid = $v;
+                               unset($values[$k]);
+                               break;
+
+                       default :
+                               unset($values[$k]);
+                               break;
+                       }
+               }
+
+               try {
+                       $params = array_keys($values);
+                       $length = count($params);
+                       for ($i = 0; $i < $length; ++$i) {
+                               $bindParams .= "{$params[$i]} = :{$params[$i]}";
+                if ($i < ($length - 1)) {
+                    $bindParams .= ', ';
+                }
+                       }
+                       $sql = "
+                               UPDATE {$this->tableName}
+                                  SET $bindParams
+                                WHERE id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $pid, PDO::PARAM_INT);
+                       foreach ($values as $k => $v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               $stmt->bindParam(":$k", $values[$k], $dataType);
+                       }
+                       $stmt->execute();
+
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+                       return false;
+               }
+               return true;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberInfo.php b/Toolkit/Members/EditMemberInfo.php
new file mode 100644 (file)
index 0000000..ba4344f
--- /dev/null
@@ -0,0 +1,3333 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * EditMemberInfo
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberInfo.php,v 1.52 2010/08/09 17:58:03 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Edit member info stored in the database
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the member data.  Handles adding / editing module details, including:
+ * 1. Restaurants
+ * 2. Accommodations
+ * 3. Golfing
+ *
+ * Controls the addition of categories to a member record.  Categories have
+ * dynamic settings which allow users to dynamically set which categories are
+ * associated to which modules (golf, accommodations, restaurant, etc...).
+ * Depending on which category is selected and assigned to a member record
+ * controls which modules are displayed on the form.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com/admin/members.php?rt=Members&ac=editMember&tab=info
+ * @see       Toolkit_Members, member_admin
+ */
+class Toolkit_Members_EditMemberInfo
+    extends Toolkit_FormBuilder implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member';
+
+       /**
+        * Array of data that holds the meta data info on the table
+        *
+        * Contains information on the type of fields in the database.
+        * That way when we run our automated SQL queries with our PDO
+        * we can properly bind data to our SQL queries.  This will
+        * allow for one more layer of protection against any sql
+        * injection attempts.
+        *
+        * @var string
+        * @access public
+        * @see Toolkit_Common::processData()
+        */
+       public $tableMetaData;
+
+       /**
+        * Determines if member updates have to be approved if changed
+        *
+        * If set to true, all module info must be approved by admin before it
+        * will be displayed on the front end to visitors. This also includes
+        * ccard information.
+        *
+        * Since all member forms will be spawned from this class, if we put
+        * this value here we can set once / change once and affect the entire
+        * app if we need to alter this.  We can also set this up in any child
+        * class and override on individual classes if need be.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $strictPending = true;
+
+       /**
+        * Some special forms dont utlize this stylesheet
+        * Allow classes to override this setting so it doesn't
+        * get included
+        *
+        * @var boolean
+        * @access protected
+        */
+       protected $includeContactStyleSheet = false;
+
+       /**
+        * The table used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $pendingTable = 'member_updates';
+
+       /**
+        * Determines if a member is in the pending state or not
+        *
+        * When the member has rows of data in the member_updates table in the DB
+        * they are considered "pending updates" until those changes are accepted
+        * or rejected by an admin user.
+        *
+        * @var string
+        * @access public
+        */
+       public $pending = false;
+
+       /**
+        * holds all the fields that are currently pending
+        *
+        * used in conjunction with the template, all fields that are in this
+        * list, will have a pending class for the <tr> row, so they can easily
+        * be identified.
+        *
+        * @var string
+        * @access public
+        */
+       public $pendingFields = array();
+
+       //      What are the modules associated with this form.
+       //      New members won't have access to these right away.
+       //      This boolean settings will be overridden inside the class.
+
+       /**
+        * The status of accommodation related categories associated w/ the member
+        *
+        * If the member has any categories that are assigned to the accommodations
+        * module, then this setting will become true and the form will show
+        * the accommodation module.
+        *
+        * @var bool
+        * @access protected
+        */
+       protected $accommodations = false;
+
+       /**
+        * The status of restaurant related categories associated w/ the member
+        *
+        * If the member has any categories that are assigned to the restaurant
+        * module, then this setting will become true and the form will show
+        * the restaurant module.
+        *
+        * @var bool
+        * @access protected
+        */
+       protected $restaurant = false;
+
+       /**
+        * The status of golf related categories associated w/ the member
+        *
+        * If the member has any categories that are assigned to the golf
+        * module, then this setting will become true and the form will show
+        * the golf module.
+        *
+        * @var bool
+        * @access protected
+        */
+       protected $golf = false;
+
+       /**
+        * Cities array for select list
+        *
+        * @var array
+        * @access protected
+        */
+       protected $cities;
+
+       /**
+        * States array for select list
+        *
+        * @var array
+        * @access protected
+        */
+       protected $states;
+
+       /**
+        * Category record objects
+        *
+        * Used when creating the category select list.
+        *
+        * @var array
+        * @access protected
+        */
+       protected $records = array();
+
+       /**
+        * The categories the member has associated with it
+        *
+        * @var array
+        * @access protected
+        */
+       protected $memberCategories = null;
+
+       /**
+        * Primary email address to send notification a record has been updated
+        *
+        * Set this value to false and it will turn off the email
+        * update notifications.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $primaryAdvisee;
+
+       /**
+        * Email address of people that might also want to be advised of updates
+        *
+        * A list of all email address that might also want to be advised
+        * updates have been made on a business record. You can add as many
+        * as you would like and they will be CC in the email.
+        *
+        * N.B. You cannot make this array bigger than 5 people or you will need to
+        * rewrite the function to handle the server spam issue.
+        * @var array
+        * @access private
+        */
+        protected $secondaryAdvisees = array();
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The name of the template used to render the business info form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editMember.tpl';
+
+       /**
+        * The name of the template used to email the owner for any updates
+        *
+        * When a member makes an update to thier record, this is the template
+        * we will use to send out the email notification to the site owner.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $emailTemplate = 'emailOwner.tpl';
+
+       /**
+        * Message to return if the form successfully submits
+        *
+        * @var string
+        * @access protected
+        */
+    protected $successMsg = '
+        <div id="form-success-top">
+            The information below has been successfully submitted.
+        </div>';
+
+       /**
+        * The flexy template object which holds the rendered object
+        *
+        * @var object
+        * @access protected
+        */
+       protected $template;
+
+       /**
+        * Form access from inside the template
+        *
+        * @var object
+        * @access protected
+        */
+       protected $view;
+
+       /**
+        * Extra rules we need to register so we can fully validate form elements
+        *
+        * @var array
+        * @access protected
+        */
+       protected $registeredRules = array(
+               'zip',
+               'phone',
+               array(
+                       'checkEmail',
+                       'callback',
+                       'email',
+                       'Validate'
+               ),
+               array(
+                       'checkURI',
+                       'callback',
+                       'uri',
+                       'Validate'
+               )
+       );
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        * @see    Toolkit_FormBuilder, HTML_QuickForm
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+               //      if this value is set to false, then no emails will be sent out
+               //      upon update of a record.
+               if ($this->primaryAdvisee !== false) {
+                       if (!defined('MEMBER_RECORD_UPDATES_ADVISOR')) {
+                               //      Please see property definition above for explanation.
+                               echo 'in file: [' . __FILE__ . ' ] on line: [' . __LINE__ . ']<br>';
+                               echo '
+                               <p>
+                                       Please define the
+                                       <strong>MEMBER_RECORD_UPDATES_ADVISOR</strong> constant
+                                       in the setup file first.<br><br> This Constant should hold
+                                       the email address of the person you would like notified
+                                       when a member submits an update.<br>Set to false if you do
+                                       not want an email to be sent.
+                               </p>';
+                               die;
+                       }
+                       $this->primaryAdvisee = MEMBER_RECORD_UPDATES_ADVISOR;
+               }
+               //      If you want to add secondary advisors that will also receive
+               //      an email when a record is updated, update the property here.
+               //      If you use associative key values then they will be appended
+               //      to the email string. i.e.
+               //      Jamie Kahgee <jamie.kahgee+secondaryAdvisorTest1@gmail.com>
+               //      Other wise the address will just be added.
+               $this->secondaryAdvisees = array(
+                       //'Jamie Kahgee' => 'jamie.kahgee+secondaryAdvisorTest1@gmail.com',
+                       //'Jodie Bissonette' => 'jodie@gaslightmedia.com',
+               );
+
+               $this->dbh = $pdo;
+
+               $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+       }
+
+       //      }}}
+
+       // {{{ addInfoElement()
+
+       /**
+        * Determines if the element is supposed to display additional info
+        *
+     * @param string $element name of element
+     *
+        * @return boolean True if supposed to display additional info.
+        *                                 false otherwise
+        * @access public
+        */
+       function addInfoElement($element)
+       {
+               switch ($element) {
+               case 'street' :
+               case 'member_contact_email' :
+                       return true;
+                       break;
+
+               default :
+                       return false;
+                       break;
+               }
+       }
+
+       //      }}}
+
+    /**
+     * Description of addMemberToStreamSend()
+     *
+     * @param integer $mid Member ID
+     *
+     * @return void
+     * @access public
+     */
+    public function addMemberToStreamSend($mid)
+    {
+        if (   defined('MEMBER_STREAMSEND_API')
+            && MEMBER_STREAMSEND_API) {
+            // send member to streamsend
+            $memberStreamSend = new Toolkit_Members_StreamSend($this->dbh);
+            $memberStreamSend->sendMemberById($mid);
+        }
+    }
+
+       //      {{{ checkMemberName()
+
+       /**
+        * Checks if the member name already exists in the database
+        *
+        * @param array $data The name of the member to check for.
+     *
+        * @return bool False on SQL Query error, otherwise true.
+        * @access      protected
+        */
+       public function checkMemberName($data)
+       {
+               try {
+                       //      If we're editing a member, they
+                       //      can save that member as its
+                       //      own name. so don't include that
+                       //      member in the check.
+                       if (is_numeric($_GET['id'])) {
+                               $and = "AND member_id <> :id";
+                       }
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM member
+                                WHERE member_name = :name
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':name', $data, PDO::PARAM_STR);
+                       if (is_numeric($_GET['id'])) {
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $valid);
+                       $stmt->fetch();
+
+                       return !(bool) $valid;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ checkUName()
+
+       /**
+        * Checks if the login name already exists in the database
+        *
+        * @param array $data The name of the member to check for.
+     *
+        * @return boolean False on SQL Query error, otherwise true.
+        * @access      protected
+        */
+       public function checkUName($data)
+       {
+               try {
+                       //      If we're editing a member, they
+                       //      can save that member as its
+                       //      own name. so don't include that
+                       //      member in the check.
+                       if (is_numeric($_GET['id'])) {
+                               $and = "AND member_id <> :id";
+                       }
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM {$this->tableName}
+                                WHERE member_login = :name
+                                 $and";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':name', $data, PDO::PARAM_STR);
+                       if (is_numeric($_GET['id'])) {
+                               $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR);
+                       }
+                       $stmt->execute();
+            $stmt->bindColumn('total', $valid);
+                       $stmt->fetch();
+
+                       return !(bool) $valid;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     checkDate()
+
+    /**
+     * Validate date input
+     *
+     * allows for empty dates to be valid
+     *
+     * @param array $date date group from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+       public function checkDate($date)
+       {
+               $validate = false;
+               foreach ($date as $i) {
+                       if (is_numeric($i)) {
+                               $validate = true;
+                               break;
+                       }
+               }
+
+               if ($validate) {
+                       //      at least one date list had a number in it.
+                       $d = implode('-', $date);
+                       return Validate::date($d, array('format' => '%n-%j-%Y'));
+               } else {
+                       //      no date numbers were selected
+                       return true;
+               }
+       }
+
+       //      }}}
+       //      {{{     checkLatitude()
+
+    /**
+     * Validate latitude input
+     *
+     * @param float $lat Latitude from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+       public function checkLatitude($lat)
+       {
+               $newLat = (float) $lat;
+               return ($newLat >= -90.0 && $newLat <= 90.0);
+       }
+
+       //      }}}
+       //      {{{     checkLongitude()
+
+    /**
+     * Validate longitude input
+     *
+     * @param float $lng Longitude from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+       public function checkLongitude($lng)
+       {
+               $newLng = (float) $lng;
+               return ($newLng >= -180.0 && $newLng <= 180.0);
+       }
+
+       //      }}}
+       //      {{{ clearModule()
+
+       /**
+        * Removes a module from a member
+        *
+        * When updating a member this function is called for every module.
+        * Then if the member still has that module category assigned to them
+        * the data will be re-inserted back into the db.  Otherwise it will
+        * removed and not associated with that member anymore.
+        *
+        * @param string $tableName     The name of the table / module to clear
+     *
+        * @return Boolean False on SQL Query error, otherwise true.
+        * @access      protected
+        */
+       protected function clearModule($tableName)
+       {
+               try {
+                       $sql = "
+                DELETE FROM $tableName
+                 WHERE member_id = :member_id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ createCategories()
+
+       /**
+        * Creates an array from the array of category tree objects
+        *
+     * @param array   $tree  linear tree array of member categories
+     * @param integer $depth what level we are on
+     *
+        * @return array The array list of categories that
+        *                               that can be loaded into a select element
+        * @access protected
+        */
+       protected function createCategories($tree, $depth = 0)
+       {
+               $this->records[] = $tree->category;
+               if ($depth == 0) {
+                       $this->categories[$tree->catid] = "<span>{$tree->category}</span>";
+               } else {
+                       $this->categories[$tree->catid] = $tree->category;
+               }
+               if (empty($tree->children)) {
+                       return;
+               } else {
+                       ++$depth;
+                       foreach ($tree->children as $miniTrees) {
+                               $this->createCategories($miniTrees, $depth);
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ configureConstants()
+
+       /**
+        * Sets the constants for the form
+        *
+        * The member category select list must always default
+        * to the -- Select Category -- option
+        *
+     * @return void
+        * @access public
+        */
+       public function configureConstants()
+       {
+               $c = array();
+
+               //      set the remove_logo_rmv element to 0 so
+               //      if a logo is uploaded and then the remove
+               //      checkbox is checked and the form is submitted
+               //      it won't retain its checked status.
+               $c = array(
+                       'member_cats[]' => '',
+                       'remove_logo_rmv' => 0,
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for the an existing member
+        *
+        * Populates data for the main member form.  Also grabs
+        * data to populate the modules on the form if needed.
+        *
+        * @return array $defaults Returns the array of defaults
+        *                                                 so children who call this function
+        *                                                 can obtain a copy of these values.
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               if (ctype_digit($_GET['id'])) {
+                       try {
+                               $member_id = $_GET['id'];
+                               //      Get the data for the main form items
+                               $sql = "
+                                       SELECT *
+                                         FROM {$this->tableName}
+                                        WHERE member_id = :member_id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT);
+                               $stmt->execute();
+                               while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                                       foreach ($row as $k => $v) {
+                                               if ($k == 'logo') {
+                                                       $defaults['old_logo_rmv'] = $v;
+                                                       $k = 'image_rmv';
+                                                       $v = '<img src="'.MEMBER_PHOTOS.$v.'"
+                                                                               alt="'.$v.'">';
+                                               }
+                                               $defaults[$k] = $v;
+                                       }
+                               }
+
+                               //      Set the defaults for the credit cards.
+                               $sql = "
+                    SELECT cct.*, mcct.*
+                      FROM ccard_type cct, member_ccard_type mcct
+                     WHERE cct.ccard_type_id = mcct.ccard_type_id
+                       AND mcct.member_id    = :member_id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT);
+                               $stmt->execute();
+                               while ($member = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                                       $defaults["creditCards[{$member['ccard_type_name']}]"] = true;
+                               }
+
+                               $moduleTables = array(
+                                       'member_accommodations',
+                                       'member_golf',
+                                       'member_restaurants',
+                               );
+                               foreach ($moduleTables as $table) {
+                                       $sql = "
+                        SELECT *
+                          FROM $table
+                         WHERE member_id = :member_id";
+                                       $stmt = $this->dbh->prepare($sql);
+                                       $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT);
+                                       $stmt->execute();
+                                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                                               foreach ($row as $k => $v) {
+                                                       $defaults[$k] = $v;
+                                               }
+                                       }
+                               }
+                       } catch (PDOException $e) {
+                               Toolkit_Common::handleError($e);
+                       }
+               } else {
+                       //  get member type
+                       $defaultState = $this->config
+                               ->getItem('section', 'conf')
+                               ->getItem('directive', 'defaultState')
+                               ->getContent();
+                       $defaults = array(
+                               'member_cats[]' => '',
+                               'state_id'              => $defaultState,
+                               'country'               => '',
+                       );
+               }
+
+               $this->setupDefaults($defaults);
+               return $defaults;
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * Categories are populated into the protected class property $categories.
+        * These categories are used to populate the select list of categories.
+        * Modules are configured before any elements are setup, that way we will
+        * know if we need to include them in the rendering of the form.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+               $e = array();
+
+        //  get member type
+               $singularType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+               $pluralType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+               $useCtrlCities = $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'controlledCities')
+                       ->getContent();
+               $allowRegions = $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'regions')
+                       ->getContent();
+               $dateStartYear = $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'dateStartYear')
+                       ->getContent();
+               $usesGlmReservations = $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'glmReservations')
+                       ->getContent();
+
+               $this->setupFormCategories();
+               $this->configureModules();
+
+               $this->getCategories();
+
+               //      All Grouped Elements are created here.
+               //      All Elements are created here.  This includes group element definitions.
+
+        //  {{{ Member Information
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'memberInfoHdr',
+                       'display' => "$singularType Information",
+                       'col1'    => true
+               );
+               $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => true,
+                       'name'    => 'active',
+                       'display' => 'Status',
+            'opts'    => 'Active',
+                       'val'     => array(0, 1),
+               );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => true,
+                       'name'    => 'reviewed',
+                       'display' => 'Reviewed?',
+            'opts'    => 'Yes',
+                       'val'     => array(0, 1),
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'member_name',
+                       'display' => "$singularType Name",
+                       'opts'    => array('class' => 'text')
+               );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'primary_contact_fname',
+//                     'display' => 'Primary Contact First Name',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'primary_contact_lname',
+//                     'display' => 'Primary Contact Last Name',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'process_email',
+//                     'display' => 'Primary Contact Email',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'date',
+//                     'req'     => false,
+//                     'name'    => 'join_date',
+//                     'display' => "$singularType Since",
+//                     'opts'    => array(
+//                             'format'           => 'm / d / Y',
+//                             'minYear'          => $dateStartYear,
+//                             'maxYear'          => date('Y'),
+//                             'addEmptyOption'   => true,
+//                             'emptyOptionValue' => '',
+//                             'emptyOptionText'  => array(
+//                                     'm' => 'mm',
+//                                     'd' => 'dd',
+//                                     'Y' => 'yyyy',
+//                             )
+//                     )
+//             );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'phone',
+                       'display' => 'Primary Phone',
+                       'opts'    => array('class' => 'text')
+               );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'toll_free',
+//                     'display' => 'Phone 2',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'fax',
+//                     'display' => 'Fax Number',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'member_contact_email',
+//                     'display' => 'Email on Website',
+//                     'opts'    => array('class' => 'text')
+//             );
+               /*
+               $e[] = array(
+                       'type'    => 'select',
+                       'req'     => false,
+                       'name'    => 'country',
+                       'display' => 'Country',
+                       'opts'    => array(
+                               ''       => '-- Select Country --',
+                               'USA'    => 'USA',
+                               'Canada' => 'Canada'
+                       )
+               );
+               */
+               $e[] = array(
+                       'type'        => 'text',
+                       'req'         => false,
+                       'name'        => 'url',
+                       'display'     => 'Website Address',
+            'opts'        => array('class' => 'text'),
+            'noCharLimit' => true
+               );
+
+        $e[] = array(
+                       'type'        => 'text',
+                       'req'         => false,
+                       'name'        => 'paypal',
+                       'display'     => 'Pay Pal URL',
+            'opts'        => array('class' => 'text'),
+            'noCharLimit' => true
+               );
+        $e[] = array(
+                       'type'        => 'text',
+                       'req'         => false,
+                       'name'        => 'distance',
+                       'display'     => 'Distance',
+            'opts'        => array('class' => 'text'),
+            'noCharLimit' => true
+               );
+        $e[] = array(
+                       'type'        => 'text',
+                       'req'         => false,
+                       'name'        => 'trailtype',
+                       'display'     => 'Type',
+            'opts'        => array('class' => 'text'),
+            'noCharLimit' => true
+               );
+        $e[] = array(
+                       'type'        => 'text',
+                       'req'         => false,
+                       'name'        => 'terrain',
+                       'display'     => 'Terrain',
+            'opts'        => array('class' => 'text'),
+            'noCharLimit' => true
+               );
+        $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'dogs',
+                       'display' => 'Dogs',
+                       'opts'        => array('class' => 'text')
+               );
+        $e[] = array(
+                       'type'        => 'text',
+                       'req'         => false,
+                       'name'        => 'difficulty',
+                       'display'     => 'Difficulty',
+            'opts'        => array('class' => 'text'),
+            'noCharLimit' => true
+               );
+
+        //  }}}
+               //      {{{     Member Categories
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'memberCategoriesHdr',
+                       'display' => "$singularType Categories",
+                       'col1'    => true
+               );
+               $e[] = array(
+                       'type'    => 'select3',
+                       'req'     => false,
+                       'name'    => 'member_cats[]',
+                       'opts'    => $this->categories,
+                       'att'     => array('id' => 'categories')
+               );
+
+               //      }}}
+
+               //      {{{ Mailing Address
+
+//             $e[] = array(
+//                     'type'    => 'header',
+//                     'req'     => false,
+//                     'name'    => 'MailingAddressHdrRmv',
+//                     'display' => 'Mailing Address (if different than physical address)',
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'mailing_address',
+//                     'display' => 'Mailing Address',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'mailing_city',
+//                     'display' => 'City',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'select',
+//                     'req'     => false,
+//                     'name'    => 'mailing_state_id',
+//                     'display' => 'State / Province',
+//                     'opts'    => array('' => '-- Select --') + $this->states
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'mailing_zip',
+//                     'display' => 'Zip / Postal Code',
+//                     'opts'    => array('class' => 'text')
+//             );
+
+        //  }}}
+               //      {{{ Member Description
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'memberDescHdr',
+                       'display' => "$singularType Description",
+                       'col1'    => true
+               );
+               $e[] = array(
+                       'type'    => 'textarea',
+                       'req'     => false,
+                       'name'    => 'description',
+                       'display' => null,
+                       'opts'    => array(
+                'id' => 'description',
+                               'rows' => 8,
+                               'cols' => 43
+                       ),
+            'noCharLimit' => true
+               );
+
+        //  }}}
+               //      {{{ Account Info
+
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'accountInfoHdr',
+            'display' => 'Street Address',
+            'col2'    => true
+        );
+        //  {{{ Physical Address
+
+//             $e[] = array(
+//                     'type'    => 'header',
+//                     'req'     => false,
+//                     'name'    => 'physicalAddressHdr',
+//                     'display' => 'Street Address',
+//             );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'street',
+                       'display' => 'Street Address',
+                       'opts'    => array('class' => 'text')
+               );
+        if ($useCtrlCities) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => true,
+                'name'    => 'city_id',
+                'display' => 'City',
+                'opts'    => array('' => '-- Select --') + $this->cities
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => true,
+                'name'    => 'city',
+                'display' => 'City',
+                'opts'    => array('class' => 'text')
+            );
+        }
+               $e[] = array(
+                       'type'    => 'select',
+                       'req'     => true,
+                       'name'    => 'state_id',
+                       'display' => 'State / Province',
+                       'opts'    => array('' => '-- Select --') + $this->states
+               );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => true,
+            'name'    => 'county',
+            'display' => 'County',
+            'opts'    => $this->getCounties()
+        );
+               if ($allowRegions) {
+                       $e[] = array(
+                               'type'    => 'select',
+                               'req'     => true,
+                               'name'    => 'region',
+                               'display' => 'Region',
+                               'opts'    => $this->getRegions()
+                       );
+               }
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'zip',
+                       'display' => 'Zip / Postal Code',
+                       'opts'    => array('class' => 'text')
+               );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'lat',
+            'display' => 'Latitude',
+            'opts' => array('class' => 'text')
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'lon',
+            'display' => 'Longitude',
+            'opts' => array('class' => 'text')
+        );
+
+        //  }}}
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'member_login',
+//                     'display' => 'Username',
+//                     'opts'    => array('class' => 'text')
+//             );
+//             $e[] = array(
+//                     'type'    => 'text',
+//                     'req'     => false,
+//                     'name'    => 'member_passwd',
+//                     'display' => 'Password',
+//                     'opts'    => array('class' => 'text')
+//             );
+
+        //  }}}
+               //      {{{ Main Image
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'logoHdr',
+                       'display' => 'Main Image',
+                       'col2'    => true
+               );
+               if ($this->hasLogo()) {
+                       $e[] = array(
+                               'type'    => 'checkbox',
+                               'req'     => false,
+                               'name'    => 'remove_logo_rmv',
+                               'display' => 'Remove Image'
+                       );
+                       $e[] = array(
+                               'type'    => 'static',
+                               'req'     => false,
+                               'name'    => 'image_rmv',
+                               'display' => 'Current Image'
+                       );
+            $e[] = array(
+                               'type' => 'hidden',
+                               'req'  => false,
+                               'name' => 'old_logo_rmv'
+                       );
+               }
+
+               $e[] = array(
+                       'type'    => 'file',
+                       'req'     => false,
+                       'name'    => 'new_logo_rmv',
+                       'display' => 'New Image',
+                       'opts'    => array('class' => 'file')
+               );
+
+        //  }}}
+               //      {{{ Payment Type Accepted
+
+//             $e[] = array(
+//                     'type'    => 'header',
+//                     'req'     => false,
+//                     'name'    => 'CreditCardsHdr',
+//                     'display' => 'Payment Type Accepted',
+//                     'col2'    => true
+//             );
+//             $e[] = array(
+//                     'type'    => 'checkbox',
+//                     'req'     => false,
+//                     'name'    => 'creditCards[American Express]',
+//                     'display' => 'American Express'
+//             );
+//             $e[] = array(
+//                     'type'    => 'checkbox',
+//                     'req'     => false,
+//                     'name'    => 'creditCards[Discover]',
+//                     'display' => 'Discover'
+//             );
+//             $e[] = array(
+//                     'type'    => 'checkbox',
+//                     'req'     => false,
+//                     'name'    => 'creditCards[Master Card]',
+//                     'display' => 'Master Card'
+//             );
+//             $e[] = array(
+//                     'type'    => 'checkbox',
+//                     'req'     => false,
+//                     'name'    => 'creditCards[Visa]',
+//                     'display' => 'Visa'
+//             );
+//        $e[] = array(
+//                     'type'    => 'checkbox',
+//                     'req'     => false,
+//                     'name'    => 'creditCards[Diners]',
+//                     'display' => 'Diners'
+//             );
+
+        //  }}}
+               //      {{{ Accommodations Information
+
+               if ($this->accommodations) {
+//                     $e[] = array(
+//                             'type'    => 'header',
+//                             'req'     => false,
+//                             'name'    => 'AccommodationsHdr',
+//                             'display' => 'Accommodations Information',
+//                             'col2'    => true
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'reservation_url',
+//                             'display' => 'Reservation Url',
+//                             'opts'    => array('class' => 'text')
+//                     );
+//                     if ($usesGlmReservations) {
+//                             $e[] = array(
+//                                     'type'    => 'text',
+//                                     'req'     => false,
+//                                     'name'    => 'reservation_id',
+//                                     'display' => 'Reservation Id',
+//                                     'opts'    => array('class' => 'text')
+//                             );
+//                     }
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'num_rooms',
+//                             'display' => 'Number of Rooms',
+//                             'opts'    => array('class' => 'text')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'year_round',
+//                             'display' => 'Open all Year',
+//                             'val'     => array(0, 1)
+//                     );
+               }
+
+        //  }}}
+               //      {{{ Restaurant Information
+
+               if ($this->restaurant) {
+//                     $e[] = array(
+//                             'type'    => 'header',
+//                             'req'     => false,
+//                             'name'    => 'RestaurantHdr',
+//                             'display' => 'Restaurant Information',
+//                             'col2'    => true
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'breakfast',
+//                             'display' => 'Breakfast',
+//                             'att'     => array('id'  => 'breakfast'),
+//                             'val'     => array(0, 1)
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'breakfast_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'breakfast_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'brunch',
+//                             'display' => 'Brunch',
+//                             'att'     => array('id' => 'brunch'),
+//                             'val'     => array(0, 1)
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'brunch_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'brunch_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'lunch',
+//                             'display' => 'Lunch',
+//                             'att'     => array('id' => 'lunch'),
+//                             'val'     => array(0, 1)
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'lunch_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'lunch_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'dinner',
+//                             'display' => 'Dinner',
+//                             'att'     => array('id' => 'dinner'),
+//                             'val'     => array(0, 1)
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'dinner_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'dinner_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'alcohol',
+//                             'display' => 'Alcohol',
+//                             'val'     => array(0, 1)
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'non_smoking',
+//                             'display' => 'Non-Smoking',
+//                             'val'     => array(0, 1)
+//                     );
+               }
+
+        //  }}}
+               //      {{{ Golf Information
+
+               if ($this->golf) {
+//                     $e[] = array(
+//                             'type' => 'header',
+//                             'req' => false,
+//                             'name' => 'GolfingHdr',
+//                             'display' => 'Golf Course Information',
+//                             'col2' => true
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'par',
+//                             'display' => 'Par',
+//                             'opts'    => array('class' => 'text')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'yardage',
+//                             'display' => 'Yardage',
+//                             'opts'    => array('class' => 'text')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'course_rating',
+//                             'display' => 'Course Rating',
+//                             'opts'    => array('class' => 'text')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'slope_rating',
+//                             'display' => 'Slope Rating',
+//                             'opts'    => array('class' => 'text')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'walking_course',
+//                             'display' => 'Walking Course',
+//                             'val'     => array(0, 1)
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'holes18',
+//                             'display' => '18 Holes',
+//                             'opts'    => array('class' => 'text')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'holes9',
+//                             'display' => '9 Holes',
+//                             'opts'    => array('class' => 'text')
+//                     );
+               }
+
+        //  }}}
+        //  {{{ Social Media Links
+
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'SocialMediaHdr',
+            'display' => 'Social Media Links',
+            'col2' => true,
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'facebook',
+            'display' => 'Facebook',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'twitter',
+            'display' => 'Twitter',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'myspace',
+            'display' => 'MySpace',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'linkedin',
+            'display' => 'LinkedIn',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'blog',
+            'display' => 'Blog',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'youtube',
+            'display' => 'YouTube',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'pinterest',
+            'display' => 'Pinterest',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+
+        //  }}}
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+       /**
+        * Setup the filters to apply to the elements before we are
+        * handed the values submitted
+        *
+     * @return void
+        * @access public
+        */
+       public function configureFilters()
+       {
+               $f = array();
+               $f[] = array(
+                       'element' => '__ALL__',
+                       'filter' => 'trim'
+               );
+        $f[] = array(
+            'element' => 'reservation_url',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'facebook',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'twitter',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'myspace',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'linkedin',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'blog',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'youtube',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+        $f[] = array(
+            'element' => 'url',
+            'filter' => array('Toolkit_Common', 'filterURI')
+        );
+//        $f[] = array(
+//            'element' => 'phone',
+//            'filter' => array('Toolkit_Common', 'filterPhone')
+//        );
+//        $f[] = array(
+//            'element' => 'fax',
+//            'filter' => array('Toolkit_Common', 'filterPhone')
+//        );
+//        $f[] = array(
+//            'element' => 'toll_free',
+//            'filter' => array('Toolkit_Common', 'filterPhone')
+//        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Wrapper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+        $this->configureDefaults();
+        $this->configureConstants();
+    }
+
+    //  }}}
+       //      {{{ configureModules()
+
+       /**
+        * Turns on a modules if the member has the appropriate category
+        *
+     * @return void
+        * @access protected
+        */
+       protected function configureModules()
+       {
+               if (is_array($this->memberCategories)) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE category_id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               foreach ($this->memberCategories as $cid => $v) {
+                                       $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                       $stmt->execute();
+                                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                                       if ($row['accommodations'] == 't') {
+                                               $this->accommodations = true;
+                                       }
+                                       if ($row['restaurant'] == 't') {
+                                               $this->restaurant = true;
+                                       }
+                                       if ($row['golf'] == 't') {
+                                               $this->golf = true;
+                                       }
+                               }
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+               $mimeTypes = array(
+                       'image/jpe',
+                       'image/jpeg',
+                       'image/jpg',
+                       'image/jfif',
+                       'image/pjpeg',
+                       'image/pjp',
+                       'image/gif',
+                       'image/png',
+               );
+
+               $r = array();
+
+               $r[] = array(
+                       'element'    => 'reservation_id',
+                       'message'    => 'ERROR: Must be an integer!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'process_email',
+                       'message'    => 'ERROR: Invalid email format!',
+                       'type'       => 'checkEmail',
+                       'format'     => array('use_rfc822' => true),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'member_contact_email',
+                       'message'    => 'ERROR: Invalid email format!',
+                       'type'       => 'checkEmail',
+                       'format'     => array('use_rfc822' => true),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'join_date',
+                       'message'    => 'ERROR: Invalid date!',
+                       'type'       => 'callback',
+                       'format'     => array(&$this, 'checkDate'),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'url',
+                       'message'    => 'ERROR: Invalid URL format',
+                       'type'       => 'checkURI',
+                       'format'     => array(
+                               'allowed_schemes' => array('http', 'https'),
+                               'strict' => false
+                       ),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'reservation_url',
+                       'message'    => 'ERROR: Invalid URL format',
+                       'type'       => 'checkURI',
+                       'format'     => array(
+                               'allowed_schemes' => array('http', 'https'),
+                               'strict' => false
+                       ),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'num_rooms',
+                       'message'    => 'ERROR: Must be an integer!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+        $r[] = array(
+            'element'    => 'lat',
+            'message'    => 'ERROR: Must be a numeric!',
+            'type'       => 'numeric',
+            'format'     => null,
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+               $r[] = array(
+                       'element'    => 'lat',
+                       'message'    => 'ERROR: Latitude out of range!',
+                       'type'       => 'callback',
+                       'format'     => array(&$this, 'checkLatitude'),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+        $r[] = array(
+            'element'    => 'lon',
+            'message'    => 'ERROR: Must be a numeric!',
+            'type'       => 'numeric',
+            'format'     => null,
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+               $r[] = array(
+                       'element'    => 'lon',
+                       'message'    => 'ERROR: Longitude out of range!',
+                       'type'       => 'callback',
+                       'format'     => array(&$this, 'checkLongitude'),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $allowDuplicateMemberNames
+                       = $this->config
+                                  ->getItem('section', 'conf')
+                                  ->getItem('directive', 'duplicateMembers')
+                                  ->getContent();
+        if (!$allowDuplicateMemberNames) {
+            $r[] = array(
+                'element'    => 'member_name',
+                'message'    => 'ERROR: There is an existing account with this name!',
+                'type'       => 'callback',
+                'format'     => array($this, 'checkMemberName'),
+                'validation' => $this->validationType,
+                'reset'      => false,
+                'force'      => false
+            );
+        }
+               $r[] = array(
+                       'element'    => 'member_login',
+                       'message'    => 'ERROR: Sorry, but this username has already been taken!',
+                       'type'       => 'callback',
+                       'format'     => array($this, 'checkUName'),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'state_id',
+                       'message'    => 'ERROR: Invalid State!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'mailing_state_id',
+                       'message'    => 'ERROR: Invalid State!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'region',
+                       'message'    => 'ERROR: Invalid Region!',
+                       'type'       => 'numeric',
+                       'format'     => null,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'zip',
+                       'message'    => 'ERROR: Invalid Zip Code!',
+                       'type'       => 'zip',
+                       'format'     => array('requireDBCheck' => false),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'mailing_zip',
+                       'message'    => 'ERROR: Invalid Zip Code!',
+                       'type'       => 'zip',
+                       'format'     => array('requireDBCheck' => false),
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'new_logo_rmv',
+                       'message'    => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                       'type'       => 'mimetype',
+                       'format'     => $mimeTypes,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+        $r[] = array(
+            'element'    => 'facebook',
+            'message'    => 'ERROR: 200 characters max!',
+            'type'       => 'maxlength',
+            'format'     => 200,
+            'validatios' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $r[] = array(
+            'element'    => 'twitter',
+            'message'    => 'ERROR: 200 characters max!',
+            'type'       => 'maxlength',
+            'format'     => 200,
+            'validatios' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $r[] = array(
+            'element'    => 'myspace',
+            'message'    => 'ERROR: 200 characters max!',
+            'type'       => 'maxlength',
+            'format'     => 200,
+            'validatios' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $r[] = array(
+            'element'    => 'linkedin',
+            'message'    => 'ERROR: 200 characters max!',
+            'type'       => 'maxlength',
+            'format'     => 200,
+            'validatios' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $r[] = array(
+            'element'    => 'blog',
+            'message'    => 'ERROR: 200 characters max!',
+            'type'       => 'maxlength',
+            'format'     => 200,
+            'validatios' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        $r[] = array(
+            'element'    => 'youtube',
+            'message'    => 'ERROR: 200 characters max!',
+            'type'       => 'maxlength',
+            'format'     => 200,
+            'validatios' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     emailOwner()
+
+       /**
+        * Emails the owner and anyone else who wants to be advised of updates
+        *
+        * A false value in the primaryAdvisee will cause no email to be sent.
+        * all secondary advisees listed in the constructor are carbon copied
+        * in the email.
+        *
+        * Emails are sent out in both HTML and TXT forms.
+        *
+     * @return boolean result of email
+        * @access protected
+        */
+       protected function emailOwner()
+       {
+               if ($this->primaryAdvisee === false) {
+                       return;
+               } else {
+                       try {
+                               $sql = "
+                    SELECT member_name
+                      FROM member
+                     WHERE member_id = :member_id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $memberName = $row['member_name'];
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+                       $template = new HTML_Template_Flexy($this->flexyOptions);
+                       $page = new stdClass();
+                       $page->member = $memberName;
+                       $page->url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : BASE_URL;
+                       $page->email = DO_NOT_REPLY_EMAIL;
+                       $page->siteName = SITENAME;
+                       $page->link = '<a target="_blank"  href="'.BASE_URL.'pending-member/'.$_GET['id'].'/">link</a>';
+
+                       $template->compile($this->emailTemplate);
+                       //      Merge the compiled template with the $page object.
+                       $htmlMsg = $template->bufferedOutputObject($page);
+
+                       $msg = "
+                               <h3>$memberName</h3>
+                               <p>
+                                       Has updated thier business record and is now in a pending
+                                       state. To approve / reject thier changes you can either log
+                                       into your {$page->siteName} admin area or follow this
+                                       {$page->link}
+                               </p>";
+                       $crlf = "\n";
+                       $mimeMail = new Mail_mime($crlf);
+            $from = preg_replace("/[^A-Za-z ]/", "", SITENAME) . ' <' . DO_NOT_REPLY_EMAIL . '>';
+                       $mimeMail->setFrom($from);
+                       $mimeMail->setSubject('Member Record Update');
+                       if (!empty($this->secondaryAdvisees)) {
+                               foreach ($this->secondaryAdvisees as $k => $v) {
+                                       if (is_string($k) && !is_numeric($k)) {
+                                               $email = "$k <$v>";
+                                       } else {
+                                               $email = $v;
+                                       }
+                                       $mimeMail->addCC($email);
+                               }
+                       }
+                       $mimeMail->setHTMLBody($htmlMsg);
+                       $mimeMail->setTXTBody($msg);
+
+                       $mail =& Mail::factory('mail');
+                       $body = $mimeMail->get();
+                       $headers = $mimeMail->headers($hdrs);
+
+                       $res = $mail->send($this->primaryAdvisee, $headers, $body);
+                       if (PEAR::isError($res)) {
+                               return Toolkit_Common::handleError($res);
+                       } else {
+                               return $res;
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{ fieldPending()
+
+       /**
+        * Determines if template fields are pending or not
+        *
+        * Each field in the template calls this function to determine if it
+        * is in a pending state or not.  Fields that return true get a
+        * different colored background and border so they are easily recognizable.
+        *
+        * fields are considered pending if they are in the pendingFields array.
+        *
+     * @param string $elem element to check for pending
+     *
+        * @return boolean If the field is pending
+        * @access protected
+        */
+       public function fieldPending($elem)
+    {
+               if (!is_array($this->pendingFields)) {
+                       return false;
+               } else {
+                       return in_array($elem->name, $this->pendingFields);
+               }
+       }
+
+       // }}}
+
+       //      {{{ getCategories()
+
+       /**
+        * Creates array structure of the category tree for use in a select element.
+        *
+        * This method will also instantiate a class property called tree for your
+        * class. This object will hold the tree structure of the categories list
+        * from the Database.
+        *
+        * @return      array           The array list of categories that can be loaded
+        *                                              into a select element
+        *
+        * @access      protected
+        * @see         Toolkit_Members_CategoryTree
+        */
+       protected function getCategories()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM category
+                                WHERE parent_id = 0
+                                ORDER BY name";
+                       foreach ($this->dbh->query($sql, PDO::FETCH_ASSOC) as $row) {
+                               $this->tree[] = new Toolkit_Members_CategoryTree(
+                                       $row['category_id'],
+                    $row['name'],
+                    $this->dbh
+                               );
+                       }
+                       if (!empty($this->tree)) {
+                               foreach ($this->tree as $t) {
+                                       $this->createCategories($t);
+                               }
+                       }
+
+                       if (empty($this->categories)) {
+                               $this->categories
+                                       = array('' => '-- No Categories Created Yet --');
+                       } else {
+                               $this->categories
+                    = array('' => '-- Select Category --') + $this->categories;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+    /**
+     * Description of getCurrentAddress()
+     *
+     * @return array
+     * @access protected
+     */
+    protected function getCurrentAddress()
+    {
+        try {
+            $sql = "
+            SELECT street,city_id,state_id,zip
+              FROM member
+             WHERE member_id = :member_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':member_id', $_GET['id']);
+            $stmt->execute();
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch(PDOException $e) {
+            var_dump($e);
+            exit;
+        }
+    }
+    // {{{ getCounties()
+
+       /**
+        * Configure the regions for member stored in the database into an array
+        *
+     * @return array the counties
+        * @access protected
+        */
+       protected function getCounties()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM county
+                                ORDER BY county_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $counties[$row['county_id']] = $row['county_name'];
+                       }
+                       if (!empty($counties)) {
+                               $counties = array('' => '-- Select County --') + $counties;
+                       } else {
+                               $counties = array('' => '-- No Counties Created Yet -- ');
+                       }
+                       return $counties;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+    // {{{ getRegions()
+
+       /**
+        * Configure the regions for member stored in the database into an array
+        *
+     * @return array the regions
+        * @access protected
+        */
+       protected function getRegions()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM region
+                                ORDER BY region_name";
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $regions[$row['region_id']] = $row['region_name'];
+                       }
+                       if (!empty($regions)) {
+                               $regions = array('' => '-- Select Region --') + $regions;
+                       } else {
+                               $regions = array('' => '-- No Regions Created Yet -- ');
+                       }
+                       return $regions;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ hasLogo()
+
+    /**
+     * Determine if the member record has a logo
+     *
+     * @return boolean if the record has a logo or not
+     * @access protected
+     */
+       protected function hasLogo()
+       {
+               try {
+                       $member_id = $_GET['id'];
+
+                       $sql = "
+                SELECT logo
+                  FROM {$this->tableName}
+                 WHERE member_id = :member_id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+            if (get_class($this) === 'Toolkit_Members_EditMemberOnlyInfo') {
+                $sql = "
+                    SELECT count(*) AS total
+                      FROM {$this->pendingTable}
+                     WHERE member_id = :member_id
+                       AND field     = 'logo'";
+
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT);
+                $stmt->execute();
+                $pendingLogos = $stmt->fetch(PDO::FETCH_ASSOC);
+            }
+
+                       $hasPending = !empty($pendingLogos['total']);
+                       $hasLogo    = !is_null($row['logo']);
+
+                       return ($hasLogo || $hasPending);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ inColumn2()
+
+       /**
+        * Lets the form know when to add a new column
+        *
+        * When rendering the form, we need to know what element
+        * to start rendering the new columns on, this function
+        * checks to see if we should start on the current
+        * element or not.
+        *
+        * This function is called from within the template.
+        *
+     * @param string $section element to check
+     *
+     * @return boolean if the section is in the 2nd column or not
+        * @access protected
+        */
+       public function inColumn2($section)
+       {
+               return ($this->formHeaders[$section]['col2']);
+       }
+
+       //      }}}
+       //      {{{ insertData()
+
+       /**
+        * Create a new record in the database from the data on the form
+        *
+        * When a member is first created, we don't have to worry about
+        * and module data ie.(golf, restaurant, accommodations), since
+        * they initially don't have any categories associated with them.
+        *
+        * Lat / Lon coordinates are not generated here, but they are
+        * injected into the form values if they are not filled in. This
+        * enables us to use google driving directions on all our members.
+        *
+        * Two groups of data are pulled from the values array of data.
+        * (categories & credit cards), these values are then unset in
+        * the values array, b/c we don't insert this data into the primary
+        * table.  They each have their own table they get inserted into and
+        * are then associated to the newly inserted member.
+        *
+        * Empty field values are inserted as NULLS vs empty strings to allow
+        * for unique member_login names.
+        *
+        * A transaction is used to avoid orphaned data if any of the sql queries
+        * fail to properly insert the data.
+        *
+        * @param array $values Form values
+     *
+        * @return boolean False on error, True otherwise.
+        * @access public
+        */
+       public function insertData($values)
+       {
+               //      {{{ Golfing
+
+               //      Remove Golf Fields for Special Insert.
+               $fields = array(
+                       'par',
+                       'yardage',
+                       'course_rating',
+                       'slope_rating',
+                       'walking_course',
+                       'holes18',
+                       'holes9',
+               );
+
+               foreach ($fields as $v) {
+                       $golfFields[$v] = $values[$v];
+                       unset($values[$v]);
+               }
+
+               //      }}}
+               //      {{{ Accommodations
+
+               //      Remove Accommodation Fields for Special Insert.
+               $fields = array(
+                       'reservation_url',
+                       'reservation_id',
+                       'num_rooms',
+                       'year_round',
+               );
+               foreach ($fields as $v) {
+                       $accommodationFields[$v] = $values[$v];
+                       unset($values[$v]);
+               }
+
+               //      }}}
+               //      {{{ Restaurant
+
+               //      Remove Restaurant Fields for Special Insert.
+               $fields = array(
+                       'breakfast',
+                       'breakfast_from',
+                       'breakfast_to',
+                       'brunch',
+                       'brunch_from',
+                       'brunch_to',
+                       'lunch',
+                       'lunch_from',
+                       'lunch_to',
+                       'dinner',
+                       'dinner_from',
+                       'dinner_to',
+                       'alcohol',
+                       'non_smoking',
+               );
+               foreach ($fields as $v) {
+                       $restaurantFields[$v] = $values[$v];
+                       unset($values[$v]);
+               }
+
+               //      }}}
+
+               if (empty($values['lat']) || empty($values['lon'])) {
+                       try {
+                               $this->setLatLngCoords($values);
+                       } catch (Exception $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               }
+
+               $ccards = $values['creditCards'];
+               //      If they dynamically add any categories, but then realize they
+               //      want to remove them, they will show up in this array.
+               if (isset($values['removeCat'])) {
+                       //      So remove them before we get the categories to insert for the member.
+                       $this->removeCategories($values['removeCat'], $values['member_cats']);
+               }
+               //      Now get the cats so we can insert them into a seperate table later.
+               $categories = $values['member_cats'];
+
+               //      Unneeded data that will not be stored in the member table
+               unset($values['member_cats'],
+                         $values['removeCat'],
+                         $values['creditCards']
+               );
+
+               try {
+                       $params = implode(', ', array_keys($values));
+                       $bindParams = ':' . implode(', :', array_keys($values));
+                       $sql = "
+                               INSERT INTO {$this->tableName} ($params)
+                               VALUES ($bindParams)
+                    RETURNING member_id";
+                       $this->dbh->beginTransaction();
+                       $stmt = $this->dbh->prepare($sql);
+                       foreach ($values as $k => &$v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } elseif ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               //      for empty values that are not actually a zero (0), we
+                               //      want to insert null's.
+                               //      This will help hold the unique values for member_logins,
+                               //      as empty values '', are not considered unique
+                               if (empty($v) && $v !== 0) {
+                                       $v = null;
+                                       $dataType = PDO::PARAM_NULL;
+                               }
+                               $stmt->bindParam(":$k", $v, $dataType);
+                       }
+                       $stmt->execute();
+                       $stmt->bindColumn('member_id', $mid);
+                       $stmt->fetch();
+
+                       //      Insert the categories into the DB and associate
+                       //      them w/ the newly inserted member.
+                       if (!empty($categories)) {
+                               $sql = "
+                                       INSERT INTO member_category(member_id, category_id)
+                                   VALUES(:member_id, :cid)";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $mid, PDO::PARAM_INT);
+                               foreach ($categories as $cid) {
+                                       //      If the user didn't select a category,
+                                       //      Then don't run an insert query.
+                                       if (!empty($cid)) {
+                                               $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                               $stmt->execute();
+                                       }
+                               }
+                       }
+
+                       //      Insert the members credit cards into the DB and associate
+                       //      the w/ our new member. We get the ccard ID # by querying for
+                       //      it in the ccard_type table by the ccard name.
+                       if (!empty($ccards)) {
+                               $sql = "
+                                       INSERT INTO member_ccard_type(member_id, ccard_type_id)
+                                               SELECT :member_id, ccard_type_id
+                                                 FROM ccard_type
+                                                WHERE ccard_type_name = :cctn";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $mid, PDO::PARAM_INT);
+                               foreach ($ccards as $k => $v) {
+                                       $stmt->bindParam(':cctn', $k, PDO::PARAM_STR);
+                                       $stmt->execute();
+                               }
+                       }
+
+                       $golf = $restaurant = $accommodations = false;
+                       if (!empty($categories)) {
+                               $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE category_id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               foreach ($categories as &$cid) {
+                                       if (!empty($cid)) {
+                                               $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                               $stmt->execute();
+                                               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                                               //      If any of the module statuses are true, set them.
+                                               //      otherwise leave them as they were, (we don't want
+                                               //      to set a true back to a false).
+                                               $golf = ($row['golf'] == 't') ? true : $golf;
+                                               $accommodations = ($row['accommodations'] == 't') ?
+                                                       true : $accommodations;
+                                               $restaurant = ($row['restaurant'] == 't') ?
+                                                       true : $restaurant;
+                                       }
+                               }
+                       }
+                       $this->clearModule('member_golf');
+                       if ($golf) {
+                               $this->updateModuleFields($golfFields, 'member_golf', $mid);
+                       }
+                       $this->clearModule('member_accommodations');
+                       if ($accommodations) {
+                               $this->updateModuleFields($accommodationFields, 'member_accommodations', $mid);
+                       }
+                       $this->clearModule('member_restaurants');
+                       if ($restaurant) {
+                               $this->updateModuleFields($restaurantFields, 'member_restaurants', $mid);
+                       }
+                       $this->dbh->commit();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+        $this->addMemberToStreamSend($mid);
+
+        header('Location: ' . BASE_URL . "admin/members.php?rt=Members&ac=editMember&tab=info&id=$mid");
+               return true;
+       }
+
+       //      }}}
+
+       //      {{{ newColumn()
+
+       /**
+        * Determines if we've reached the field that should start a new column
+        *
+        * This is used from the Flexy template.  Each field name is passed into
+        * this function, when we reach the appropriate field, we will know that
+        * we need to start a new column.
+        *
+        * @param string $string The name of the field we're checking.
+     *
+        * @return boolean True on the right field, otherwise false.
+        * @access protected
+        */
+       public function newColumn($string)
+       {
+               return ($string == 'Street Address');
+       }
+
+       //      }}}
+
+    public function isMyCheckBox($string)
+    {
+        return (in_array($string, array('active', 'dogsallowed', 'reviewed')));
+    }
+
+       //      {{{ processData()
+
+       /**
+        * Handles processing the submitted forms data.
+        *
+        * Sets up the table meta data so we can insert into the member table.
+        * removes any unwanted fields from the values array.  these fields
+        * will be denoted by the '_rmv' at the end of thier name in the
+        * configureElements function
+        *
+        * <example>
+        * ... 'name' => 'remove_rmv', ...
+        * </example>
+        *
+        * This function also verifies that the lat/lon values were properly filled
+        * out, if they were left blank then the values will either be looked up
+        * via google maps or through our own zip DB. These values will then be
+        * inserted into the values array AND also injected into the form field
+        * values so they will display when the form comes back around.
+        *
+        * The form then decides if it is handeling a new member or not and calls
+        * the appropriate function to insert or update data.
+        *
+        * @param array $values The array of all submitted form values.
+        *
+        * @return boolean Whether the insert/update succeeded.
+        * @access public
+        */
+       public function processData($values)
+       {
+               //      Clean up some form elements before we try any processing
+               if (is_array($values['join_date'])) {
+                       if (is_numeric($values['join_date']['m'])) {
+                               $values['join_date'] = implode('-', $values['join_date']);
+                       } else {
+                               $values['join_date'] = null;
+                       }
+               }
+               $this->processLogo($values);
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       case 'MAX_FILE_SIZE' :
+                               unset($values[$k]);
+                               break;
+
+                       default :
+                               if (preg_match('/^.+_rmv$/', $k)) {
+                                       unset($values[$k]);
+                               }
+                               break;
+                       }
+               }
+
+               if (ctype_digit($_GET['id'])) {
+                       return $this->updateData($values);
+               } else {
+                       return $this->insertData($values);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     processLogo()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+       protected function processLogo(&$values)
+       {
+               //      Keep a tidy house.
+               //      There are 2 scenarios to deal w/ logos:
+               //      1.  Removing logo:
+               //              Delete the image from the image server
+               //              and set the values['logo'] to null.
+               //      2.  New logo:
+               //              Check to see if old_logo_rmv holds a value,
+               //              if it does then remove that logo
+               //              Upload the image and put new filename
+               //              into values['logo'] variable.
+               $imgServer  = new Toolkit_Image_Server();
+
+               if ($values['remove_logo_rmv'] == 1) {
+                       $imgServer->imageDelete($values['old_logo_rmv']);
+                       $values['logo'] = null;
+
+                       if (get_class($this) == 'Toolkit_Members_EditMemberOnlyInfo') {
+                               try {
+                                       //      Make sure any logos that were pending are removed as well.
+                                       $sql = "
+                                               DELETE FROM {$this->pendingTable}
+                                                WHERE field        = 'logo'
+                                                  AND member_id    = :member_id";
+                                       $stmt = $this->dbh->prepare($sql);
+                                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                                       $stmt->execute();
+
+                                       $sql = "
+                                               UPDATE {$this->tableName}
+                                                  SET logo = :logo
+                                                WHERE member_id = :member_id";
+                                       $stmt = $this->dbh->prepare($sql);
+                                       $stmt->bindParam(':logo', $values['logo'], PDO::PARAM_NULL);
+                                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                                       $stmt->execute();
+                               } catch (PDOException $e) {
+                                       return Toolkit_Common::handleError($e);
+                               }
+                       }
+               }
+
+               //      If a new logo is uploaded, have the image server
+               //      process that logo and give us back the file name on
+               //      the server.
+               if ($values['new_logo_rmv']['size'] > 0) {
+                       $imgName = $imgServer->imageUpload('new_logo_rmv');
+                       $values['logo'] = $imgName;
+                       $img = '<img alt="'. $imgName . '" src="'.MEMBER_PHOTOS . $imgName.'">';
+
+                       //      If the old_logo_rmv key is set and not empty
+                       //      then we are replacing an existing logo and did not
+                       //      check the remove logo checkbox.
+                       //      remove this old logo just for good house keeping.
+                       if (isset($values['old_logo_rmv']) && !empty($values['old_logo_rmv'])) {
+                               $imgServer->imageDelete($values['old_logo_rmv']);
+                               //      update the elements on the form if we are replacing an existing logo.
+                               if ($this->elementExists('old_logo_rmv')) {
+                                       $e =& $this->getElement('old_logo_rmv');
+                                       $e->setValue($imgName);
+                               }
+                               if ($this->elementExists('image_rmv')) {
+                                       $e =& $this->getElement('image_rmv');
+                                       $e->setValue($img);
+                               }
+                       } else {
+                               $source =& $this->createElement(
+                    'checkbox',
+                    'remove_logo_rmv',
+                    'Remove Logo'
+                );
+                               $this->insertElementBefore($source, 'new_logo_rmv');
+
+                               $source =& $this->addElement('hidden', 'old_logo_rmv');
+                               $source->setValue($imgName);
+
+                               $source =& $this->createElement(
+                    'static',
+                    'image_rmv',
+                    'Current Image'
+                );
+                               $source->setValue($img);
+                               $element = $this->insertElementBefore($source, 'new_logo_rmv');
+
+                               if (PEAR::isError($element)) {
+                                       die ('there was an error uploading your file!');
+                               } else {
+                                       //  I don't know why, but the insertElementBefore
+                                       //  function was erasing the value we set earlier.
+                                       //  so just reset it to make double sure its there.
+                                       $element->setValue($img);
+                               }
+                       }
+               }
+
+               //      We clicked to remove the logo and did not upload a new one.
+               if ($values['remove_logo_rmv'] == 1 && $values['new_logo_rmv']['size'] == 0) {
+                       if ($this->elementExists('remove_logo_rmv')) {
+                               $this->removeElement('remove_logo_rmv', false);
+                       }
+                       if ($this->elementExists('image_rmv')) {
+                               $this->removeElement('image_rmv', false);
+                       }
+                       if ($this->elementExists('old_logo_rmv')) {
+                               $this->removeElement('old_logo_rmv', false);
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{ removeCategories()
+
+       /**
+        * Remove categories from the values['member_cats'] array
+        *
+        * Any values in the removeCats array are removed from the
+        * values['member_cats'] array which is passed in by reference
+        * so we don't have to return any values.
+        *
+        * @param array $targets All the category id's we want to remove
+        * @param array &$values All the categories submitte.
+        *
+     * @return void
+        * @access      protected
+        */
+       protected function removeCategories($targets, &$values)
+       {
+               foreach ($targets as $cid) {
+                       $key = array_search($cid, $values);
+                       unset($values[$key]);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ setConfig()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function setConfig(Config_Container $c)
+    {
+        $this->config = $c;
+    }
+
+    //  }}}
+    //  {{{ setStates()
+
+    /**
+     * Set the states available for the form
+     *
+     * @param array $states Array of states available for the form
+     *
+     * @return void
+     * @access public
+     */
+    public function setStates(array $states)
+    {
+        $this->states = $states;
+    }
+
+    //  }}}
+    //  {{{ setCities()
+
+    /**
+     * Set the cities available for the form
+     *
+     * @param array $cities Array of cities available for the form
+     *
+     * @return void
+     * @access public
+     */
+    public function setCities(array $cities)
+    {
+        $this->cities = $cities;
+    }
+
+    //  }}}
+       //      {{{     setLatLngCoords()
+
+    /**
+     * Description for setLatLngCoords()
+     *
+     * @param array &$values Values array
+     *
+     * @return void|mixed Only on pdo error
+     * @access protected
+     */
+       protected function setLatLngCoords(&$values)
+       {
+               $geocoder = new GeocodeYahoo();
+
+               $sql = "
+                       SELECT c.city_name, s.state_abb
+                         FROM city c, state s
+                        WHERE c.city_id  = :cityId
+                          AND s.state_id = :stateId";
+
+               try {
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':cityId', $values['city_id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':stateId', $values['state_id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('city_name', $cityName);
+                       $stmt->bindColumn('state_abb', $stateName);
+                       $stmt->fetch(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+               $address = array(
+                       'city' => $cityName,
+                       'state' => $stateName,
+                       'zip' => $values['zip'],
+               );
+               if (!empty($values['street'])) {
+                       $address['street'] = $values['street'];
+               }
+
+               if (   $this->elementExists('lat')
+                   && $this->elementExists('lon')
+               ) {
+                       try {
+                               $response = $geocoder->geocodeAddress($address);
+                               $responseArray = unserialize($response);
+                if ($responseArray['ResultSet']['Result'][0]['Latitude']) {
+                    $values['lat'] = $responseArray['ResultSet']['Result'][0]['Latitude'];
+                    $values['lon'] = $responseArray['ResultSet']['Result'][0]['Longitude'];
+                } else {
+                    $values['lat'] = $responseArray['ResultSet']['Result']['Latitude'];
+                    $values['lon'] = $responseArray['ResultSet']['Result']['Longitude'];
+                }
+
+                               $lat =& $this->getElement('lat');
+                               $lat->setValue($values['lat']);
+                               $lng =& $this->getElement('lon');
+                               $lng->setValue($values['lon']);
+                       } catch (BadMethodCallException $e) {
+                               Toolkit_Logger::logException('Invalid Arg', $e);
+                       } catch (Exception $e) {
+                               Toolkit_Logger::logException('Yahoo GeoCode', $e);
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ setupFormCategories()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupFormCategories()
+       {
+               try {
+                       //      Determine if this is a new member record or we're editing
+                       //      an existing member record.
+                       $member_id = $_GET['id'];
+                       //      Get all the categories already associated w/ this member.
+                       //      This part is primarily for editing existing members.
+                       //      That way they categories initially show up.
+                       //      They are ordered by the mem_cat_id which should keep
+                       //      them in the same order as they were added.
+                       $sql = "
+                SELECT *
+                  FROM member_category
+                 WHERE member_id = :id
+                                ORDER BY member_category_id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $member_id, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $memCats[$row['category_id']] = true;
+                       }
+
+                       //      If we submitted the form:
+                       //      1. Get all the member_cat values on the form that were submitted.
+                       //              If we flip the key/value pairs when we add the submitted values
+                       //              we won't have to worry about checking for duplicate cats submitted.
+                       //      2. If we clicked on a remove button determine the x/y coords
+                       //              (hint: the coords will be empty if we didn't click on one).
+                       //              if the coords are not empty, then remove the category we clicked
+                       //              on, it will be the removeCat form element.
+                       if ($this->isSubmitted()) {
+                               if (!is_array($memCats)) {
+                                       $memCats = array();
+                               }
+                               $submittedMemberCats = $this->getSubmitValue('member_cats');
+                               if (is_array($submittedMemberCats) && !empty($submittedMemberCats)) {
+                                       $memCats += array_flip($this->getSubmitValue('member_cats'));
+                               }
+                               //      Holds a possible array of category id's we want to remove.
+                               $removeTargets = $this->getSubmitValue('removeCat');
+                               //      If the array is not empty, then scoot through it and remove
+                               //      any of the categories form the memCats array so they won't
+                               //      show up again.
+                               if (!empty($removeTargets)) {
+                                       foreach ($removeTargets as $k => $v) {
+                                               unset($memCats[$v]);
+                                       }
+                               }
+                       }
+
+                       //      Unset the blank key so the sql query doesn't puke when trying to
+                       //      add it into the DB.  The blank key will occur if no cat is selected.
+                       //      its the default option for the select list.
+                       unset($memCats['']);
+                       $this->memberCategories = $memCats;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ setupRenderers()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+        $m = new Toolkit_Members_RecordNavigation($this->config);
+        $m->setupAdminNavStructure();
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+        $this->view->baseUrl = BASE_URL;
+               $this->view->form = $renderer->toObject();
+        $this->view->nav = $m->getPageNav();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+       //      {{{ showCategories()
+
+    /**
+     * Creates the <i> tags for the member categories
+     *
+     * @return string set of <i> tags for categories assigned to a member
+     * @access public
+     */
+       public function showCategories()
+       {
+               if (!empty($this->memberCategories)) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE category_id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               $out = '';
+                               foreach ($this->memberCategories as $cid => $v) {
+                                       $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                       $stmt->execute();
+                                       $category = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                                       $out .= '<i>';
+                                       $out .=         '<input id="catid'.$category['category_id'].'" ';
+                                       $out .=                 'type="hidden" name="member_cats[]" ';
+                                       $out .=                 'value="'.$category['category_id'].'">';
+                                       $out .=         '<label class="remove" for="'.$category['category_id'].'">';
+                                       $out .=                 '<input type="checkbox" name="removeCat[]" ';
+                                       $out .=                         'id="'.$category['category_id'].'" ';
+                                       $out .=                         'value="'.$category['category_id'].'">';
+                                       $out .=                 'Remove';
+                                       $out .=         '</label>';
+                                       $out .=         $category['name'];
+                                       $out .= '</i>';
+                               }
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               }
+
+               return $out;
+       }
+
+       //      }}}
+
+       //      {{{ toHTML()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+        * @return      string  The rendered form
+        * @access      public
+        */
+       public function toHTML()
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+               if ($this->validated) {
+                       $processed = $this->process(array(&$this, 'processData'), $this->mergeFiles);
+               }
+
+               //      ProcessData handles settingup the lat/lon coordinates if they were not entered
+               //      into the form.  these values ar calculated and then inserted into the forms
+               //      element values.  So we need to process the data first and then render the form.
+               $this->setupRenderers();
+
+               return $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the record data
+     *
+     * @param array $values scrubbed values submitted from the form
+     *
+     * @return object True on success
+     * @access public
+     */
+       public function updateData($values)
+       {
+        $addressUpdated = false;
+
+        $currentAddress = $this->getCurrentAddress();
+        // check current address with new one to see ifthere's a change
+        $newAddress = array(
+            'street'   => $values['street'],
+            'city_id'  => (int)$values['city_id'],
+            'state_id' => (int)$values['state_id'],
+            'zip'      => $values['zip']
+        );
+        if ($newAddress != $currentAddress) {
+            $values['lat'] = '';
+            $values['lon'] = '';
+        }
+
+               $member_id = $_GET['id'];
+               //      {{{ Golfing
+
+               //      Remove Golf Fields for Special Insert.
+               $fields = array(
+                       'par',
+                       'yardage',
+                       'course_rating',
+                       'slope_rating',
+                       'walking_course',
+                       'holes18',
+                       'holes9',
+               );
+
+               foreach ($fields as $v) {
+                       $golfFields[$v] = $values[$v];
+                       unset($values[$v]);
+               }
+
+               //      }}}
+               //      {{{ Accommodations
+
+               //      Remove Accommodation Fields for Special Insert.
+               $fields = array(
+                       'reservation_url',
+                       'reservation_id',
+                       'num_rooms',
+                       'year_round',
+               );
+               foreach ($fields as $v) {
+                       $accommodationFields[$v] = $values[$v];
+                       unset($values[$v]);
+               }
+
+               //      }}}
+               //      {{{ Restaurant
+
+               //      Remove Restaurant Fields for Special Insert.
+               $fields = array(
+                       'breakfast',
+                       'breakfast_from',
+                       'breakfast_to',
+                       'brunch',
+                       'brunch_from',
+                       'brunch_to',
+                       'lunch',
+                       'lunch_from',
+                       'lunch_to',
+                       'dinner',
+                       'dinner_from',
+                       'dinner_to',
+                       'alcohol',
+                       'non_smoking',
+               );
+               foreach ($fields as $v) {
+                       $restaurantFields[$v] = $values[$v];
+                       unset($values[$v]);
+               }
+
+               //      }}}
+
+               if (empty($values['lat']) || empty($values['lon'])) {
+                       try {
+                               $this->setLatLngCoords($values);
+                       } catch (Exception $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               }
+
+               //      Remove values not wanted before we get all the member categories.
+               if (isset($values['removeCat'])) {
+                       //      So remove them before we get the categories to insert for the member.
+                       $this->removeCategories($values['removeCat'], $values['member_cats']);
+               }
+               //      Now get the cats so we can insert them into a seperate table later.
+               $categories = $values['member_cats'];
+
+               $ccards = $values['creditCards'];
+               unset($values['member_cats'],
+                         $values['removeCat'],
+                         $values['creditCards']
+               );
+
+               try {
+                       $params = array_keys($values);
+                       $length = count($params);
+                       for ($i = 0; $i < $length; ++$i) {
+                               $bindParams .= "{$params[$i]} = :{$params[$i]}";
+                if ($i < ($length - 1)) {
+                    $bindParams .= ', ';
+                }
+                       }
+                       $this->dbh->beginTransaction();
+                       $sql = "
+                               UPDATE {$this->tableName}
+                                  SET $bindParams
+                                WHERE member_id = :member_id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT);
+                       foreach ($values as $k => &$v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               //      for empty values that are not actually a zero (0), we
+                               //      want to insert null's.
+                               //      This will help hold the unique values for member_logins,
+                               //      as empty values '', are not considered unique
+                               if (empty($v) && $v !== 0) {
+                                       $v = null;
+                                       $dataType = PDO::PARAM_NULL;
+                               }
+                               $stmt->bindParam(":$k", $v, $dataType);
+                       }
+                       $stmt->execute();
+
+                       //      Handle updating the credit cards
+                       $sql = "
+                DELETE FROM member_ccard_type
+                 WHERE member_id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $member_id, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       if (is_array($ccards)) {
+                               $sql = "
+                                       INSERT INTO member_ccard_type (member_id, ccard_type_id)
+                                       SELECT :id, ccard_type_id
+                                         FROM ccard_type
+                                        WHERE ccard_type_name = :cctn";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':id', $member_id, PDO::PARAM_INT);
+                               foreach ($ccards as $k => &$v) {
+                                       if ($v) {
+                                               $stmt->bindParam(':cctn', $k, PDO::PARAM_STR);
+                                               $stmt->execute();
+                                       }
+                               }
+                       }
+
+                       //      Handle updating the categories
+                       $sql = "
+                DELETE FROM member_category
+                 WHERE member_id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $member_id, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       if (is_array($categories)) {
+                               $sql = "
+                    INSERT INTO member_category (member_id, category_id)
+                    VALUES (:member_id, :cid)";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT);
+                               foreach ($categories as &$cid) {
+                                       if (!empty($cid)) {
+                                               $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                               $stmt->execute();
+                                       }
+                               }
+                       }
+
+                       $golf = $restaurant = $accommodations = false;
+                       if (!empty($categories)) {
+                               $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE category_id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               foreach ($categories as &$cid) {
+                                       if (!empty($cid)) {
+                                               $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                               $stmt->execute();
+                                               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                                               //      If any of the module statuses are true, set them.
+                                               //      otherwise leave them as they were, (we don't want
+                                               //      to set a true back to a false).
+                                               $golf = ($row['golf'] == 't') ? true : $golf;
+                                               $accommodations = ($row['accommodations'] == 't') ?
+                                                       true : $accommodations;
+                                               $restaurant = ($row['restaurant'] == 't') ?
+                                                       true : $restaurant;
+                                       }
+                               }
+                       }
+                       $this->clearModule('member_golf');
+                       if ($golf) {
+                               $this->updateModuleFields($golfFields, 'member_golf');
+                       }
+                       $this->clearModule('member_accommodations');
+                       if ($accommodations) {
+                               $this->updateModuleFields($accommodationFields, 'member_accommodations');
+                       }
+                       $this->clearModule('member_restaurants');
+                       if ($restaurant) {
+                               $this->updateModuleFields($restaurantFields, 'member_restaurants');
+                       }
+
+            $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+                       $cache->remove("Member-{$_GET['id']}", 'Profile');
+
+                       $ret = $this->dbh->commit();
+
+            $this->addMemberToStreamSend($_GET['id']);
+
+            return $ret;
+               } catch (PDOException $e) {
+                       $this->dbh->rollBack();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ updateModuleFields()
+
+       //      member_id in the params is for inserting the data if the form fails validation
+       //      first and comes back around and module categories will be included on the form
+       //      and you need to be able to insert the data and associate to the member.
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array   $values    Parameter description (if any) ...
+     * @param unknown $tableName Parameter description (if any) ...
+     * @param unknown $member_id Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+       protected function updateModuleFields(
+        $values,
+        $tableName,
+        $member_id = null
+    ) {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $tableName
+        );
+               $values['member_id'] = !is_null($member_id)
+                              ? $member_id
+                              : $_GET['id'];
+               try {
+                       $params = implode(', ', array_keys($values));
+                       $bindParams = ':' . implode(', :', array_keys($values));
+                       $sql = "
+                INSERT INTO $tableName ($params)
+                VALUES ($bindParams)";
+                       $stmt = $this->dbh->prepare($sql);
+                       foreach ($values as $k => &$v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               //      for empty values that are not actually a zero (0), we
+                               //      want to insert null's.
+                               //      This will help hold the unique values for member_logins,
+                               //      as empty values '', are not considered unique
+                               if (empty($v) && $v !== 0) {
+                                       $v = null;
+                                       $dataType = PDO::PARAM_NULL;
+                               }
+                               $stmt->bindParam(":$k", $v, $dataType);
+                       }
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ validated()
+
+       /**
+        * Checks if the form is validated
+        *
+        * If the form is validated display the success msg.
+        * If the form is submitted but not validated, display
+        * the error msg.  Other wise display nothing.
+        *
+        * This function is called from within the template.
+        *
+        * @return      string          The success or error msg for the user.
+        * @access      protected
+        */
+       public function validated()
+       {
+               if ($this->validated) {
+                       return $this->successMsg;
+               } elseif ($this->isSubmitted()) {
+                       return $this->errorMsg;
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberOnlyAmenities.php b/Toolkit/Members/EditMemberOnlyAmenities.php
new file mode 100644 (file)
index 0000000..9ff1d69
--- /dev/null
@@ -0,0 +1,454 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberOnlyAmenities.php,v 1.14 2010/07/18 16:44:51 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Short description for class
+ *
+ * Long description (if any) ...
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_EditMemberOnlyAmenities
+       extends Toolkit_Members_EditMemberAmenities implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * All the default data
+        *
+        * When we load the default data (member record from the database), we will
+        * store all that data in this variable. That way when we process the form
+        * we will have all the information to compare against, so we can find the
+        * updates.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $oldData;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        * @see    Toolkit_Members_EditMemberInfo
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+               $this->setPending();
+       }
+
+       //      }}}
+
+       //      {{{ createPendingData()
+
+       /**
+        * Make any changes into a pending state
+        *
+        * If strict pending is turned on, any changes that were made will
+        * have to fall into a pending state.  to do that we need to drop
+        * any update into the updates table.
+        *
+     * @param array $values submitted form values
+     *
+     * @return boolean
+        * @access Protected
+        */
+       protected function createPendingData($values)
+       {
+               try {
+                       $this->handleReconsiderations($values);
+                       //      Find out all the amenities the member currently has.
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE member_id = :member_id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $currentAmenities[] = $row['amenity_id'];
+                       }
+
+                       //      If they have no amenities already, we need to make sure
+                       //      this variable is at least defined as an array so
+                       //      we can get the array_diff.
+                       if (empty($currentAmenities)) {
+                               $currentAmenities = array();
+                       }
+                       //      Find out all the new amenities that where added.
+                       $alteredAmenities
+                = array_diff(array_keys($values), $currentAmenities);
+
+                       $sql = "
+                SELECT *
+                  FROM amenity
+                 WHERE amenity_id = :aid";
+                       $fetchStmt = $this->dbh->prepare($sql);
+                       $sql = "
+                               INSERT INTO member_updates (update, data_type, member_id, field,
+                               db_table, label)
+                               VALUES (:update, 'string', :member_id, :field, :table, :label)";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':table', $this->tableName, PDO::PARAM_STR);
+                       //      If any amenities where added
+                       //      insert them into the updates table to be in a pending state.
+                       if (!empty($alteredAmenities)) {
+                               $update = 1;
+                               $stmt->bindParam(':update', $update, PDO::PARAM_STR);
+                               foreach ($alteredAmenities as $k => &$v) {
+                                       $fetchStmt->bindParam(':aid', $v, PDO::PARAM_INT);
+                                       $fetchStmt->execute();
+                                       $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                                       $stmt->bindParam(':label', $row['amenity_name'], PDO::PARAM_STR);
+                                       $stmt->bindParam(':field', $v, PDO::PARAM_STR);
+                                       $stmt->execute();
+                               }
+                       }
+
+                       $update = 0;
+                       //      If any amenities are removed
+                       //      insert the removal request into the updates table
+                       //      so it can be in a pending state.
+                       foreach ($currentAmenities as $k => &$v) {
+                               if (!array_key_exists($v, $values)) {
+                                       $fetchStmt->bindParam(':aid', $v, PDO::PARAM_INT);
+                                       $fetchStmt->execute();
+                                       $row = $fetchStmt->fetch(PDO::FETCH_ASSOC);
+
+                                       $stmt->bindParam(':update', $update, PDO::PARAM_STR);
+                                       $stmt->bindParam(':label', $row['amenity_name'], PDO::PARAM_STR);
+                                       $stmt->bindParam(':field', $v, PDO::PARAM_STR);
+                                       $stmt->execute();
+                               }
+                       }
+
+                       return true;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+       /**
+        * Loads default values for the form
+        *
+        * Setup the members default values to load into the form.
+        * Copy all these values, which is the old data we will use to compare
+        * against when the form is submitted to determine the updates, into
+        * the oldData variable.
+        *
+        * @return void
+        * @access protected
+        */
+       public function configureDefaults()
+       {
+               $this->oldData = parent::configureDefaults();
+
+               try {
+                       $sql = "
+                SELECT field, \"update\"
+                  FROM member_updates
+                 WHERE id in (
+                                               SELECT max(id)
+                                                 FROM member_updates
+                 GROUP BY field)
+                   AND member_id = :member_id
+                                  AND db_table = '{$this->tableName}'";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $this->oldData[$row['field']] = (bool)$row['update'];
+                       }
+                       $this->setupDefaults($this->oldData);
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ fieldPending()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param object $elem Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+       public function fieldPending($elem)
+       {
+               if (!is_array($this->pendingFields)) {
+                       return false;
+               } else {
+                       return in_array($elem->label, $this->pendingFields);
+               }
+       }
+
+       // }}}
+
+       //      {{{ handleReconsiderations()
+
+       /**
+        * Makes amenities not pending anymore if they get re-added or re-removed
+        *
+        * These two cases both reset the field to its previous state before
+        * the original request was made.  So it bypasses the need of an admin
+        * to approve or reject the request, removes the fields from the updates
+        * table, and resets the field to its state before the request was made.
+        *
+        * If an amenity was added and removed before the admin has the ability
+        * to approve the request, we remove the field from the updates table
+        * and reset the pending field.  Same happens if an amenity is removed
+        * and added back in before the admin approves the removal request.
+        *
+        * @param mixed $values array of values submitted from the form.
+     *
+     * @return void
+        * @access public
+        */
+       protected function handleReconsiderations($values)
+       {
+               //      Get all the latest updates for this member's amenities.
+               $sql = "
+            SELECT *
+              FROM member_updates
+             WHERE id IN (
+                                       SELECT max(id)
+                                         FROM member_updates
+                                        WHERE member_id      = :member_id
+             GROUP BY field)
+               AND db_table = '{$this->tableName}'";
+               $stmt = $this->dbh->prepare($sql);
+               $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+               $stmt->execute();
+               while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                       $updates[$row['field']] = $row;
+               }
+
+               //      Set up the query to remove an amenity.
+               $sql = "
+                       DELETE FROM member_updates
+                        WHERE field    = :field
+                          AND db_table = '{$this->tableName}'
+                          AND member_id = :member_id";
+               $delStmt = $this->dbh->prepare($sql);
+               $delStmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+               //      This case can only happen if there are updates pending.
+               //      If any amenities were re-added or re-removed, then remove
+               //      them from the updates table cause they went back to their
+               //      original state.
+               if (!empty($updates)) {
+                       $updateableAmenities = array_keys($updates);
+                       foreach ($updateableAmenities as $k => &$v) {
+                               $keyExists = array_key_exists($v, $values);
+                               $adding = (bool) $updates[$v]['update'];
+                               //      Removed then added back in.
+                               $reAdded = (!$keyExists && $adding) ? true : false;
+                               //      Added then removed again.
+                               $reRemoved = ($keyExists && !$adding) ? true : false;
+
+                               if ($reAdded || $reRemoved) {
+                                       $delStmt->bindParam(':field', $v, PDO::PARAM_INT);
+                                       $delStmt->execute();
+                               }
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+       public function processData($values)
+       {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+
+               foreach ($values as $k => $v) {
+                       switch ($k) {
+                       default :
+                               if (preg_match('/^.+_rmv$/', $k)) {
+                                       unset($values[$k]);
+                               }
+                               break;
+                       }
+               }
+
+               $this->dbh->beginTransaction();
+               if ($this->updateData($values)) {
+                       // insert into pending table
+                       $this->dbh->commit();
+               } else {
+                       $this->dbh->rollBack();
+               }
+
+               $listPage = BASE_URL .
+            "members-only-area/?rt=EditProfile&tab=amenities";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ setPending()
+
+       /**
+        * Determines if the member has made any update requests
+        *
+        * Any update requests that are in the member_updates table
+        * will let us know if this member is pending or not.
+        *
+     * @return void
+        * @access protected
+        * @see    Toolkit_FormBuilder::setupElements()
+        */
+       public function setPending()
+       {
+               unset ($this->pendingFields);
+               try {
+                       $sql = "
+                SELECT DISTINCT label
+                  FROM {$this->pendingTable}
+                 WHERE member_id      = :member_id
+                   AND db_table = '{$this->tableName}'";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $this->pendingFields[] = $row['label'];
+                       }
+                       $this->pending = (count($this->pendingFields)) ? true : false;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ setupRenderers()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+        $m = new Toolkit_Members_RecordNavigation($this->config);
+        $m->setupUserNavStructure();
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+               $this->view->form = $renderer->toObject();
+        $this->view->nav = $m->getPageNav();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $values Parameter description (if any) ...
+     *
+     * @return unknown   Return description (if any) ...
+     * @access public
+     */
+       public function updateData($values)
+       {
+               $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-$id", 'Profile');
+
+               if ($this->strictPending) {
+                       $this->emailOwner();
+                       return $this->createPendingData($values);
+               } else {
+                       return parent::insertData($values);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberOnlyContacts.php b/Toolkit/Members/EditMemberOnlyContacts.php
new file mode 100644 (file)
index 0000000..c9d4da8
--- /dev/null
@@ -0,0 +1,722 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberOnlyContacts.php,v 1.15 2010/07/18 16:45:11 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handle associating contacts along with member records
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the business contacts. Form is not rendered until the user is added into the Database.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_EditMemberOnlyContacts
+       extends Toolkit_Members_EditMemberOnlyInfo implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data of the files
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_contacts';
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editContacts.tpl';
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               try {
+                       if (isset($_GET['cid'])) {
+                               $sql = "
+                                       select * from {$this->tableName} where id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':cid', $_GET['cid'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $defaults['id']                 = $row['id'];
+                               $defaults['title']              = $row['title'];
+                               $defaults['fname']              = $row['fname'];
+                               $defaults['lname']              = $row['lname'];
+                               $defaults['email']              = $row['email'];
+                               $defaults['phone']              = $row['phone'];
+                               $defaults['send_mail']  = $row['send_mail'];
+                       }
+            $sql = "
+              SELECT *, fname || ' ' || lname AS name,
+                     CASE send_mail
+                     WHEN 'true' THEN 'Can Mail'
+                     ELSE 'No Mail'
+                     END AS send_mail
+                FROM {$this->tableName}
+               WHERE member_id = :id
+                          ORDER BY id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $i = 0;
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $defaults["cid$i"]                      = $row['id'];
+                               $defaults["title$i"]            = $row['title'];
+                               $defaults["name$i"]             = $row['name'];
+                               $defaults["email$i"]            = $row['email'];
+                               $defaults["phone$i"]            = $row['phone'];
+                               $defaults["send_mail$i"]        = $row['send_mail'];
+                               ++$i;
+                       }
+                       $this->setupDefaults($defaults);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+        $e = array();
+               $contacts = $this->getMemberContacts();
+               //      All Grouped Elements are created here.
+               $submitText = (is_numeric($_GET['cid'])) ? 'Update' : 'Submit';
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'fileHdr',
+            'display' => 'Contacts'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'id'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'title',
+            'display' => 'Title',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'fname',
+            'display' => 'First Name',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'lname',
+            'display' => 'Last Name',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'email',
+            'display' => 'Email',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'phone',
+            'display' => 'Phone',
+            'opts' => array('class' => 'text')
+        );
+               $e[] = array(
+            'type' => 'advcheckbox',
+            'req' => false,
+            'name' => 'send_mail',
+            'display' => 'Receive Mail',
+            'val' => array(0,
+            1)
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => $submitText,
+            'opts' => array('class' => 'submit')
+        );
+               if (is_array($contacts)) {
+                       foreach ($contacts as $k => $v) {
+                               $e[] = array(
+                    'type' => 'header',
+                    'req' => false,
+                    'name' => "fileHdr$k"
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "cid$k"
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "name$k",
+                    'display' => 'Name'
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "title$k"
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "email$k",
+                    'display' => 'Email'
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "phone$k",
+                    'display' => 'Phone'
+                );
+                               $e[] = array(
+                    'type' => 'static',
+                    'req' => false,
+                    'name' => "send_mail$k",
+                    'display' => 'Receive Mail'
+                );
+                       }
+               }
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+        //  form rules
+        $r = array();
+               $this->registeredRules = array('phone', 'email');
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Invalid Email Address!',
+            'type' => 'email',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        /*
+               $r[] = array(
+            'element' => 'phone',
+            'message' => 'ERROR: Invalid Phone Number!',
+            'type' => 'phone',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        */
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     getDelUrl()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param object $sec Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+       public function getDelUrl($sec)
+       {
+               return $_SERVER['REQUEST_URI'] . "&d=t&cid={$sec->elements[0]->html}";
+       }
+
+       //      }}}
+       //      {{{     getEditUrl()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param object $sec Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+       public function getEditUrl($sec)
+       {
+               return $_SERVER['REQUEST_URI'] . "&cid={$sec->elements[0]->html}";
+       }
+
+       //      }}}
+       //      {{{     getMailIcon()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param object $sec Parameter description (if any) ...
+     *
+     * @return string Return description (if any) ...
+     * @access public
+     */
+       public function getMailIcon($sec)
+       {
+        if ($sec->html == 'No Mail') {
+            $icon = 'delete';
+            $title = 'Does not receive newsletters';
+        } else {
+            $icon = 'add';
+            $title = 'Receives newsletters';
+        }
+        return '<img width="16" height="16" title="'.$title.'"
+                   class="mail" alt="mail"
+                   src="'. GLM_APP_BASE_URL . "assets/icons/email_$icon.png" . '">';
+       }
+
+       //      }}}
+       //      {{{ getMemberContacts()
+
+       /**
+        * Get all the contacts data uploaded to a member into an array
+        *
+     * @return array member contacts
+        * @access protected
+        */
+       protected function getMemberContacts()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM {$this->tableName}
+                 WHERE member_id = :id
+                                ORDER BY id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $contacts[] = $row;
+                       }
+                       return $contacts;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access public
+     */
+       public function insertData($values)
+       {
+               unset(
+                       $values['id'],
+                       $values['target'],
+                       $values['submit']
+               );
+               $values['member_id'] = $_GET['id'];
+               try {
+                       $params = implode(', ', array_keys($values));
+                       $bindParams = ':' . implode(', :', array_keys($values));
+                       $sql = "
+                               INSERT INTO {$this->tableName} ($params)
+                               VALUES ($bindParams)";
+                       $stmt = $this->dbh->prepare($sql);
+                       foreach ($values as $k => $v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } elseif ($metaData == 'double precision') {
+                                       $dataType = null;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               $stmt->bindParam(":$k", $values[$k], $dataType);
+                       }
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+    }
+
+        //     }}}
+       //      {{{     isEmail()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isEmail($name)
+       {
+               return (substr($name, 0, 5) == 'email');
+       }
+
+       //      }}}
+       //      {{{ isForm()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $sec Parameter description (if any) ...
+     *
+     * @return unknown Return description (if any) ...
+     * @access public
+     */
+       public function isForm($sec)
+       {
+               return !$sec;
+       }
+
+       //      }}}
+       //      {{{     isName()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isName($name)
+       {
+               return (substr($name, 0, 4) == 'name');
+       }
+
+       //      }}}
+       //      {{{     isPhone()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isPhone($name)
+       {
+               return (substr($name, 0, 5) == 'phone');
+       }
+
+       //      }}}
+       //      {{{     isTitle()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $name Parameter description (if any) ...
+     *
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       public function isTitle($name)
+       {
+               return (substr($name, 0, 5) == 'title');
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+       public function processData($values)
+       {
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               if (empty($values['id'])) {
+                       $this->insertData($values);
+               } else {
+                       $this->updateData($values);
+               }
+               $listPage = BASE_URL .
+            "members-only-area/?rt=EditProfile&tab=contacts";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ removeContact()
+
+    /**
+     * Remove a contact from a member record
+     *
+     * @param integer $cid contact id
+     * @param integer $mid member id
+     *
+     * @return void
+     * @access public
+     */
+       public function removeContact($cid, $mid)
+       {
+               try {
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE id = :cid
+                   AND member_id = :mid";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                       $stmt->bindParam(':mid', $mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $target = BASE_URL .
+                               "members-only-area/?rt=EditProfile&tab=contacts";
+                       header("Location: $target");
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ setupRenderers()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+        $m = new Toolkit_Members_RecordNavigation($this->config);
+        $m->setupUserNavStructure();
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+               $this->view->form = $renderer->toObject();
+        $this->view->nav = $m->getPageNav();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+       //      {{{ show()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+       public function show()
+       {
+               if (isset($_GET['d'])) {
+                       $this->removeContact($_GET['cid']);
+                       $target = BASE_URL .
+                               "members-only-area/?rt=EditProfile&tab=contacts";
+                       header("Location: $target");
+               }
+               Toolkit_Common::show();
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access public
+     */
+       public function updateData($values)
+       {
+               if (array_key_exists('delete', $values)) {
+                       $this->deleteFile($values);
+               }
+
+               unset(
+                       $values['target'],
+                       $values['submit']
+               );
+
+               try {
+                       $params = array_keys($values);
+                       $length = count($params);
+                       for ($i = 0; $i < $length; ++$i) {
+                               $bindParams .= "{$params[$i]} = :{$params[$i]}";
+                if ($i < ($length - 1)) {
+                    $bindParams .= ', ';
+                }
+                       }
+                       $sql = "
+                               UPDATE {$this->tableName}
+                                  SET $bindParams
+                                WHERE id = :id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $pid, PDO::PARAM_INT);
+                       foreach ($values as $k => $v) {
+                               $metaData = $this->tableMetaData[$k];
+                               if ($metaData == 'integer') {
+                                       $dataType = PDO::PARAM_INT;
+                               } else if ($metaData == 'boolean') {
+                                       $dataType = PDO::PARAM_BOOL;
+                               } else {
+                                       $dataType = PDO::PARAM_STR;
+                               }
+                               $stmt->bindParam(":$k", $values[$k], $dataType);
+                       }
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberOnlyFile.php b/Toolkit/Members/EditMemberOnlyFile.php
new file mode 100644 (file)
index 0000000..f396c8f
--- /dev/null
@@ -0,0 +1,428 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberOnlyFile.php,v 1.14 2010/07/18 16:45:23 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Controls for uploading / editing files for a business record
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the business files. Form is not rendered until the user is added into the
+ * Database.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ * @see       Toolkit_Members_EditMemberInfo, Toolkit_Members_EditMemberFile
+ */
+class Toolkit_Members_EditMemberOnlyFile
+       extends Toolkit_Members_EditMemberFile implements Toolkit_Form
+{
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+               $this->setPending();
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form
+        *
+        * Handles setting the normal defaults by way of the parents function.
+        * Then overrides any caption updates by grabbing the latest update
+        * submitted for any caption in the updates table and sets those as
+        * the defaults instead.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               parent::configureDefaults();
+               try {
+                       //      Get all the latest file name updates for the files
+                       //      EXCEPT any file that has an update of [0].
+                       //      zero denotes a newly uploaded file and doesn't yet have
+                       //      a caption.
+                       $sql = "
+                SELECT 'mu.update', mf.id
+                  FROM {$this->pendingTable} mu, {$this->tableName} mf
+                 WHERE mu.id in (
+                                               SELECT max(id)
+                                                 FROM {$this->pendingTable}
+                                                WHERE db_table  =  '{$this->tableName}'
+                                                  AND member_id       =  :member_id
+                                                GROUP BY foreign_key)
+                   AND mu.field = 'file_name'
+                   AND mu.foreign_key = mf.id";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $fields[] = $row;
+                       }
+
+                       if (!empty($fields)) {
+                               $sql = "
+                                       SELECT count(*)
+                                         FROM {$this->tableName}
+                                        WHERE id      < :id
+                                          AND member_id     = :member_id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                               foreach ($fields as &$f) {
+                                       $stmt->bindParam(':id', $f['id'], PDO::PARAM_INT);
+                                       $stmt->execute();
+                                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                                       $defaults["file_name{$row['count']}"] = $f['update'];
+                               }
+                               $this->setupDefaults($defaults);
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ insertData()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return mixed     Return description (if any) ...
+     * @access public
+     */
+       public function insertData($values)
+       {
+               if ($this->strictPending) {
+                       try {
+                               $this->dbh->beginTransaction();
+                               //      Insert the file the normal way, w/ pending being true.
+                               parent::insertData($values, $pending = true);
+
+                               //      Get the last file inserted.
+                               $sql = "
+                                       SELECT *
+                                         FROM {$this->tableName}
+                                        WHERE pending = true
+                                          AND member_id     = :member_id
+                                        ORDER BY id DESC";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $file = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                               //      Insert the file into the updates table for approval.
+                               $fname = empty($values['file_name']) ?
+                                                       $values['file_rmv']['name'] :
+                                                       $values['file_name'];
+                               $imgTag = '<img src="'.BASE_URL.'images/file-ext/pdf.png"
+                                       alt="pdf Image" style="display: inline;">';
+                               $label = '<div class="pendingFileName">
+                                                       <a href="' . BASE_URL . $this->uploadDir .
+                                               $values['uploaded_file_rmv'].'" target="_blank">' .
+                                               $imgTag . $fname . '</a></div>';
+                               $update = false;
+                               $dataType = 'boolean';
+                               $field = 'pending';
+                               $sql =  "
+                                       INSERT INTO {$this->pendingTable}
+                                               (member_id, field, update, db_table, data_type, label, foreign_key)
+                                       VALUES
+                                               (:member_id, :field, :update, :db_table, :data_type, :label, :foreign_key)";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->bindParam(':field', $field, PDO::PARAM_STR);
+                               $stmt->bindParam(':update', $update, PDO::PARAM_BOOL);
+                               $stmt->bindParam(':db_table', $this->tableName, PDO::PARAM_STR);
+                               $stmt->bindParam(':data_type', $dataType, PDO::PARAM_STR);
+                               $stmt->bindParam(':label', $label, PDO::PARAM_STR);
+                               $stmt->bindParam(':foreign_key', $file['id'], PDO::PARAM_STR);
+                               $stmt->execute();
+                               $this->emailOwner();
+                               return $this->dbh->commit();
+                       } catch (PDOException $e) {
+                               $this->dbh->rollBack();
+                               return Toolkit_Common::handleError($e);
+                       }
+               } else {
+                       return parent::insertData($values);
+           }
+    }
+
+    // }}}
+
+    // {{{     pendingClass()
+
+       /**
+        * Returns a pending class for the file if it is in a pending state
+        *
+        * The offset passed in is controlled from the loop in the template
+        * that creates each file form.
+     *
+     * @param integer $offset which file we're dealing with
+        *
+     * @return mixed
+        * @access Protected
+        * @see    Toolkit_Members_EditMemberFile::getMemberFiles()
+        */
+    public function pendingClass($offset)
+    {
+        $files = $this->getMemberFiles();
+        //     If the offset is empty (0) then we know we're dealing
+        //     with the upload box.
+        if (empty($offset)) {
+            return;
+        } else {
+            // Otherwise we need to see if this file is pending or not.
+            try {
+                //     Get all the files that are pending in the updates table.
+                $sql = "
+                    SELECT DISTINCT foreign_key AS fid
+                      FROM {$this->pendingTable}
+                     WHERE db_table  = '{$this->tableName}'
+                       AND member_id = :member_id";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                $stmt->execute();
+                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                    $pendingFiles[] = $row['fid'];
+                }
+            } catch (PDOException $e) {
+                return Toolkit_Common::handleError($e);
+            }
+
+            --$offset;
+
+            // If our current file is in the pending table
+            // return the pending class.
+            if (   is_array($files)
+                               && is_array($pendingFiles)
+                               && in_array($files[$offset]['id'], $pendingFiles)
+                       ) {
+                return 'pending';
+            } else {
+                               return;
+                       }
+        }
+    }
+
+    // }}}
+       //      {{{ processData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param unknown $values Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+       public function processData($values)
+       {
+               $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-$id", 'Profile');
+
+               parent::processData($values);
+               $listPage = BASE_URL .
+            "members-only-area/?rt=EditProfile&tab=files";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ setPending()
+
+       /**
+        * Determines if the member has made any update requests
+        *
+        * Any update requests that are in the member_updates table
+        * will let us know if this member is pending or not.
+        *
+     * @return boolean
+        * @access protected
+        */
+       public function setPending()
+       {
+               unset ($this->pendingFields);
+               try {
+                       $sql = "
+                SELECT DISTINCT foreign_key AS fid
+                  FROM {$this->pendingTable}
+                 WHERE member_id      = :member_id
+                   AND db_table = '{$this->tableName}'";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $this->pendingFields[] = $row['fid'];
+                       }
+                       $this->pending = (count($this->pendingFields)) ? true : false;
+                       return true;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ setupRenderers()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+        $m = new Toolkit_Members_RecordNavigation($this->config);
+        $m->setupUserNavStructure();
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+               $this->view->form = $renderer->toObject();
+        $this->view->nav = $m->getPageNav();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $values Parameter description (if any) ...
+     *
+     * @return mixed     Return description (if any) ...
+     * @access public
+     */
+       public function updateData($values)
+       {
+               if ($this->strictPending) {
+                       if (array_key_exists('delete', $values)) {
+                               return $this->deleteFile($values);
+                       }
+                       try {
+                               $fid = $values["file{$values['target']}"];
+                               $sql = "
+                                       SELECT *
+                                         FROM {$this->tableName}
+                                        WHERE id      = :id";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':id', $fid, PDO::PARAM_INT);
+                               $stmt->execute();
+                               $file = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                               $fname = empty($file['file_name']) ?
+                                                       $file['original_name'] :
+                                                       $file['file_name'];
+                               $imgTag = '<img src="'.BASE_URL.'images/file-ext/pdf.png"
+                                       alt="pdf Image" style="display: inline;">';
+                               $label = '<a href="' . BASE_URL . $this->uploadDir .
+                                               $file['name_on_disk'].'" target="_blank">' .
+                                               $imgTag . $fname . '</a>';
+
+                               $dataType = 'text';
+                               $label = '<div class="pendingFileName">' .
+                                                       $label . 'File Name</div>';
+                               $field = 'file_name';
+                               $sql = "
+                    INSERT INTO {$this->pendingTable}
+                                               (member_id, field, update, db_table, data_type, label, foreign_key)
+                    VALUES
+                                               (:member_id, :field, :update, :db_table, :data_type, :label, :foreign_key)";
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->bindParam(':field', $field, PDO::PARAM_INT);
+                               $stmt->bindParam(':update', $values["file_name{$values['target']}"], PDO::PARAM_STR);
+                               $stmt->bindParam(':db_table', $this->tableName, PDO::PARAM_INT);
+                               $stmt->bindParam(':data_type', $dataType, PDO::PARAM_INT);
+                               $stmt->bindParam(':label', $label, PDO::PARAM_INT);
+                               $stmt->bindParam(':foreign_key', $fid, PDO::PARAM_INT);
+                               $this->emailOwner();
+                               return $stmt->execute();
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               } else {
+                       return parent::updateData($values);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditMemberOnlyInfo.php b/Toolkit/Members/EditMemberOnlyInfo.php
new file mode 100644 (file)
index 0000000..68ea7a5
--- /dev/null
@@ -0,0 +1,1248 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditMemberOnlyInfo.php,v 1.27 2010/03/12 18:22:53 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Edit member info stored in the database
+ *
+ * Controls all aspects of creating and rendering the form used to manipulate
+ * the member data.  Handles adding / editing module details, including:
+ * 1. Restaurants
+ * 2. Accommodations
+ * 3. Golfing
+ *
+ * Controls the addition of categories to a member record.  Categories have
+ * dynamic settings which allow users to dynamically set which categories are
+ * associated to which modules (golf, accommodations, restaurant, etc...).
+ * Depending on which category is selected and assigned to a member record
+ * controls which modules are displayed on the form.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_Members, member_admin
+ */
+class Toolkit_Members_EditMemberOnlyInfo
+    extends Toolkit_Members_EditMemberInfo implements Toolkit_Form
+{
+       //      {{{ properties
+
+       /**
+        * Set all the tables in the DB that hold the module info
+        *
+        * @var string
+        * @access protected
+        */
+       protected $moduleTables = array(
+               'member_golf' => array(),
+               'member_restaurants' => array(),
+               'member_accommodations' => array(),
+       );
+
+       /**
+        * All the default data
+        *
+        * When we load the default data (member record from the database), we will
+        * store all that data in this variable. That way when we process the form
+        * we will have all the information to compare against, so we can find the
+        * updates.
+        *
+        * @var string
+        * @access protected
+        */
+       protected $oldData;
+
+       //      }}}
+
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object to use for DB calls
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+     *
+        * @access public
+        * @see    Toolkit_Members_EditMemberInfo
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $pdo,
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+               $this->setPending();
+               //      Unset this so it won't get displayed.
+               $this->successMsg = null;
+       }
+
+       //      }}}
+
+       //      {{{ configureDefaults()
+
+       /**
+        * Loads default values for the form
+        *
+        * Setup the members default values to load into the form.
+        * Copy all these values, which is the old data we will use to compare
+        * against when the form is submitted to determine the updates, into
+        * the oldData variable.
+        *
+        * @return array default values
+        * @access protected
+        */
+       public function configureDefaults()
+       {
+               $this->oldData = parent::configureDefaults();
+
+               try {
+                       $sql = "
+                SELECT field, 'update'
+                  FROM {$this->pendingTable}
+                 WHERE id in (
+                                               SELECT max(id)
+                                                 FROM {$this->pendingTable}
+                                                WHERE member_id = :member_id
+                                                  AND (db_table = 'member' OR
+                                                               db_table = 'member_ccard_type' OR
+                                                               db_table = 'member_accommodations' OR
+                                                               db_table = 'member_restaurants' OR
+                                                               db_table = 'member_golf')
+                                                GROUP BY field)";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               if ($row['field'] == 'logo') {
+                                       $this->oldData['old_logo_rmv'] = $row['update'];
+                                       $row['update'] = '<img alt="'.$row['update'].'"
+                                               src="'.MEMBER_PHOTOS.$row['update'].'">';
+                                       $row['field'] = 'image_rmv';
+                               }
+                               $this->oldData[$row['field']] = $row['update'];
+                       }
+                       return $this->setupDefaults($this->oldData);
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * Categories are populated into the protected class property $categories.
+        * These categories are used to populate the select list of categories.
+        * Modules are configured before any elements are setup, that way we will
+        * know if we need to include them in the rendering of the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements()
+       {
+               $e = array();
+
+               $singularType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+               $pluralType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+               $useCtrlCities = $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'controlledCities')
+                       ->getContent();
+               $allowRegions = $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'regions')
+                       ->getContent();
+               $usesGlmReservations= $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'glmReservations')
+                       ->getContent();
+
+               $this->setupFormCategories();
+               $this->configureModules();
+
+               $this->getCategories();
+
+               //      All Grouped Elements are created here.
+               //      All Elements are created here.  This includes group element definitions.
+
+               //      {{{ Member Information
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'memberInfoHdr',
+                       'display' => "$singularType Information",
+                       'col1'    => true
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'primary_contact_fname',
+                       'display' => 'Primary Contact First Name',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'primary_contact_lname',
+                       'display' => 'Primary Contact Last Name',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'process_email',
+                       'display' => 'Primary Contact Email',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'phone',
+                       'display' => 'Primary Phone',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'toll_free',
+                       'display' => 'Phone 2',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'fax',
+                       'display' => 'Fax Number',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'member_contact_email',
+                       'display' => 'Email on Website',
+                       'opts'    => array('class' => 'text')
+               );
+               /*
+               $e[] = array(
+                       'type'    => 'select',
+                       'req'     => false,
+                       'name'    => 'country',
+                       'display' => 'Country',
+                       'opts'    => array(
+                               ''       => '-- Select Country --',
+                               'USA'    => 'USA',
+                               'Canada' => 'Canada'
+                       )
+               );
+               */
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'url',
+                       'display' => 'Website Address',
+                       'opts'    => array('class' => 'text'),
+            'noCharLimit' => true
+               );
+
+        //  }}}
+               //      {{{     Member Categories
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'memberCategoryHdr',
+                       'display' => "$singularType Categories",
+                       'col1'    => true
+               );
+               $e[] = array(
+                       'type'    => 'static',
+                       'req'     => false,
+                       'name'    => 'member_cats[]',
+                       'opts'    => $this->categories,
+                       'att'     => array('id' => 'categories')
+               );
+
+               //      }}}
+               //      {{{ Physical Address
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'physicalAddressHdr',
+                       'display' => 'Street Address',
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'street',
+                       'display' => 'Street Address',
+                       'opts'    => array('class' => 'text')
+               );
+        if ($useCtrlCities) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => true,
+                'name'    => 'city_id',
+                'display' => 'City',
+                'opts'    => array('' => '-- Select --') + $this->cities
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => true,
+                'name'    => 'city',
+                'display' => 'City',
+                'opts'    => array('class' => 'text')
+            );
+        }
+               $e[] = array(
+                       'type'    => 'select',
+                       'req'     => true,
+                       'name'    => 'state_id',
+                       'display' => 'State / Province',
+                       'opts'    => array('' => '-- Select --') + $this->states
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => true,
+                       'name'    => 'zip',
+                       'display' => 'Zip / Postal Code',
+                       'opts'    => array('class' => 'text')
+               );
+
+        //  }}}
+               //      {{{ Mailing Address
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'MailingAddressHdrRmv',
+                       'display' => 'Mailing Address (if different than physical address)',
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'mailing_address',
+                       'display' => 'Mailing Address',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'mailing_city',
+                       'display' => 'City',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'select',
+                       'req'     => false,
+                       'name'    => 'mailing_state_id',
+                       'display' => 'State / Province',
+                       'opts'    => array('' => '-- Select --') + $this->states
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'mailing_zip',
+                       'display' => 'Zip / Postal Code',
+                       'opts'    => array('class' => 'text')
+               );
+
+        //  }}}
+               //      {{{ Member Description
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'memberDescHdr',
+                       'display' => "$singularType Description",
+                       'col1'    => true
+               );
+               $e[] = array(
+                       'type'    => 'textarea',
+                       'req'     => false,
+                       'name'    => 'description',
+                       'display' => 'Description',
+                       'opts'    => array(
+                               'id'   => 'description',
+                               'rows' => 8,
+                               'cols' => 43
+                       ),
+            'noCharLimit' => true
+               );
+
+        //  }}}
+               //      {{{ Account Info
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'accountInfoHdr',
+                       'display' => 'Account Info',
+                       'col2'    => true
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'member_login',
+                       'display' => 'Username',
+                       'opts'    => array('class' => 'text')
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'member_passwd',
+                       'display' => 'Password',
+                       'opts'    => array('class' => 'text')
+               );
+
+        //  }}}
+               //      {{{ Main Image
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'logoHdr',
+                       'display' => 'Main Image',
+                       'col2'    => true
+               );
+               if ($this->hasLogo()) {
+                       $e[] = array(
+                               'type'    => 'checkbox',
+                               'req'     => false,
+                               'name'    => 'remove_logo_rmv',
+                               'display' => 'Remove Image'
+                       );
+                       $e[] = array(
+                               'type'    => 'static',
+                               'req'     => false,
+                               'name'    => 'image_rmv',
+                               'display' => 'Current Image'
+                       );
+            $e[] = array(
+                               'type' => 'hidden',
+                               'req'  => false,
+                               'name' => 'old_logo_rmv'
+                       );
+               }
+
+               $e[] = array(
+                       'type'    => 'file',
+                       'req'     => false,
+                       'name'    => 'new_logo_rmv',
+                       'display' => 'New Image',
+                       'opts'    => array('class' => 'file')
+               );
+
+        //  }}}
+               //      {{{ Payment Type Accepted
+
+               $e[] = array(
+                       'type'    => 'header',
+                       'req'     => false,
+                       'name'    => 'CreditCardsHdr',
+                       'display' => 'Payment Type Accepted',
+                       'col2'    => true
+               );
+               $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'creditCards[American Express]',
+                       'display' => 'American Express',
+                       'val'     => array(0, 1)
+               );
+               $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'creditCards[Discover]',
+                       'display' => 'Discover',
+                       'val'     => array(0, 1)
+               );
+               $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'creditCards[Master Card]',
+                       'display' => 'Master Card',
+                       'val'     => array(0, 1)
+               );
+               $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'creditCards[Visa]',
+                       'display' => 'Visa',
+                       'val'     => array(0, 1)
+               );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'creditCards[Diners]',
+                       'display' => 'Diners'
+               );
+
+        //  }}}
+               //      {{{ Accommodations Information
+
+               if ($this->accommodations) {
+                       $e[] = array(
+                               'type'    => 'header',
+                               'req'     => false,
+                               'name'    => 'AccommodationsHdr',
+                               'display' => 'Accommodations Information',
+                               'col2'    => true
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'reservation_url',
+                               'display' => 'Reservation Url',
+                               'opts'    => array('class' => 'text')
+                       );
+                       if ($usesGlmReservations) {
+                               $e[] = array(
+                                       'type'    => 'text',
+                                       'req'     => false,
+                                       'name'    => 'reservation_id',
+                                       'display' => 'Reservation Id',
+                                       'opts'    => array('class' => 'text')
+                               );
+                       }
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'num_rooms',
+                               'display' => 'Number of Rooms',
+                               'opts'    => array('class' => 'text')
+                       );
+                       $e[] = array(
+                               'type'    => 'advcheckbox',
+                               'req'     => false,
+                               'name'    => 'year_round',
+                               'display' => 'Open all Year',
+                               'val'     => array(0, 1)
+                       );
+               }
+
+        //  }}}
+               //      {{{ Restaurant Information
+
+               if ($this->restaurant) {
+                       $e[] = array(
+                               'type'    => 'header',
+                               'req'     => false,
+                               'name'    => 'RestaurantHdr',
+                               'display' => 'Restaurant Information',
+                               'col2'    => true
+                       );
+                       $e[] = array(
+                               'type'    => 'advcheckbox',
+                               'req'     => false,
+                               'name'    => 'breakfast',
+                               'display' => 'Breakfast',
+                               'att'     => array('id' => 'breakfast'),
+                               'val'     => array(0, 1)
+                       );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'breakfast_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'breakfast_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+                       $e[] = array(
+                               'type'    => 'advcheckbox',
+                               'req'     => false,
+                               'name'    => 'brunch',
+                               'display' => 'Brunch',
+                               'att'     => array('id' => 'brunch'),
+                               'val'     => array(0, 1)
+                       );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'brunch_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'brunch_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+                       $e[] = array(
+                               'type'    => 'advcheckbox',
+                               'req'     => false,
+                               'name'    => 'lunch',
+                               'display' => 'Lunch',
+                               'att'     => array('id' => 'lunch'),
+                               'val'     => array(0, 1)
+                       );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'lunch_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'lunch_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+                       $e[] = array(
+                               'type'    => 'advcheckbox',
+                               'req'     => false,
+                               'name'    => 'dinner',
+                               'display' => 'Dinner',
+                               'att'     => array('id' => 'dinner'),
+                               'val'     => array(0, 1)
+                       );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'dinner_from',
+//                             'display' => 'From',
+//                             'opts'    => array('class' => 'priceFrom')
+//                     );
+//                     $e[] = array(
+//                             'type'    => 'text',
+//                             'req'     => false,
+//                             'name'    => 'dinner_to',
+//                             'display' => 'To',
+//                             'opts'    => array('class' => 'priceTo')
+//                     );
+                       $e[] = array(
+                               'type'    => 'advcheckbox',
+                               'req'     => false,
+                               'name'    => 'alcohol',
+                               'display' => 'Alcohol',
+                               'val'     => array(0, 1)
+                       );
+//                     $e[] = array(
+//                             'type'    => 'advcheckbox',
+//                             'req'     => false,
+//                             'name'    => 'non_smoking',
+//                             'display' => 'Non-Smoking',
+//                             'val'     => array(0, 1)
+//                     );
+               }
+
+        //  }}}
+               //      {{{ Golf Information
+
+               if ($this->golf) {
+                       $e[] = array(
+                               'type'    => 'header',
+                               'req'     => false,
+                               'name'    => 'GolfingHdr',
+                               'display' => 'Golf Course Information',
+                               'col2'    => true
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'par',
+                               'display' => 'Par',
+                               'opts'    => array('class' => 'text')
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'yardage',
+                               'display' => 'Yardage',
+                               'opts'    => array('class' => 'text')
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'course_rating',
+                               'display' => 'Course Rating',
+                               'opts'    => array('class' => 'text')
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'slope_rating',
+                               'display' => 'Slope Rating',
+                               'opts'    => array('class' => 'text')
+                       );
+                       $e[] = array(
+                               'type'    => 'advcheckbox',
+                               'req'     => false,
+                               'name'    => 'walking_course',
+                               'display' => 'Walking Course',
+                               'val'     => array(0, 1)
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'holes18',
+                               'display' => '18 Holes',
+                               'opts'    => array('class' => 'text')
+                       );
+                       $e[] = array(
+                               'type'    => 'text',
+                               'req'     => false,
+                               'name'    => 'holes9',
+                               'display' => '9 Holes',
+                               'opts'    => array('class' => 'text')
+                       );
+               }
+
+        //  }}}
+        //  {{{ Social Media Links
+
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'SocialMediaHdr',
+            'display' => 'Social Media Links',
+            'col2' => true,
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'facebook',
+            'display' => 'Facebook',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'twitter',
+            'display' => 'Twitter',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'myspace',
+            'display' => 'MySpace',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'linkedin',
+            'display' => 'LinkedIn',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'blog',
+            'display' => 'Blog',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'youtube',
+            'display' => 'YouTube',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'pinterest',
+            'display' => 'Pinterest',
+            'col2' => true,
+            'noCharLimit' => true
+        );
+
+        //  }}}
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+
+       //      {{{     processData()
+
+       /**
+        * Handles processing the submitted forms data
+        *
+        * See parent function for better description.
+        *
+        * @param array $values The array of all submitted form values.
+        *
+        * @return boolean Whether the insert/update succeeded.
+        * @access public
+        * @see    Toolkit_Members_EditMemberInfo::processData()
+        */
+       public function processData($values)
+       {
+               $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-$id", 'Profile');
+
+               $return = parent::processData($values);
+               $this->setPending();
+               return $return;
+       }
+
+       //      }}}
+
+       //      {{{ setPending()
+
+       /**
+        * Determines if the member has made any update requests
+        *
+        * Any update requests that are in the member_updates table
+        * will let us know if this member is pending or not.
+        *
+     * @return void
+        * @access public
+        */
+       public function setPending()
+       {
+               unset ($this->pendingFields);
+               try {
+                       $sql = "
+                SELECT DISTINCT
+                       CASE field
+                       WHEN 'lat' THEN 'latitude'
+                       WHEN 'lon' THEN 'longitude'
+                       WHEN 'logo' THEN 'image_rmv'
+                       ELSE field
+                       END AS field
+                  FROM {$this->pendingTable}
+                 WHERE member_id        = :member_id
+                                  AND (db_table = '{$this->tableName}'
+                                  OR db_table = 'member_ccard_type'
+                                  OR db_table = 'member_restaurants'
+                                  OR db_table = 'member_accommodations'
+                                  OR db_table = 'member_golf')";
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $this->pendingFields[] = $row['field'];
+                       }
+                       $this->pending = (count($this->pendingFields));
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{ setupRenderers()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($this->flexyOptions);
+
+        $m = new Toolkit_Members_RecordNavigation($this->config);
+        $m->setupUserNavStructure();
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+               $this->view->form = $renderer->toObject();
+        $this->view->nav = $m->getPageNav();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+       //      {{{ showCategories()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return string Return description (if any) ...
+     * @access public
+     */
+       public function showCategories()
+       {
+               if (!empty($this->memberCategories)) {
+                       try {
+                               $sql = "
+                                       SELECT *
+                                         FROM category
+                                        WHERE category_id = :cid";
+                               $stmt = $this->dbh->prepare($sql);
+                               foreach ($this->memberCategories as $cid => $v) {
+                                       $stmt->bindParam(':cid', $cid, PDO::PARAM_INT);
+                                       $stmt->execute();
+                                       $category = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                                       $out .= '
+                                               <i>
+                                                       <input id="catid'.$category['category_id'].'"
+                                                               type="hidden" name="member_cats[]"
+                                                               value="'.$category['category_id'].'" >';
+                                       if (   defined('MEMBERS_ONLY_AREA_ON')
+                                               && MEMBERS_ONLY_AREA_ON == true
+                                       ) {
+                                               //      do nothing
+                                       } else {
+                                               $out .= '
+                                                       <input type="image" name="removeCat" height="16" width="16"
+                                                               class="remove" src="'.BASE_URL.'assets/cancel.png"
+                                                               value="'.$category['category_id'].'" >';
+                                       }
+                                       $out .= "{$category['name']}</i>";
+                               }
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+               }
+
+               return $out;
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+       /**
+        * Insert the values that were updated from the member only form
+        *
+        * 1. Get all the field types in the DB for the module tables
+        * 2. Check the module fields against the old Data (the original values
+        *        we obtained when we got the defaults for the form).  If the
+        *        value is not the same, then add the value to the column field of
+        *        the table in the moduleUpdates array.
+        * 3. Get the updates for the member record.
+        * 4. Insert all the updates into the member_updates table.
+     *
+     * @param array $values submitted form values
+        *
+     * @return mixed
+        * @access public
+        */
+       public function updateData($values)
+       {
+               if ($this->strictPending) {
+                       foreach ($this->moduleTables as $tname => &$arr) {
+                               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+                    $this->dbh,
+                    $tname
+                );
+                               if (is_array($this->tableMetaData)) {
+                                       foreach ($this->tableMetaData as $k => $v) {
+                                               switch ($k) {
+                                               case 'id' :
+                                               case 'member_id' :
+                                                       break;
+
+                                               default :
+                                                       $arr[$k]['data_type'] = $v;
+                                                       $arr[$k]['value'] = $values[$k];
+                                                       unset($values[$k]);
+                                                       break;
+                                               }
+                                       }
+                               }
+                       }
+                       //      Check for updates in the module tables.
+                       foreach ($this->moduleTables as $tname => &$arr) {
+                               foreach ($arr as $k => $v) {
+                                       if (array_key_exists($k, $this->oldData)) {
+                                               if ($v['data_type'] != 'boolean') {
+                                                       if ($v['value'] != $this->oldData[$k]) {
+                                                               $moduleUpdates[$tname][$k] = $v;
+                                                       }
+                                               } else {
+                                                       //      Due to how PDO's cast a boolean value False
+                                                       //      to '' when you query the DB.
+                                                       //      we need to adjust any empty fields
+                                                       //      that are of data_type boolean to a 0, True
+                                                       //      values are queried as 1.
+                                                       //      See:  http://bugs.php.net/bug.php?id=33876
+                                                       //      for more info.
+                                                       $oldData = (empty($this->oldData[$k])) ? 0 : 1;
+                                                       if ($v['value'] != $oldData) {
+                                                               $moduleUpdates[$tname][$k] = $v;
+                                                       }
+                                               }
+                                               //      If the field was set in the module Updates array
+                                               //      then also try and set what type of field we are
+                                               //      dealing w/ on the form.
+                                               if (isset($moduleUpdates[$tname][$k])) {
+                                                       if ($this->elementExists($k)) {
+                                                               $e =& $this->getElement($k);
+                                                               if (PEAR::isError($e)) {
+                                                                       return Toolkit_Common::handleError($e);
+                                                               }
+                                                               $moduleUpdates[$tname][$k]['field_type'] = $e->getType();
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+
+                       //      Need a special case for the credit cards.
+            if (is_array($values['creditCards'])) {
+                foreach ($values['creditCards'] as $k => $v) {
+                    if (array_key_exists("creditCards[$k]", $this->oldData)) {
+                        if ($v != $this->oldData["creditCards[$k]"]) {
+                            $ccUpdates["creditCards[$k]"]['data_type'] = 'integer';
+                            $ccUpdates["creditCards[$k]"]['value'] = $v;
+                        }
+                    } elseif (!empty($v)) {
+                        $ccUpdates["creditCards[$k]"]['data_type'] = 'integer';
+                        $ccUpdates["creditCards[$k]"]['value'] = $v;
+                    }
+                    // If the credit card was set in the credit card updates array
+                    // then also try and set what type of field we are dealing w/
+                    // on the form.
+                    if (isset($ccUpdates["creditCards[$k]"])) {
+                        if ($this->elementExists("creditCards[$k]")) {
+                            $e =& $this->getElement("creditCards[$k]");
+                            if (PEAR::isError($e)) {
+                                return Toolkit_Common::handleError($e);
+                            }
+                            $ccUpdates["creditCards[$k]"]['field_type'] = $e->getType();
+                        }
+                    }
+                }
+            }
+               } else {
+                       return parent::updateData($values);
+               }
+
+               $ccards = $values['creditCards'];
+               $pattern = '/^-?(.+)$/i';
+               $replacement = '$1';
+               //      Adjust the lat/lon coordinates to negative #'s if needed
+               $coords = array('lat' => 'South', 'lon' => 'East');
+               foreach ($coords as $k => $v) {
+                       if ($values["{$k}Direction"] == $v && !empty($values[$k])) {
+                               $string = $values[$k];
+                               $values[$k] = preg_replace($pattern, $replacement, $string);
+                               $values[$k] = "-{$values[$k]}";
+                       }
+               }
+               unset($values['lonDirection'],
+                       $values['latDirection'],
+                       $values['member_cats'],
+                       $values['creditCards']
+               );
+
+        $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               //      Check for updates in the member record.
+               //      If we find any, add that field to the list of record updates
+               //      along with what type of field it is in the member table.
+               //      We will use the data_type field when the admin is dealing
+               //      w/ the updates to determine values on boolean records and empty
+               //      text field records.
+               foreach ($values as $k => $v) {
+                       if (array_key_exists($k, $this->oldData)) {
+                               if ($v != $this->oldData[$k]) {
+                                       if ($this->elementExists($k)) {
+                                               $e =& $this->getElement($k);
+                                               if (PEAR::isError($e)) {
+                                                       return Toolkit_Common::handleError($e);
+                                               }
+                                               $recordUpdates[$k]['field_type'] = $e->getType();
+                                       }
+                                       $recordUpdates[$k]['data_type'] = $this->tableMetaData[$k];
+                                       $recordUpdates[$k]['value'] = $v;
+                               }
+                       }
+                       //      We need a special case for the member image. cause Its a pain
+                       //      in the ass.
+                       if ($k == 'logo') {
+                               if (!empty($v)) {
+                                       if (array_key_exists('old_logo_rmv', $this->oldData)) {
+                                               if ($v != $this->oldData['old_logo_rmv']) {
+                                                       $recordUpdates[$k]['data_type'] = 'boolean';
+                                                       $recordUpdates[$k]['field_type'] = 'file';
+                                                       $recordUpdates[$k]['value'] = $v;
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               //      Combine the update arrays for the modules and the member record
+               //      into one single array. The array will hold this pattern.
+               //      An array of tables that holds an array of fields that were updated
+               //      [DB Table] => array
+               //              (
+               //                      [Column Name] => array
+               //                              (
+               //                                      [data_type] => boolean / text / integer
+               //                                      [field_type] => text / select / checkbox
+               //                                      [value] => updated value from the form.
+               //                              )
+               //              )
+               //      Make sure to only add these array's if there is update information
+               //      in them.
+               $updates = array();
+               if (is_array($moduleUpdates)) {
+                       $updates += $moduleUpdates;
+               }
+               if (is_array($recordUpdates)) {
+                       $updates += array('member' => $recordUpdates);
+               }
+               if (is_array($ccUpdates)) {
+                       $updates += array('member_ccard_type' => $ccUpdates);
+               }
+
+               try {
+                       //      If we have an array of updates, we need to insert all the
+                       //      updates into the member_updates table.  This will signal that
+                       //      the member has pending updates that the admin needs to
+                       //      authorize.
+                       if (!empty($updates)) {
+                               //      Loop through all the elements that were updated and get
+                               //      the label we use on the form so when the admin is looking
+                               //      at the updates they will know what field its for.
+                               //      We can be sure we are getting the right label because
+                               //      there can only be unique element names in the form.
+                               foreach ($updates as &$sec) {
+                                       foreach ($sec as $field => $v) {
+                                               switch ($field) {
+                        case 'lat' :
+                            $g =& $this->getElement('latitude');
+                            $e =& $g->getElements();
+                            $sec[$field]['label'] = $e[1]->getLabel();
+                            break;
+
+                        case 'lon' :
+                            $g =& $this->getElement('longitude');
+                            $e =& $g->getElements();
+                            $sec[$field]['label'] = $e[1]->getLabel();
+                            break;
+
+                        case '' :
+                        case null :
+                            break;
+
+                        default :
+                            $e =& $this->getElement($field);
+                            // Check to make sure an actual element was
+                            // returned.  If a "module" is unassigned from a
+                            // category, those elements will not be created.
+                            // so we won't be able to get the labels for those
+                            // elements.  In this case, just use the field
+                            // name.
+                            if (PEAR::isError($e)) {
+                                $sec [$field]['label'] = $field;
+                            } else {
+                                $sec[$field]['label'] = $e->getLabel();
+                            }
+                            break;
+                                               }
+                                       }
+                               }
+                               $this->dbh->beginTransaction();
+
+                               $sql = "
+                                       INSERT INTO {$this->pendingTable} (member_id, field, update, db_table, data_type, field_type, label)
+                                        VALUES (:member_id, :field, :update, :table, :data_type, :field_type, :label)";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $GLOBALS['memberAuth']->getAuthData('member_id'), PDO::PARAM_INT);
+                               foreach ($updates as $table => &$sec) {
+                                       $stmt->bindParam(':table', $table, PDO::PARAM_STR);
+                                       foreach ($sec as $k => &$v) {
+                                               $dataType = PDO::PARAM_STR;
+                                               //      Fields that are empty which have a data_type of text
+                                               //      can be inserted as NULL values.
+                                               if (empty($v['value']) && $v['data_type'] == 'text') {
+                                                       $v['value'] = null;
+                                                       $dataType = PDO::PARAM_NULL;
+                                               }
+                                               $stmt->bindParam(":field", $k, PDO::PARAM_STR);
+                                               $stmt->bindParam(":update", $v['value'], $dataType);
+                                               $stmt->bindParam(":data_type", $v['data_type'], PDO::PARAM_STR);
+                                               $stmt->bindParam(":field_type", $v['field_type'], PDO::PARAM_STR);
+                                               $stmt->bindParam(":label", $v['label'], PDO::PARAM_STR);
+                                               $stmt->execute();
+                                       }
+                               }
+                               $this->setPending();
+                               $this->emailOwner();
+                               return $this->dbh->commit();
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+               return;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/EditPackages.php b/Toolkit/Members/EditPackages.php
new file mode 100644 (file)
index 0000000..49c7ef0
--- /dev/null
@@ -0,0 +1,1928 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles the packages tab in the member record
+ *
+ * Controls setting up the add package form if applicable, and rendering
+ * each uploaded package edit form to edit/delete the package.
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditPackages.php,v 1.16 2010/07/18 16:45:33 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit/Image/Server.php
+ */
+
+
+/**
+ * The image server processing class
+ */
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Constructor class to setup the page layout
+ *
+ * this class determines if the user can upload any more packages to their
+ * account and if so renders the add package form.  It also controls
+ * rending the individual forms for each previously uploaded package.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_EditPackages extends Toolkit_Members_Admin_EditPackages
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_packages';
+
+    /**
+     * Template used to layout form when editing a package
+     * @var    string
+     * @access protected
+     */
+       protected $pageTemplate = 'editPackages.tpl';
+
+       /**
+        * Sets the max number of packages allowed for each listing
+        * @var integer
+        * @access protected
+        */
+       protected $maxPackages = 2;
+
+    /**
+     * What is the maximum caption length for packages
+        *
+     * @var    array
+     * @access public
+     * @static
+     */
+       static public $maxTitleLength = 60;
+
+    /**
+     * Objects that will go into the page (add form, edit package forms)
+     * @var    object
+     * @access protected
+     */
+       protected $page;
+
+    /**
+     * Description for protected
+     * @var    PDO
+     * @access protected
+     */
+    protected $dbh;
+
+       //      }}}
+       //      {{{     canAddPackages()
+
+       /**
+        * Determine if this member can have more packages added to their profile
+        *
+        * Load the entire package gallery into member via a linked list.
+        * Then return if the # of linked list nodes is smaller than
+        * the maximum limit of packages.
+        *
+        * @access protected
+        * @return boolean If the linked list is smaller than max packages allowed
+        */
+       protected function canAddPackages()
+       {
+        $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+               $ll = new Toolkit_Members_Packages(null, $id);
+        $ll->setDbh($this->dbh);
+               $ll->createMemberList();
+               return ($ll->getListSize() < $this->maxPackages);
+       }
+
+       //      }}}
+
+       //      {{{     displayPage()
+
+    /**
+     * Displays the page to the screen
+     *
+     * @return void
+     * @access public
+     */
+       public function displayPage()
+       {
+               echo $this->getPage();
+       }
+
+       //      }}}
+
+       //      {{{     getUploadedPackages()
+
+       /**
+        * Get an array of package ids from the DB that have been uploaded for this member
+        *
+        * - Create a linked list of all the members packages
+        * - Walk through the linked list extracting the id from each node into an array
+        *
+        * @access protected
+        * @return array Ids of all uploaded packages for this member
+        */
+       protected function getUploadedPackages()
+       {
+        $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+               $packages = new Toolkit_Members_Packages(null, $id);
+        $packages->setDbh($this->dbh);
+               $packages->createMemberList();
+               $packages->rewind();
+
+               $ids = array();
+               foreach ($packages as $i) {
+                       $ids[] = $i->getId();
+               }
+
+               return $ids;
+       }
+
+       //      }}}
+
+       //      {{{     setUpPage()
+
+       /**
+        * Sets up the page to manipulate packages for a member
+        *
+        * Checks if all the packages uploaded for a member (pending & non-pending)
+        * exceed or match the maximum # of packages allowed for each member to
+        * upload to their account.
+        *
+        * For every package that is already uploaded, create an edit-package form that
+        * will allow the user to update the caption or delete the package.
+        *
+        * @param Config_Container $c Application configuration
+        *
+        * @return void
+        * @access public
+        */
+       public function setUpPage(Config_Container $c)
+       {
+               $this->page = new StdClass;
+
+               //      Find out if we can still add packages to the record.
+               //      If we can, then add the upload form to the page for the member to see.
+               if ($this->canAddPackages()) {
+                       $addForm = new AddPackage(
+                               $this->dbh,
+                'new_member_package',
+                               'post',
+                               '',
+                               '',
+                               null,
+                               true
+                       );
+
+            $addForm->configureForm($c);
+                       $this->page->uploadForm = $addForm->toHtml($this->tEngine);
+               }
+
+               //      Find out if we have any packages already uploaded.
+               //      If we do, then add the edit package form to the page for each package
+               //      so the member can edit/delete their packages.
+               if ($packages = $this->getUploadedPackages()) {
+                       $this->page->editForm = array();
+                       while (list($i, $j) = each($packages)) {
+                               $editForm = new EditPackage(
+                                       $this->dbh,
+                    "edit_member_package_$j",
+                    'post',
+                    '',
+                    '',
+                    array('id' => $j),
+                    true
+                               );
+
+                $editForm->configureForm();
+                               $this->page->editForm[] = $editForm->toHtml($this->tEngine);
+                       }
+               }
+       }
+
+       //      }}}
+}
+
+/**
+ * Form to handle creating a new package in the members only area
+ *
+ * Handles inserting new package into db as a pending package and creating a
+ * tuple in the member_updates table which will allow the admin to
+ * approve/deny the new package request.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      <>
+ */
+class AddPackage extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_packages';
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'addPackage.tpl';
+
+    /**
+     * The name of the template used to email the owner for any updates
+     *
+     * When a member makes an update to thier record, this is the template
+     * we will use to send out the email notification to the site owner.
+     *
+     * @var string
+     * @access protected
+     */
+    protected $emailTemplate = 'emailOwner.tpl';
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+    protected $successMsg
+        = '<div id="form-success-top">
+            You successfully uploaded your package.
+           </div>';
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $mimeTypes = array(
+        'image/jpe',
+        'image/jpeg',
+        'image/jpg',
+        'image/jfif',
+        'image/pjpeg',
+        'image/pjp',
+        'image/gif',
+        'image/png',
+    );
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+        * @param PDO    $pdo         PHP Data Object to use for DB calls
+        * @param string $formName    Form's name.
+        * @param string $method      (optional) Form's method defaults to 'POST'
+        * @param string $action      (optional) Form's action.
+        * @param string $target      (optional) Form's target defaults to '_self'
+        * @param mixed  $attributes  (optional) Extra attributes for <form> tag.
+        * @param bool   $trackSubmit (optional) Whether to track if the form was
+        *                                                                               submitted by adding a special hidden
+        *                                                                               field.
+        *
+        * @access public
+        * @see    Toolkit_Members_Admin_EditPackages
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+    //  {{{ configureForm()
+
+    /**
+     * Quick form configuration
+     *
+     * @param Config_Container $c Config container
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(Config_Container $c)
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+        $this->configureConstants($c);
+    }
+
+    //  }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * @access public
+        * @see    Toolkit_FormBuilder::setupElements()
+        * @return void
+        */
+       public function configureElements()
+       {
+               $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+                       'type'    => 'hidden',
+                       'req'     => false,
+                       'name'    => 'pending',
+               );
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'title',
+            'display' => 'Package Title',
+               );
+               $e[] = array(
+                       'type'        => 'textarea',
+                       'req'         => false,
+                       'name'        => 'description',
+            'display'     => 'Package Description',
+            'opts'        => array('id' => 'descrAdd', 'class' => 'ckeditor'),
+                       'noCharLimit' => true
+               );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'sdate',
+            'display' => 'Start Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'edate',
+            'display' => 'End Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'checkbox',
+            'req'     => false,
+            'name'    => 'remove_img_rmv',
+            'display' => 'Remove Image',
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'curr_image',
+            'display' => 'Current Image',
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'curr_image_rmv',
+        );
+               $e[] = array(
+                       'type'    => 'file',
+                       'req'     => false,
+                       'name'    => 'image',
+            'display' => 'Upload a Package Photo / Image',
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'add_rmv',
+                       'display' => 'Upload new package',
+                       'opts'    => array('class' => 'submit')
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+    /**
+     * Configure rules for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+               $r = array();
+
+        $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));');
+               $r[] = array(
+                       'element'    => 'sdate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'edate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'image',
+                       'message'    => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                       'type'       => 'mimetype',
+                       'format'     => $this->mimeTypes,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{ configureConstants()
+
+    /**
+     * Configure constants for form
+     *
+        * @param Config_Container $conf Application configuration
+        *
+     * @return void
+     * @access public
+     */
+       public function configureConstants(Config_Container $conf)
+       {
+               $pending = $conf->getItem('section', 'conf')
+                       ->getItem('directive', 'strictPending')
+                       ->getContent();
+
+               $c = array(
+                       'pending' => $pending
+        );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Configure filters for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+               $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+
+    //  {{{ deleteImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server  $is  Parameter description (if any) ...
+     * @param string                $img Parameter description (if any) ...
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+    protected function deleteImage(Toolkit_Image_Server $is, $img)
+    {
+        return $is->imageDelete($img);
+    }
+
+    //  }}}
+
+    //  {{{ emailOwner()
+
+    /**
+     * Emails the owner and anyone else who wants to be advised of updates
+     *
+     * A false value in the primaryAdvisee will cause no email to be sent.
+     * all secondary advisees listed in the constructor are carbon copied
+     * in the email.
+     *
+     * Emails are sent out in both HTML and TXT forms.
+     *
+     * @return boolean result of email
+     * @access protected
+     */
+    protected function emailOwner()
+    {
+        if (MEMBER_RECORD_UPDATES_ADVISOR === false) {
+            return;
+        } else {
+            $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+            $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+            try {
+                $sql = "
+                    SELECT member_name
+                      FROM member
+                     WHERE member_id = :member_id";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(':member_id', $id, PDO::PARAM_INT);
+                $stmt->execute();
+                $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                $memberName = $row['member_name'];
+            } catch (PDOException $e) {
+                return Toolkit_Common::handleError($e);
+            }
+            $template = new HTML_Template_Flexy($this->flexyOptions);
+            $page = new stdClass();
+            $page->member = $memberName;
+            $page->url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : BASE_URL;
+            $page->email = OWNER_EMAIL;
+            $page->siteName = SITENAME;
+            $page->link = '<a target="_blank"  href="'.BASE_URL.'pending-member/'.$id.'/">link</a>';
+
+            $template->compile($this->emailTemplate);
+            //  Merge the compiled template with the $page object.
+            $htmlMsg = $template->bufferedOutputObject($page);
+
+            $msg = "
+                <h3>$memberName</h3>
+                <p>
+                    Has updated thier business record and is now in a pending
+                    state. To approve / reject thier changes you can either log
+                    into your {$page->siteName} admin area or follow this
+                    {$page->link}
+                </p>";
+            $crlf = "\n";
+            $mimeMail = new Mail_mime($crlf);
+            $from = preg_replace("/[^A-Za-z ]/", "", SITENAME) . ' <' . OWNER_EMAIL . '>';
+            $mimeMail->setFrom($from);
+            $mimeMail->setSubject('Member Record Update');
+            $mimeMail->setHTMLBody($htmlMsg);
+            $mimeMail->setTXTBody($msg);
+
+            $mail =& Mail::factory('mail');
+            $body = $mimeMail->get();
+            $headers = $mimeMail->headers($hdrs);
+
+            $res = $mail->send(MEMBER_RECORD_UPDATES_ADVISOR, $headers, $body);
+            if (PEAR::isError($res)) {
+                return Toolkit_Common::handleError($res);
+            } else {
+                return $res;
+            }
+        }
+    }
+
+    //  }}}
+       //      {{{ insertData()
+
+    /**
+     * Create a new package in the db
+     *
+     * @param array &$values Form submitted values
+        *
+     * @return object    db result of adding package
+     * @access protected
+     */
+       protected function insertData(&$values)
+       {
+               try {
+                       $this->dbh->beginTransaction();
+            $sql = Toolkit_Common::createSQLInsert(
+                $this->tableName,
+                array_keys($values)
+            );
+
+            $res = Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+
+                       if ($values['pending']) {
+                               $this->_createPendingData($values);
+                       }
+
+                       $this->dbh->commit();
+                       return $res;
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _createPendingData()
+
+    /**
+     * Description of _createPendingData()
+     *
+     * @param array $values Value array
+     *
+     * @return void|mixed
+     * @access private
+     */
+       private function _createPendingData($values)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM member_packages
+                 WHERE member_id = :member_id
+                 ORDER BY id DESC LIMIT 1";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $values['member_id'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+
+                       $sql = "
+                               INSERT INTO member_updates
+                                       (field, update, db_table, data_type, label,
+                                        foreign_key, member_id, field_type)
+                               VALUES (:field, :update, :db_table, :data_type, :label,
+                                               :foreign_key, :member_id, :field_type)";
+
+                       $dataToInsert = array();
+                       if (!empty($values['title'])) {
+                           $dataToInsert[] = array(
+                                'field' => 'title',
+                                'update' => $values['title'],
+                                'label' => 'Title'
+                           );
+                       }
+
+                       if (!empty($values['description'])) {
+                           $dataToInsert[] = array(
+                                               'field' => 'description',
+                                               'update' => $values['description'],
+                                               'label' => 'Description'
+                           );
+                       }
+                       /*if (!empty($values['image'])) {
+                           $dataToInsert[] = array(
+                                               'field' => 'image',
+                                               'update' => $values['image'],
+                                               'label' => 'Image'
+                           );
+                       }*/
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindValue(':db_table', 'member_packages', PDO::PARAM_STR);
+                       $stmt->bindValue(':data_type', 'text', PDO::PARAM_STR);
+                       $stmt->bindValue(':field_type', 'text', PDO::PARAM_STR);
+                       $stmt->bindParam(':foreign_key', $row['id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':member_id', $values['member_id'], PDO::PARAM_INT);
+
+                       foreach ($dataToInsert as $i) {
+                               $stmt->bindParam(':field', $i['field'], PDO::PARAM_STR);
+                               $stmt->bindParam(':update', $i['update'], PDO::PARAM_STR);
+                               $stmt->bindParam(':label', $i['label'], PDO::PARAM_STR);
+                               $stmt->execute();
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ processData()
+
+       /**
+        * Handles setting up the from processing and which function to get it done
+        *
+        * @param array $values Submitted values from the form.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function processData($values)
+       {
+               $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-$id", 'Profile');
+
+        $e =& $this->getElement('curr_image_rmv');
+
+               $packages = new Toolkit_Members_Packages(null, $id);
+        $packages->setDbh($this->dbh);
+               $packages->createMemberList();
+               $values['pos']       = $packages->getListSize() + 1;
+        $values['image'] = $e->getValue('curr_image_rmv');
+               $values['member_id'] = $GLOBALS['memberAuth']->getAuthData('member_id');
+        $values['sdate'] = implode('-', $values['sdate']);
+        $values['edate'] = implode('-', $values['edate']);
+               unset($values['MAX_FILE_SIZE'],
+                         $values['curr_image_rmv'],
+                         $values['remove_img_rmv'],
+              $values['add_rmv']);
+
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               $this->insertData($values);
+               $this->emailOwner();
+
+               $listPage = BASE_URL .
+            "members-only-area/?rt=EditProfile&tab=packages";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ setupRenderers()
+
+    /**
+     * Set up the rendering engine we are going to use to display this form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+        $fo = Toolkit_Members::getFlexyOptions();
+
+               $this->template = new HTML_Template_Flexy($fo);
+
+               $renderer = new HTML_QuickForm_Renderer_ObjectFlexy($this->template);
+
+               $this->accept($renderer);
+               $this->view              = new StdClass;
+        $this->view->showCurrImg = $this->showCurrImg;
+               $this->view->form        = $renderer->toObject();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+    //  {{{ validNewImg()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $newImg Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+    function validNewImg(array $newImg)
+    {
+        return (is_numeric($newImg['size']) &&
+                $newImg['size'] > 0 &&
+                in_array($newImg['type'], $this->mimeTypes));
+    }
+
+    //  }}}
+    //  {{{ removeOldImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is     Parameter description (if any) ...
+     * @param string               $oldImg Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    function removeOldImage(Toolkit_Image_Server $is, $oldImg)
+    {
+        $this->deleteImage($is, $oldImg);
+        if ($this->elementExists('curr_image_rmv')) {
+            $e =& $this->getElement('curr_image_rmv');
+            $e->setValue(null);
+            $this->_submitValues['curr_image_rmv'] = null;
+        }
+    }
+
+    //  }}}
+    //  {{{ syncCurrImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+    protected function syncCurrImage()
+    {
+        $is = new Toolkit_Image_Server();
+
+        $delImg = $this->getSubmitValue('remove_img_rmv');
+        $oldImg = $this->getSubmitValue('curr_image_rmv');
+        $newImg = $this->getSubmitValue('image');
+
+        if ($delImg && $oldImg) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        } elseif ($oldImg && $this->validNewImg($newImg)) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        }
+
+        if ($this->validNewImg($newImg)) {
+            $image = $this->uploadImage($is, 'image');
+        } else {
+            $image = $oldImg;
+        }
+
+        if ($image) {
+            $this->updatePhotoElements($is, $image);
+            $this->showCurrImg = true;
+        }
+    }
+
+    //  }}}
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml()
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+
+        //  If they have submitted the form and uploaded a proper image
+        //  but some other element had an error, then we need to show
+        //  their uploaded image in the form
+        if ($this->isSubmitted()) {
+            $this->syncCurrImage();
+        }
+
+               $this->setupRenderers();
+
+               if ($this->validated) {
+                       $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+               }
+
+               return $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+    //  {{{ updatePhotoElements()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is    Parameter description (if any) ...
+     * @param string               $image Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    public function updatePhotoElements(Toolkit_Image_Server $is, $image)
+    {
+        //  Get the dimensions of the image
+        $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image);
+        if (PEAR::isError($dimensions)) {
+            Toolkit_Common::handleError($dimensions);
+        }
+        list($w, $h) = $dimensions;
+        $s = MEMBER_PHOTOS . $image;
+
+        //  Set the image to show in the element
+        $e =& $this->getElement('curr_image');
+        $e->setText('<img width="'.$w.'" height="'.$h.'" src="'.$s.'">');
+
+        //  updated the hidden elements value to make sure it
+        //  holds the most up-to-date image name
+        $e =& $this->getElement('curr_image_rmv');
+        $e->setValue($image);
+    }
+
+    //  }}}
+    //  {{{ uploadImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server  $is    Parameter description (if any) ...
+     * @param string                $field Form field name of image
+     *
+     * @return string image name
+     * @access protected
+     */
+    protected function uploadImage(Toolkit_Image_Server $is, $field)
+    {
+        return $is->imageUpload($field);
+    }
+
+    //  }}}
+}
+
+/**
+ * Form to handle editing/deleting existing packages in members only area
+ *
+ * Handles updating caption requests for a member or to remove a
+ * package from thier profile
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      <>
+ * @see       Toolkit_FormBuilder
+ */
+class EditPackage extends Toolkit_FormBuilder
+{
+       //      {{{ properties
+
+       /**
+        * The table name in the database used to store the data
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member_packages';
+
+       /**
+        * The template used to render the form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'editPackage.tpl';
+
+    /**
+     * The name of the template used to email the owner for any updates
+     *
+     * When a member makes an update to thier record, this is the template
+     * we will use to send out the email notification to the site owner.
+     *
+     * @var string
+     * @access protected
+     */
+    protected $emailTemplate = 'emailOwner.tpl';
+
+    /**
+     * Id of package in db
+     * @var    integer
+     * @access protected
+     */
+       protected $packageId;
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+    protected $successMsg
+        = '<div id="form-success-top">
+            You successfully updated your package.
+          </div>';
+
+    /**
+     * Any rules we want to register for this form
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $mimeTypes = array(
+        'image/jpe',
+        'image/jpeg',
+        'image/jpg',
+        'image/jfif',
+        'image/pjpeg',
+        'image/pjp',
+        'image/gif',
+        'image/png',
+    );
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+        * @param PDO    $pdo         PHP Data Object to use for DB calls
+        * @param string $formName    Form's name.
+        * @param string $method      (optional) Form's method defaults to 'POST'
+        * @param string $action      (optional) Form's action.
+        * @param string $target      (optional) Form's target defaults to '_self'
+        * @param mixed  $attributes  (optional) Extra attributes for <form> tag.
+        * @param bool   $trackSubmit (optional) Whether to track if the form was
+        *                                                                               submitted by adding a special hidden
+        *                                                                               field.
+        *
+        * @access public
+        * @see    Toolkit_Members_Admin_EditPackages
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               $this->packageId = $attributes['id'];
+        $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+               $this->packages  = new Toolkit_Members_Packages(null, $id);
+        $this->packages->setDbh($pdo);
+               $this->packages->createMemberList();
+        $this->dbh = $pdo;
+       }
+
+       //      }}}
+
+    //  {{{ configureForm()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureDefaults();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{ configureDefaults()
+
+       /**
+        * Setup the element default values for form
+        *
+        * @access public
+        * @see    Toolkit_FormBuilder::setupDefaults()
+        * @return void
+        */
+       public function configureDefaults()
+       {
+        $sql = "
+            SELECT *
+              FROM {$this->tableName}
+             WHERE id = {$this->packageId}";
+
+        $defaults = $this->dbh->query($sql)->fetch(PDO::FETCH_ASSOC);
+        $defaults['curr_image_rmv'] = $defaults['image'];
+        $img = '<img src="%s">';
+        $defaults['curr_image'] = sprintf($img, MEMBER_PHOTOS . $defaults['image']);
+
+                       //      Get any updates for that photo that are still in
+                       //      a pending status.
+                       $sql = "
+                               SELECT *
+                                 FROM member_updates
+                                WHERE id in (
+                                       SELECT max(id)
+                                         FROM member_updates
+                                        WHERE foreign_key = :foreign_key
+                                          AND db_table = 'member_packages'
+                                        GROUP BY field)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute(array($this->packageId));
+               while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                       if ($row['field'] == 'title') {
+                               $defaults['title'] = $row['update'];
+                       } elseif ($row['field'] == 'description') {
+                               $defaults['description'] = $row['update'];
+                       }
+               }
+
+        $this->showCurrImg = $defaults['image'];
+               $this->setupDefaults($defaults);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+        * @access public
+        * @see    Toolkit_FormBuilder::setupElements()
+        * @return void
+        */
+       public function configureElements()
+       {
+               $e = array();
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'title',
+            'display' => 'Package Title',
+               );
+               $e[] = array(
+                       'type'        => 'textarea',
+                       'req'         => false,
+                       'name'        => 'description',
+            'display'     => 'Package Description',
+            'opts'        => array('id' => 'descr' . $this->packageId, 'class' => 'ckeditor'),
+                       'noCharLimit' => true
+               );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'sdate',
+            'display' => 'Start Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => true,
+            'name'    => 'edate',
+            'display' => 'End Date',
+            'opts'    => array(
+                'format'           => 'm / d / Y',
+                'minYear'          => date('Y'),
+                'maxYear'          => date('Y') + 10,
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy',
+                ),
+            )
+        );
+        $e[] = array(
+            'type'    => 'checkbox',
+            'req'     => false,
+            'name'    => 'remove_img_rmv',
+            'display' => 'Remove Image',
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'curr_image',
+            'display' => 'Current Image',
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'curr_image_rmv',
+        );
+               $e[] = array(
+                       'type'    => 'file',
+                       'req'     => false,
+                       'name'    => 'image',
+            'display' => 'Upload a Package Photo / Image',
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'add_rmv',
+                       'display' => 'Update Package',
+                       'opts'    => array('class' => 'submit')
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'remove_rmv',
+                       'display' => 'Remove Package',
+                       'opts'    => array('class' => 'submit')
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+    /**
+     * Configure rules for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+               $r = array();
+
+        $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));');
+               $r[] = array(
+                       'element'    => 'sdate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'edate',
+                       'message'    => 'ERROR: Invalid Date!',
+                       'type'       => 'callback',
+                       'format'     => $checkDate,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+               $r[] = array(
+                       'element'    => 'image',
+                       'message'    => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                       'type'       => 'mimetype',
+                       'format'     => $this->mimeTypes,
+                       'validation' => $this->validationType,
+                       'reset'      => false,
+                       'force'      => false
+               );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{ configureConstants()
+
+    /**
+     * Configure constants for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+               $c = array(
+            'remove_img_rmv' => false
+        );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+    /**
+     * Configure filters for form
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+               $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+
+    //  {{{ deleteImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is  Parameter description (if any) ...
+     * @param string               $img Parameter description (if any) ...
+     *
+     * @return unknown Return description (if any) ...
+     * @access protected
+     */
+    protected function deleteImage(Toolkit_Image_Server $is, $img)
+    {
+        return $is->imageDelete($img);
+    }
+
+    //  }}}
+
+       //      {{{     _createPendingData()
+
+    /**
+     * Description for _createPendingData()
+     *
+     * @param array $values Value array
+     *
+     * @return void|mixed only on error
+     * @access private
+     */
+       private function _createPendingData($values)
+       {
+               try {
+                       $sql = "
+                               INSERT INTO member_updates
+                                       (field, update, db_table, data_type, label,
+                                        foreign_key, member_id, field_type)
+                               VALUES (:field, :update, :db_table, :data_type, :label,
+                                               :foreign_key, :member_id, :field_type)";
+
+                       $dataToInsert = array();
+            if ($values['title'] != $this->_defaultValues['title']) {
+                $dataToInsert[] = array(
+                     'field' => 'title',
+                     'update' => $values['title'],
+                     'label' => 'Title'
+                );
+            }
+
+            if ($values['description'] != $this->_defaultValues['description']) {
+                $dataToInsert[] = array(
+                        'field' => 'description',
+                        'update' => $values['description'],
+                        'label' => 'Description'
+                );
+            }
+            /*if ($values['image'] != $this->_defaultValues['image']) {
+                $dataToInsert[] = array(
+                        'field' => 'image',
+                        'update' => $values['image'],
+                        'label' => 'Image'
+                );
+            }*/
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindValue(':db_table', 'member_packages', PDO::PARAM_STR);
+                       $stmt->bindValue(':data_type', 'text', PDO::PARAM_STR);
+                       $stmt->bindValue(':field_type', 'text', PDO::PARAM_STR);
+                       $stmt->bindParam(':foreign_key', $values['id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':member_id', $values['member_id'], PDO::PARAM_INT);
+
+                       foreach ($dataToInsert as $i) {
+                               if (!empty($i['update'])) {
+                                       $stmt->bindParam(':field', $i['field'], PDO::PARAM_STR);
+                                       $stmt->bindParam(':update', $i['update'], PDO::PARAM_STR);
+                                       $stmt->bindParam(':label', $i['label'], PDO::PARAM_STR);
+                                       $stmt->execute();
+                               }
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+
+    //  {{{ emailOwner()
+
+    /**
+     * Emails the owner and anyone else who wants to be advised of updates
+     *
+     * A false value in the primaryAdvisee will cause no email to be sent.
+     * all secondary advisees listed in the constructor are carbon copied
+     * in the email.
+     *
+     * Emails are sent out in both HTML and TXT forms.
+     *
+     * @return boolean result of email
+     * @access protected
+     */
+    protected function emailOwner()
+    {
+        if (MEMBER_RECORD_UPDATES_ADVISOR === false) {
+            return;
+        } else {
+            $this->flexyOptions = Toolkit_Members::getFlexyOptions();
+            $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+            try {
+                $sql = "
+                    SELECT member_name
+                      FROM member
+                     WHERE member_id = :member_id";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(':member_id', $id, PDO::PARAM_INT);
+                $stmt->execute();
+                $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                $memberName = $row['member_name'];
+            } catch (PDOException $e) {
+                return Toolkit_Common::handleError($e);
+            }
+            $template = new HTML_Template_Flexy($this->flexyOptions);
+            $page = new stdClass();
+            $page->member = $memberName;
+            $page->url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : BASE_URL;
+            $page->email = OWNER_EMAIL;
+            $page->siteName = SITENAME;
+            $page->link = '<a target="_blank"  href="'.BASE_URL.'pending-member/'.$id.'/">link</a>';
+
+            $template->compile($this->emailTemplate);
+            //  Merge the compiled template with the $page object.
+            $htmlMsg = $template->bufferedOutputObject($page);
+
+            $msg = "
+                <h3>$memberName</h3>
+                <p>
+                    Has updated thier business record and is now in a pending
+                    state. To approve / reject thier changes you can either log
+                    into your {$page->siteName} admin area or follow this
+                    {$page->link}
+                </p>";
+            $crlf = "\n";
+            $mimeMail = new Mail_mime($crlf);
+            $from = preg_replace("/[^A-Za-z ]/", "", SITENAME) . ' <' . OWNER_EMAIL . '>';
+            $mimeMail->setFrom($from);
+            $mimeMail->setSubject('Member Record Update');
+            $mimeMail->setHTMLBody($htmlMsg);
+            $mimeMail->setTXTBody($msg);
+
+            $mail =& Mail::factory('mail');
+            $body = $mimeMail->get();
+            $headers = $mimeMail->headers($hdrs);
+
+            $res = $mail->send(MEMBER_RECORD_UPDATES_ADVISOR, $headers, $body);
+            if (PEAR::isError($res)) {
+                return Toolkit_Common::handleError($res);
+            } else {
+                return $res;
+            }
+        }
+    }
+
+    //  }}}
+       //      {{{ processData()
+
+       /**
+        * Handles setting up the from processing and which function to get it done
+        *
+        * @param array $values Submitted values from the form.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function processData($values)
+       {
+               $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+        $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+        $cache->remove("Member-$id", 'Profile');
+
+        $e =& $this->getElement('curr_image_rmv');
+
+        $values['image'] = $e->getValue('curr_image_rmv');
+        $values['sdate'] = implode('-', $values['sdate']);
+        $values['edate'] = implode('-', $values['edate']);
+               unset($values['MAX_FILE_SIZE'],
+                         $values['curr_image_rmv'],
+                         $values['remove_img_rmv'],
+              $values['add_rmv']);
+
+               $this->tableMetaData = Toolkit_Common::getTableMetaData(
+            $this->dbh,
+            $this->tableName
+        );
+               $this->updateData($values);
+               if (   $values['title'] != $this->_defaultValues['title']
+                       || $values['description'] != $this->_defaultValues['description']
+               ) {
+                       $this->emailOwner();
+               }
+
+               $listPage = BASE_URL .
+            "members-only-area/?rt=EditProfile&tab=packages";
+               header("Location: $listPage");
+       }
+
+       //      }}}
+
+       //      {{{ setupRenderers()
+
+    /**
+     * Set up the rendering engine we are going to use to display this form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+        $fo = Toolkit_Members::getFlexyOptions();
+
+               $this->template = new HTML_Template_Flexy($fo);
+
+               $renderer = new HTML_QuickForm_Renderer_ObjectFlexy($this->template);
+
+               $this->accept($renderer);
+               $this->view              = new StdClass;
+        $this->view->showCurrImg = $this->showCurrImg;
+               $this->view->form        = $renderer->toObject();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+
+    //  {{{ validNewImg()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param array $newImg Parameter description (if any) ...
+     *
+     * @return mixed  Return description (if any) ...
+     * @access public
+     */
+    function validNewImg(array $newImg)
+    {
+        return (is_numeric($newImg['size']) &&
+                $newImg['size'] > 0 &&
+                in_array($newImg['type'], $this->mimeTypes));
+    }
+
+    //  }}}
+    //  {{{ removeOldImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is     Parameter description (if any) ...
+     * @param string               $oldImg Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    function removeOldImage(Toolkit_Image_Server $is, $oldImg)
+    {
+        $this->deleteImage($is, $oldImg);
+        if ($this->elementExists('curr_image_rmv')) {
+            $e =& $this->getElement('curr_image_rmv');
+            $e->setValue(null);
+            $this->_submitValues['curr_image_rmv'] = null;
+        }
+    }
+
+    //  }}}
+    //  {{{ syncCurrImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return void
+     * @access protected
+     */
+    protected function syncCurrImage()
+    {
+        $is = new Toolkit_Image_Server();
+
+        $delImg = $this->getSubmitValue('remove_img_rmv');
+        $oldImg = $this->getSubmitValue('curr_image_rmv');
+        $newImg = $this->getSubmitValue('image');
+
+        if ($delImg && $oldImg) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        } elseif ($oldImg && $this->validNewImg($newImg)) {
+            $this->removeOldImage($is, $oldImg);
+            unset($oldImg);
+        }
+
+        if ($this->validNewImg($newImg)) {
+            $image = $this->uploadImage($is, 'image');
+        } else {
+            $image = $oldImg;
+        }
+
+        if ($image) {
+            $this->updatePhotoElements($is, $image);
+            $this->showCurrImg = true;
+        }
+    }
+
+    //  }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml()
+       {
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+
+        //  If they have submitted the form and uploaded a proper image
+        //  but some other element had an error, then we need to show
+        //  their uploaded image in the form
+        if ($this->isSubmitted()) {
+            $this->syncCurrImage();
+        }
+
+               $this->setupRenderers();
+
+               if ($this->validated) {
+                       $processed = $this->process(
+                array(&$this, 'processData'),
+                $this->mergeFiles
+            );
+               }
+
+               return $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+       //      {{{     removePackage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param integer $id Member ID
+     *
+     * @return object    Return description (if any) ...
+     * @access protected
+     */
+       protected function removePackage($id)
+       {
+               try {
+                       $this->dbh->beginTransaction();
+            //  need to delete the image associated w/ this package here.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE id           = :id
+                   AND member_id    = :mid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->bindparam(
+                               ':mid',
+                               $GLOBALS['memberAuth']->getAuthData('member_id'),
+                               PDO::PARAM_INT
+                       );
+
+                       $stmt->execute();
+
+                       $sql = "
+                               DELETE FROM member_updates
+                                WHERE db_table = '{$this->tableName}'
+                                  AND member_id = :mid
+                                  AND foreign_key = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->bindparam(
+                               ':mid',
+                               $GLOBALS['memberAuth']->getAuthData('member_id'),
+                               PDO::PARAM_INT
+                       );
+                       $stmt->execute();
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ updateData()
+
+    /**
+     * Update the package caption
+     *
+     * @param array $values Submitted form values
+        *
+     * @return boolean Result of updating the caption in the db
+     * @access public
+     */
+       protected function updateData($values)
+       {
+        try {
+            if (array_key_exists('remove_rmv', $values)) {
+                return $this->removePackage($this->packageId);
+            }
+                       $this->dbh->beginTransaction();
+
+            $pending = $values;
+            $pending['member_id'] = $GLOBALS['memberAuth']->getAuthData('member_id');
+            unset($pending['sdate'], $pending['edate']);
+            unset($values['title'], $values['description']);
+            $sql = Toolkit_Common::createSQLUpdate(
+                $this->tableName,
+                array_keys($values),
+                array('id = :id')
+            );
+
+            //$values['id'] = $this->packageId;
+            $pending['id'] = $values['id'] = $this->packageId;
+            $res = Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+
+                       $this->_createPendingData($pending);
+
+                       $this->dbh->commit();
+                       return $res;
+        } catch (PDOException $e) {
+                       $this->dbh->rollback();
+            return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+    //  {{{ updatePhotoElements()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server $is    Parameter description (if any) ...
+     * @param string               $image Parameter description (if any) ...
+     *
+     * @return void
+     * @access public
+     */
+    public function updatePhotoElements(Toolkit_Image_Server $is, $image)
+    {
+        //  Get the dimensions of the image
+        $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image);
+        if (PEAR::isError($dimensions)) {
+            Toolkit_Common::handleError($dimensions);
+        }
+        list($w, $h) = $dimensions;
+        $s = MEMBER_PHOTOS . $image;
+
+        //  Set the image to show in the element
+        $e =& $this->getElement('curr_image');
+        $e->setText('<img width="'.$w.'" height="'.$h.'" src="'.$s.'">');
+
+        //  updated the hidden elements value to make sure it
+        //  holds the most up-to-date image name
+        $e =& $this->getElement('curr_image_rmv');
+        $e->setValue($image);
+    }
+
+    //  }}}
+    //  {{{ uploadImage()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @param Toolkit_Image_Server  $is    Parameter description (if any) ...
+     * @param string                $field Parameter description (if any) ...
+     *
+     * @return string    Return description (if any) ...
+     * @access protected
+     */
+    protected function uploadImage(Toolkit_Image_Server $is, $field)
+    {
+        return $is->imageUpload($field);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/EditPhoto.php b/Toolkit/Members/EditPhoto.php
new file mode 100644 (file)
index 0000000..66bd934
--- /dev/null
@@ -0,0 +1,235 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles the photos tab in the member record
+ *
+ * Controls setting up the add photo form if applicable, and rendering
+ * each uploaded photo edit form to edit/delete the photo.
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: EditPhoto.php,v 1.5 2010/07/16 20:52:51 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit/Image/Server.php
+ */
+
+
+/**
+ * The image server processing class
+ */
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Form to handle editing/deleting existing photos in members only area
+ *
+ * Handles updating caption requests for a member or to remove a
+ * photo from thier profile
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_EditPhoto extends Toolkit_Members_Admin_EditPhoto
+{
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for elements in the form.
+        *
+        * @return void
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               $photo    = $this->photos->findNode($this->photoId);
+               $defaults = array(
+                       'caption' => $photo->getCaption(),
+                       'pos' => $photo->getPosition(),
+                       'pid' => $photo->getId(),
+               );
+
+               //      overwrite the photo caption w/ the pending
+               //      caption, ONLY if the pending caption exists.
+               $pc = $photo->getPendingCaption();
+               if (!empty($pc)) {
+                       $defaults['caption'] = $pc;
+                       $photo->setFauxPending(true);
+               }
+               $this->setupDefaults($defaults);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+     * @param Config_Container $c application configuration
+        *
+        * @return void
+        * @access public
+        */
+       public function configureElements(Config_Container $c)
+       {
+        $e = array();
+
+               $positions = range(1, $this->photos->getListSize(true));
+               $options   = array_combine($positions, $positions);
+
+        $config =& $c->getItem('section', 'photos');
+        $maxLength =& $config->getItem('directive', 'maxCaptionLength');
+               //      All Grouped Elements are created here.
+
+               //      All Elements are created here.  This includes group element definitions.
+               $cur = $this->photos->findNode($this->photoId);
+
+               $e[] = array(
+                       'type' => 'hidden',
+                       'req'  => false,
+                       'name' => 'pid'
+               );
+               $e[] = array(
+                       'type' => 'text',
+                       'req'  => false,
+                       'name' => 'caption',
+            'display' => 'Image Caption',
+                       'opts' => array(
+                               'class'     => 'text',
+                               'maxlength' => $maxLength->getContent(),
+                       ),
+            'noCharLimit' => true
+               );
+               $e[] = array(
+                       'type'    => 'select',
+                       'req'     => false,
+                       'name'    => 'pos',
+                       'display' => 'Position',
+                       'opts'    => $options,
+                       'att'     => array('id' => "pos{$cur->getPosition()}")
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'update',
+                       'display' => 'Update Photo',
+                       'opts'    => array('class' => 'submit')
+               );
+               $e[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'delete',
+                       'display' => 'Delete Photo',
+                       'opts'    => array('class' => 'photoDelete')
+               );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ createPendingCaption()
+
+       /**
+        * Updates the caption in the member_updates table for the photo
+        *
+        * @param array            &$values submitted values from the form.
+     * @param Config_Container $c       Member Configuration
+        *
+        * @return sql insert result
+        * @access protected
+        */
+       protected function createPendingCaption(&$values, Config_Container $c)
+       {
+        $config = $c->getItem('section', 'tables');
+        $pendingTable = $config->getItem('directive', 'pendingTable');
+
+               try {
+                       //      Insert the picture into the updates table for approval.
+                       $sql =  "
+                INSERT INTO {$pendingTable->getContent()}
+                                       (member_id, field, update, db_table,
+                                       data_type, label, foreign_key)
+                VALUES
+                                       (:member_id, :field, :update, :db_table,
+                                       :data_type, :label, :foreign_key)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(
+                ':member_id',
+                $GLOBALS['memberAuth']->getAuthData('member_id'),
+                PDO::PARAM_INT
+            );
+                       $stmt->bindValue(':field', 'caption', PDO::PARAM_STR);
+                       $stmt->bindParam(':update', $values['caption'], PDO::PARAM_BOOL);
+                       $stmt->bindValue(':db_table', 'member_photos', PDO::PARAM_STR);
+                       $stmt->bindValue(':data_type', 'text', PDO::PARAM_STR);
+                       $stmt->bindValue(':label', 'Caption', PDO::PARAM_STR);
+                       $stmt->bindParam(':foreign_key', $values['pid'], PDO::PARAM_STR);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+        //     }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+     * @param HTML_Template_Flexy  $tEngine Templating Engine
+     * @param Cache_Lite           $cache   Caching Engine
+     * @param Toolkit_Image_Server $is      Image Server
+     * @param Config_Container     $c       Member Configuration
+     *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(
+        HTML_Template_Flexy $tEngine,
+        Cache_Lite $cache,
+        Toolkit_Image_Server $is,
+        Config_Container $c
+    ) {
+               if ($this->validate()) {
+            $config = $c->getItem('section', 'conf');
+            $strictPending = $config->getItem('directive', 'strictPending');
+
+            $id = $GLOBALS['memberAuth']->getAuthData('member_id');
+            $res = $cache->remove("Member-$id", 'Profile');
+
+            if ($this->getSubmitValue('delete')) {
+                $this->photos->removeNode($is, $c, $this->getSubmitValue('pid'));
+            }
+
+            if ($strictPending->getContent() && !$this->getSubmitValue('delete')) {
+                $this->createPendingCaption($this->getSubmitValues(), $c);
+                header('Location:' . $this->getAttribute('action'));
+            } else {
+                $this->process(
+                    array(&$this, 'processData'),
+                    $this->mergeFiles
+                );
+            }
+               }
+
+               $this->setupRenderers($tEngine);
+
+               return $tEngine->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Events/CommonEditEvent.php b/Toolkit/Members/Events/CommonEditEvent.php
new file mode 100644 (file)
index 0000000..b55fc0f
--- /dev/null
@@ -0,0 +1,1730 @@
+<?php
+/**
+ * New Event Form
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Events
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: AddEventForm.php,v 1.20 2010/07/04 23:58:22 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+if (!defined('COMMON_APP_BASE')) {
+    define('COMMON_APP_BASE', '/var/www/server/CommonApps/');
+}
+require_once COMMON_APP_BASE . 'EventCalendar/V0/models/EventMapper.php';
+require_once BASE . 'Toolkit/Forms/Rules/Image.php';
+
+/**
+ * Toolkit_Members_Events_EditEvent
+ *
+ * @category  Toolkit
+ * @package   Members_Events
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Events_CommonEditEvent
+    extends Toolkit_FormBuilder
+    implements Toolkit_Form
+{
+       //      {{{     properties
+
+    /**
+     * Table in Database which holds the contact data
+        *
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'events.events';
+
+    /**
+     * Table meta data
+        *
+        * This is used when inserting/updating data for the records
+        * so the PDO's can use explicit data types for the parameters.
+        *
+     * @var    array
+     * @access public
+     */
+       public $tableMetaData;
+
+    /**
+        * Who to send the email to when the contact form is submitted
+        *
+        * If you leave this blank, its value will get set to the OWNER_EMAIL
+        * in the constructor.
+        *
+        * If you ***DO NOT*** want any emails to go out when the form is submitted
+        * then set the value to false. Do not set it to 0 for false, because the
+        * check uses a strict type check to determine if the value is actually
+        * false. This is what allows for the empty value as an option, which sets
+        * the value to OWNER_EMAIL and won't override the $email property if
+        * this class gets subclassed and the value for this property gets set in
+        * the properties of the subclass and not in the constructor after this
+        * constructor function is called.
+        *
+        * tongue twister...I know.
+        * <code>
+        * protected $email = false;
+        * </code>
+        *
+     * @var    unknown
+     * @access protected
+     */
+       protected $email;
+
+    /**
+     * From header in the owner email
+        *
+        * This just sets the From header in the owner email
+        * SITENAME <from@email.com>
+        *
+        * It gets set to the constant SITENAME in the constructor if you leave
+        * empty here, but you can set it to something different here to override
+        * that if you desire.
+        *
+     * @var    unknown
+     * @access protected
+     */
+       protected $siteName;
+
+    /**
+        * Email subject and <h1> header in email
+        *
+        * It gets set in the constructor if you leave empty here, but you
+        * can set it to something different here to override that if you desire.
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $subject = 'New Event Submission';
+
+    /**
+     * Message to display if the form is successfully submitted
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $successMsg = '
+    <style type="text/css">
+        #category {display:none};
+        .listings {display:none};
+    </style>
+               <div id="form-sucess-top">
+            Your event has been successfully added to the events calendar,
+            however will not be visible until it has been approved by
+            the Web site administrator. Thank You.
+               </div>';
+
+    /**
+     * Extra rules for processesing
+        *
+        * This registers the Zip validation rules (and any others listed) for
+        * QuickForm.
+        *
+        * Zip validation checks both US and Canadian Zip codes
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array(
+        'phone',
+        array(
+            'checkEmail',
+            'callback',
+            'email',
+            'Validate'
+        ),
+        array(
+            'checkURI',
+            'callback',
+            'uri',
+            'Validate'
+        )
+    );
+
+    /**
+     * Options for flexy templating engine
+        *
+        * Pulls the preset options from the setup.phtml file
+        * overwrites the templateDir and compileDir to match this classes needs
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $flexyOptions;
+
+    protected $eventMapper;
+
+       //      }}}
+       //      {{{     __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false,
+        EventMapper $eventMapper
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+        $this->eventMapper = $eventMapper;
+
+               if ($this->email !== false && empty($this->email)) {
+                       //      Set to false to turn off email function.
+                       $this->email
+                = (MEMBERS_EVENTS_NOTIFICATION_EMAIL)
+                ? MEMBERS_EVENTS_NOTIFICATION_EMAIL
+                : MEMBER_RECORD_UPDATES_ADVISOR;
+               }
+               if (empty($this->siteName)) {
+                       $this->siteName = SITENAME;
+               }
+               if (empty($this->subject)) {
+                       $this->subject = 'Contact Request from website ' . SITENAME;
+               }
+
+               $this->flexyOptions                = $GLOBALS['flexyOptions'];
+               $this->flexyOptions['templateDir'] = dirname(__FILE__) . "/templates/";
+               $this->flexyOptions['compileDir']
+                   = dirname(__FILE__) . "/templates/compiled/";
+
+               $var = basename(__FILE__, '.php');
+
+               $callbackUrl = ($_SERVER['HTTPS'] == 'on') ?
+                                                         BASE_SECURE_URL : BASE_URL;
+
+               $this->captchaOptions = array(
+                       'width' => 100,
+                       'height' => 50,
+                       'callback' => "{$callbackUrl}Toolkit/qfcaptcha.php?var=$var",
+                       'sessionVar' => $var,
+                       'imageOptions' => array(
+                               'font_size' => 16,
+                               'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/',
+                               'font_file' => 'times.ttf',
+                               'background_color' => '#cccccc',
+                               'obfuscation' => false,
+                               'angle' => true,
+                       ),
+               );
+       }
+
+       //      }}}
+
+    //  {{{ checkDate()
+
+    /**
+     * Validate date input
+     *
+     * allows for empty dates to be valid
+     *
+     * @param array $date date group from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+    public function checkDate($date)
+    {
+        if (!$date) {
+            return true;
+        } else {
+            return Validate::date($date, array('format' => '%m/%d/%Y'));
+        }
+    }
+
+    //  }}}
+    //  {{{ checkDateRange()
+
+    /**
+     * Validate date input
+     *
+     * allows for empty end date to be valid
+     *
+     * @param array $d date group from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+    public function checkDateRange(array $d)
+    {
+        if (!$this->hasEndDate($d[1])) {
+            //  no end date is a valid date range
+            return true;
+        }
+
+        $pattern = '/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/';
+        if (preg_match($pattern, $d[0], $m)) {
+            $t1 = mktime(0, 0, 0, (int) $m[1], (int) $m[2], (int) $m[3]);
+            $bdate = new Date($t1);
+        }
+        if (preg_match($pattern, $d[1], $m)) {
+            $t2    = mktime(0, 0, 0, (int) $m[1], (int) $m[2], (int) $m[3]);
+            $edate = new Date($t2);
+        }
+        if ($bdate && $edate) {
+            //  0 if the dates are equal - valid
+            // -1 if $bdate is before $edate - valid
+            //  1 if $bdate is after $edate - invalid
+            $res = Date::compare($bdate, $edate);
+            return ($res !== 1);
+        }
+        return true;
+    }
+
+    //  }}}
+       //      {{{     configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements()
+       {
+        $e = array();
+
+               //      All Elements are created here.  This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventInfoHeader_rmv',
+            'display' => 'Event Information'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'header',
+            'display' => 'Event Name'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'id'
+        );
+        $e[] = array(
+               'type' => 'hidden',
+               'req'  => false,
+               'name' => 'member',
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'visable',
+            'val'  => 0
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'starting',
+            'display' => 'Start Date',
+            'opts'    => array('id' => 'sdate')
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'ending',
+            'display' => 'End Date',
+            'opts'    => array('id' => 'edate')
+        );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'allday',
+                       'display' => 'All Day Event?',
+                       'opts'    => 'Yes',
+                       'val'     => array(0, 1)
+               );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => false,
+            'name'    => 'btime',
+            'display' => 'Start Time',
+            'opts'    => array(
+                'format'           => 'h : i A',
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'h' => 'hh',
+                    'i' => 'mm',
+                    'A' => 'am/pm'
+                ),
+                'optionIncrement' => array(
+                    'i' => 15,
+                ),
+            ),
+            'error' => 'ERROR: You must select a start time!',
+        );
+        $e[] = array(
+            'type'    => 'date',
+            'req'     => false,
+            'name'    => 'etime',
+            'display' => 'End Time',
+            'opts'    => array(
+                'format'           => 'h : i A',
+                'addEmptyOption'   => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText'  => array(
+                    'h' => 'hh',
+                    'i' => 'mm',
+                    'A' => 'am/pm'
+                ),
+                'optionIncrement' => array(
+                    'i' => 15,
+                ),
+            ),
+        );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'recurr',
+                       'display' => 'Recurring Event',
+                       'opts'    => 'Is this a recurring event?',
+                       'val'     => array(0, 1)
+               );
+               $daysOm = array(''=>'');
+               for ($i = 1; $i <= 31; ++$i) {
+                   $daysOm[$i] = $i;
+               }
+               $e[] = array(
+                   'type'    => 'select',
+                       'name'    => 'dayom',
+                   'display' => 'Every Month on',
+                   'opts'    => $daysOm
+               );
+               $e[] = array(
+            'type'    => 'select',
+            'req'     => false,
+            'name'    => 'weekom',
+            'display' => 'Recurs',
+            'opts'    => array(
+                   ''  => 'Every Week of Month',
+                   '9' => 'Every Other Week',
+                   '1' => 'Every First Week of Month',
+                   '2' => 'Every Second Week of Month',
+                   '3' => 'Every Third Week of Month',
+                   '4' => 'Every Fourth Week of Month',
+               ),
+        );
+               $weekdays = array(
+                   1 => 'Sunday',
+                       'Monday',
+                   'Tuesday',
+                   'Wednesday',
+                       'Thursday',
+                   'Friday',
+                   'Saturday'
+               );
+               $ri = 1;
+               for ($i = 1; $i <= 7; ++$i) {
+               $daysOw[] = array(
+                       'type' => 'advcheckbox',
+               'req'  => false,
+               'name' => $i,
+               'opts' => $weekdays[$i],
+                   'val'  => array('', $ri)
+               );
+               $ri = $ri << 1;
+               }
+               //echo '<pre>'.print_r($daysOw, true).'</pre>';
+               $e[] = array(
+            'type'       => 'group',
+            'req'        => false,
+            'name'       => 'daysow',
+            'group'         => $daysOw,
+            'label'      => 'Days Of Week',
+            'seperator'  => ' ',
+            'appendName' => true
+        );
+        $e[] = array(
+            'type'    => 'select',
+            'req'     => true,
+            'name'    => 'category',
+            'display' => 'Category',
+            'opts'    => $this->getTopicFields(),
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'website',
+            'display' => 'Website'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'facebook',
+            'display' => 'Facebook',
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'twitter',
+            'display' => 'Twitter',
+        );
+
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'cost',
+            'display' => 'Cost',
+        );
+        $e[] = array(
+            'type'    => 'textarea',
+            'req'     => false,
+            'name'    => 'intro',
+            'display' => 'Intro <span id="charleft">350</span> characters left',
+            'opts'    => array('id' => 'intro')
+        );
+        $e[] = array(
+            'type'    => 'textarea',
+            'req'     => false,
+            'name'    => 'description',
+            'display' => 'Description',
+            'opts'    => array('id' => 'descr')
+        );
+               $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'current_img_rmv',
+            'display' => 'Current Image'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'img'
+        );
+               $e[] = array(
+            'type'    => 'file',
+            'req'     => false,
+            'name'    => 'img_file_rmv',
+            'display' => 'Event Image'
+        );
+               $e[] = array(
+            'type' => 'static',
+            'req'  => false,
+            'name' => 'img_instructions_rmv',
+            'opts' => '.jpg or .gif images only'
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventLocationInfoHeader_rmv',
+            'display' => 'Event Location Information
+                <div id="map-dialog">
+                    <div id="map_canvas" style="width:500px; height:400px"></div>
+                </div>
+                <a id="map-it" href="#">Map It</a>'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'lat',
+            'opts' => array('id' => 'lat')
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'lon',
+            'opts' => array('id' => 'lon')
+        );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'use_memberloc',
+                       'display' => 'User Member Location?',
+                       'opts'    => 'Yes',
+                       'val'     => array(0, 1)
+               );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'place',
+            'display' => 'Place'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'address',
+            'display' => 'Address',
+            'opts'    => array('id' => 'address')
+        );
+        $e[]         = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'city',
+            'display' => 'City',
+            'opts'    => array('id' => 'city')
+        );
+        $e[]         = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'state',
+            'display' => 'State',
+            'opts'    => array('id' => 'state')
+        );
+        $e[]         = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'zip',
+            'display' => 'ZIP',
+            'opts'    => array('id' => 'zip')
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventContactHeader_rmv',
+            'display' => 'Event Contact Information'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'contact_name',
+            'display' => 'Contact Person'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'contact_email',
+            'display' => 'Contact Email'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'contact_phone',
+            'display' => 'Contact Phone'
+        );
+               $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'current_file_rmv',
+            'display' => 'Current File'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'file'
+        );
+               $e[] = array(
+            'type'    => 'file',
+            'req'     => false,
+            'name'    => 'file_rmv',
+            'display' => 'Event File'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'filename',
+            'display' => 'File Name'
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventInfoHeader_rmv',
+            'display' => 'Event Admin Information'
+        );
+        $e[]      = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_contact',
+            'display' => 'Contact Name Submitting Event'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_org',
+            'display' => 'Organization Name Submitting Event'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_phone',
+            'display' => 'Phone'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_email',
+            'display' => 'Email Address'
+        );
+               $e[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit_rmv',
+            'display' => 'Submit'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+        * Applies a data filter for the given fields when the form is submitted
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+        $f[] = array(
+            'element' => 'url',
+                       'filter' => array('Toolkit_Common', 'filterURI')
+        );
+
+        $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureDefaults();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{     configureRules()
+
+    /**
+     * Form rule definitions
+     *
+        * Adds validation rules for the given fields
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+               //      Form Rules
+        $r = array();
+
+               $mimeTypes = array(
+                       'image/jpe',
+                       'image/jpeg',
+                       'image/jpg',
+                       'image/jfif',
+                       'image/pjpeg',
+                       'image/pjp',
+                       'image/gif',
+                       'image/png',
+               );
+
+               $r[] = array(
+            'element' => 'topicid',
+            'message' => 'ERROR: Invalid Topic!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Invalid Email Format!',
+            'type' => 'checkEmail',
+            'format' => array('use_rfc822' => true),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => array('bdate', 'edate'),
+            'message' => 'ERROR: Starting Date must be before Ending Date',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDateRange'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'bdate',
+            'message' => 'ERROR: Invalid date!',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDate'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'edate',
+            'message' => 'ERROR: Invalid date!',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDate'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'url',
+            'message' => 'ERROR: Invalid URL format',
+            'type' => 'checkURI',
+            'format' => array(
+                'allowed_schemes' => array('http', 'https'),
+                'strict' => true
+            ),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'phone',
+            'message' => 'ERROR: Invalid Phone Format (xxx) xxx - xxxx!',
+            'type' => 'phone',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+        if ($this->useCaptcha) {
+            $r[] = array(
+                'element' => 'captcha_rmv',
+                'message' => 'ERROR: What you entered didn\'t match!',
+                'type' => 'CAPTCHA',
+                'format' => $this->captchaQuestion,
+                'validation' => $this->validationType,
+                'reset' => true,
+                'force' => false
+            );
+        }
+               if (is_uploaded_file($_FILES['img_file_rmv']['tmp_name'])) {
+                       $r[] = array(
+                'element' => 'img_file_rmv',
+                'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                'type' => 'mimetype',
+                'format' => $mimeTypes,
+                'validation' => $this->validationType,
+                'reset' => false,
+                'force' => false
+            );
+               }
+               $r[] = array(
+                       'element' => 'img_file_rmv',
+                       'message' => 'ERROR: Error uploading image!',
+                       'type' => 'Image',
+                       'format' => array(
+                               'form' => $this,
+                               'fieldName' => 'img_file_rmv',
+                               'imageField' => 'img',
+                               'is' => new Toolkit_FileServer_ImageAdapter(),
+                               'deleteExistingImage' => false,
+                               'injectImage' => array('tgtElement' => 'current_img_rmv')
+                       ),
+                       'validation' => 'server',
+                       'reset' => false,
+                       'force' => false
+               );
+        /*
+               $r[] = array(
+                       'element' => 'file_rmv',
+                       'message' => 'ERROR: Error uploading file!',
+                       'type' => 'Image',
+                       'format' => array(
+                               'form' => $this,
+                               'fieldName' => 'file_rmv',
+                               'imageField' => 'file',
+                               'is' => new Toolkit_FileServer_FileAdapter(),
+                               'deleteExistingImage' => false,
+                               'injectImage' => array('tgtElement' => 'current_file_rmv')
+                       ),
+                       'validation' => 'server',
+                       'reset' => false,
+                       'force' => false
+               );
+         */
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{     configureDefaults()
+
+    /**
+     * Form defaults
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+        $eventId = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT);
+               if ($eventId) {
+            $event = $this->eventMapper->fetchEvent($eventId);
+            $eventFile = $event->getFile();
+            if ($eventFile) {
+                $file     = $eventFile->getFilename();
+                $filename = $eventFile->getUrltext();
+            } else {
+                $file = $filename = '';
+            }
+            $d = array(
+                'id'          => $event->getId(),
+                'starting'    => $event->getStarting(),
+                'ending'      => $event->getEnding(),
+                'description' => $event->getDescription(),
+                'category'    => $event->getCategory()->getId(),
+                'btime'       => $event->getStarthour(),
+                'etime'       => $event->getEndhour(),
+                'header'      => $event->getHeader(),
+                'website'     => $event->getWebsite(),
+                'facebook'    => $event->getFacebook(),
+                'twitter'     => $event->getTwitter(),
+                'allday'      => $event->getAllday(),
+                'hide_address' => $event->getHideAddress(),
+                'recurr'       => $event->getRecurr(),
+                'daysow'       => $event->getDaysow(),
+                'dayom'        => $event->getDayom(),
+                'weekom'       => $event->getWeekom(),
+                'place'        => $event->getPlace(),
+                'address'      => $event->getAddress(),
+                'city'         => $event->getCity(),
+                'state'        => $event->getState(),
+                'zip'          => $event->getZip(),
+                'lat'          => $event->getLat(),
+                'lon'          => $event->getLon(),
+                'cost'         => $event->getCost(),
+                'contact_name' => $event->getContactName(),
+                'contact_email' => $event->getContactEmail(),
+                'contact_phone' => $event->getContactPhone(),
+                'intro'         => $event->getIntro(),
+                'use_memberloc' => $event->getUseMemberLocation(),
+                'img'           => $event->getImage(),
+                'admin_contact' => $event->getAdminContact(),
+                'admin_email'   => $event->getAdminEmail(),
+                'admin_phone'   => $event->getAdminPhone(),
+                'admin_org'     => $event->getAdminOrg(),
+                'file'          => $file,
+                'filename'      => $filename
+            );
+            $d['active'] = 0;
+            $d['current_file_rmv']
+                = ($d['file'])
+                ? '<a href="' . UPLOADED_FILES . 'original/' . $d['file'] . '">
+                '.$d['file'].'</a>
+                <input type="hidden" name="del_file_rmv" value="0">
+                <input type="checkbox" name="del_file_rmv" value="1">Delete File?'
+                : 'File not yet uploaded';
+            $d['current_img_rmv']
+                = ($d['img'])
+                ? '<img src="' . THUMB . $d['img'] . '">
+                <input type="hidden" name="del_img_rmv" value="0">
+                <input type="checkbox" name="del_img_rmv" value="1">Delete Image?'
+                : 'Image not yet uploaded';
+            $ri = 1;
+            for ($r = 1; $r <= 7; ++$r) {
+                if ($d['daysow']&$ri) {
+                    $daysow[$r] = $ri;
+                }
+                $ri = $ri << 1;
+            }
+            $d['daysow'] = $daysow;
+        } else {
+            $d['current_img_rmv'] = 'Image not yet uploaded';
+            $d['current_file_rmv'] = 'File not yet uploaded';
+        }
+        $d['member'] = $GLOBALS['memberAuth']->getAuthData('member_id');
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+
+       //      {{{     emailOwner()
+
+    /**
+     * Emails the owner the submitted data from the submitted form
+     *
+        * Uses a flexy template to render a nice looking html email.
+        * Fills in the supplied data from the form and doesn't add the
+        * empty fields the user didn't fill in.
+        *
+     * @param string $mailFactory What type of mail factory should we use
+     *
+     * @return boolean result of the mailing
+     * @access protected
+     */
+       protected function emailOwner($mailFactory = 'mail')
+       {
+               if (!$this->email) {
+                       return;
+               }
+
+               $topics = $this->getTopicFields();
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->email_from  = OWNER_EMAIL;
+               $page->subject     = $this->subject;
+               $page->client_info = $this->clientInfo;
+               $page->fname       = $this->_getMemberName();
+               $page->formData    = $this->formData;
+        // setup a link to admin section
+        $page->lname
+            = '<a href="'.BASE_URL.'admin/Events/list_events.phtml?pending=t">Events Admin</a>';
+        unset(
+            $page->formData['img'],
+            $page->formData['member_id'],
+            $page->formData['MAX_FILE_SIZE'],
+            $page->formData['comments'],
+            $page->formData['visable'],
+            $page->formData['id']
+        );
+        if ($page->formData['btime']['element']) {
+            $btime = explode(" / ", $page->formData['btime']['element']);
+            $page->formData['btime']['element']
+                = $btime[0] . ':' . (($btime[1] == '0')?'00':$btime[1]) . ' ' . $btime[2];
+        }
+        if ($page->formData['etime']['element']) {
+            $etime = explode(" / ", $page->formData['etime']['element']);
+            $page->formData['etime']['element']
+                = $etime[0] . ':' . (($etime[1] == '0')?'00':$etime[1]) . ' ' . $etime[2];
+        }
+               if ($page->formData['topicid']['element']) {
+                       //      Clean up the mail_ok flag so its human readable
+                       $page->formData['topicid']['element']
+                = $topics[$page->formData['topicid']['element']];
+               }
+
+               $template->compile('emailOwner.tpl');
+               $htmlMsg = $template->bufferedOutputObject($page);
+
+               $msg  = "{$page->subject}\n\n";
+               $msg .= "From {$page->fname} {$page->lname}\n\n";
+               $msg .= "Information\n\n";
+               foreach ($page->formData as $i) {
+                       $msg .= "{$i['label']}: {$i['element']}\n";
+               }
+
+        $mimeMail = new Mail_mime("\n");
+               $mimeMail->setFrom("Online Form <{$page->email_from}>");
+               $mimeMail->setSubject($this->subject);
+               $mimeMail->setHTMLBody($htmlMsg);
+               $mimeMail->setTXTBody($msg);
+
+               $mail =& Mail::factory($mailFactory);
+               $body = $mimeMail->get();
+
+        $setHeader['Reply-To'] = "{$this->getSubmitValue('fname')} {$this->getSubmitValue('lname')} <{$this->getSubmitValue('email')}>";
+
+               $headers = $mimeMail->headers($setHeader);
+
+               $res = $mail->send($this->email, $headers, $body);
+               if (PEAR::isError($res)) {
+                       return Toolkit_Common::handleError($res);
+               } else {
+                       return $res;
+               }
+       }
+
+       //      }}}
+
+    // {{{ _getMemberName()
+    /**
+     * return the member name from PDO call
+     *
+     * @access protected
+     * @return string
+     */
+    function _getMemberName()
+    {
+        try {
+            $sql  = "
+            SELECT member_name
+              FROM member
+             WHERE member_id = :mid";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ":mid",
+                $GLOBALS['memberAuth']->getAuthData('member_id'),
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    // }}}
+       //      {{{     getTopicFields()
+
+    /**
+     * get event topics
+     *
+     * @return array topics
+     * @access protected
+     */
+       protected function getTopicFields()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM categories
+                 ORDER BY name";
+
+            $topics = array('' => '-- Select --');
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $topics[$row['id']] = $row['name'];
+                       }
+
+                       return $topics;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ hasEndDate()
+
+    /**
+     * verifies if we have a valid end date to work with
+     *
+     * @param string $d end date
+     *
+     * @return boolean if the end date is
+     */
+    protected function hasEndDate($d)
+    {
+        $pattern = '/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/';
+        if (preg_match($pattern, $d, $m)) {
+            return checkdate((int) $m[1], (int) $m[2], (int) $m[3]);
+        } else {
+            return false;
+        }
+    }
+
+    //  }}}
+
+    //  {{{ formatValue()
+
+    /**
+     * Format an array into an acceptable string
+     *
+     * @param mixed  &$i     array values to format or null value for
+     *                       element that was not filled in
+     * @param string $format string to format values into
+     *
+     * @return string formatted string
+     * @access public
+     */
+    public function formatValue(&$i, $format)
+    {
+        //  Allow for 0 to be not empty.  This allows for minutes in the
+        //  time arrays to be valid if they are on the hour ie. (1:00 pm)
+        $notEmpty = create_function('$v', 'return strlen($v) > 0;');
+        if (is_array($i) && count(array_filter($i, $notEmpty)) == 3) {
+            list($x, $y, $z) = array_values($i);
+            eval("\$i = sprintf('$format', $x, $y, $z);");
+        } else {
+            $i = null;
+        }
+    }
+
+    //  }}}
+
+       //      {{{     insertData()
+
+    /**
+     * Inserts contact data into the contact db
+     *
+     * @param array $values submitted values
+        *
+     * @return object result of db insert query
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $values = $this->_geocode($values);
+
+               try {
+            // need to set the dates up first
+            unset($values['id']);
+            $values['visable'] = 0;
+            $sql = Toolkit_Common::createSQLInsert(
+                $this->tableName,
+                array_keys($values)
+            );
+            $sql .= " RETURNING id";
+            $stmt = Toolkit_Common::prepareQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+            $stmt->execute();
+            return $stmt->fetchColumn();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    private function _geocode(array $values)
+    {
+        $geocoder = new GeocodeYahoo();
+        if (!$values['address'] && !$values['city'] && !$values['state']) {
+            return $values;
+        }
+        $address = array(
+                       'city'  => $values['city'],
+                       'state' => $values['state'],
+                       'zip'   => $values['zip'],
+               );
+               if (!empty($values['address'])) {
+                       $address['street'] = $values['address'];
+               }
+        try {
+            $response = $geocoder->geocodeAddress($address);
+            $responseArray = unserialize($response);
+            if ($responseArray['ResultSet']['Result'][0]['Latitude']) {
+                $values['lat'] = $responseArray['ResultSet']['Result'][0]['Latitude'];
+                $values['lon'] = $responseArray['ResultSet']['Result'][0]['Longitude'];
+            } else {
+                $values['lat'] = $responseArray['ResultSet']['Result']['Latitude'];
+                $values['lon'] = $responseArray['ResultSet']['Result']['Longitude'];
+            }
+        } catch (BadMethodCallException $e) {
+            Toolkit_Logger::logException('Invalid Arg', $e);
+        } catch (Exception $e) {
+            Toolkit_Logger::logException('Yahoo GeoCode', $e);
+        }
+        return $values;
+    }
+
+       //      {{{     processData()
+
+    /**
+     * Handles how to process the form when submitted
+     *
+     * @param array $values Form submitted values
+        *
+     * @return array Result of Insert / Update function
+     * @access protected
+     */
+       public function processData($values)
+       {
+               //      Form data used for the insert/update sql queries and
+               //      the form email.
+               $e = array();
+               $this->setFormData($e);
+
+        if (  (!$this->_didLatLonChange($values)
+            && $this->_didAddressChange($values))
+            || (!$values['lat'] && !$values['lon'])
+        ) {
+            $values = $this->_geocode($values);
+        }
+        unset($values['MAX_FILE_SIZE']);
+        if ($values['del_img_rmv'] && $values['img']) {
+                   $is = new Toolkit_Image_Server();
+            $is->imageDelete($values['img']);
+            $values['image'] = '';
+        }
+        if ($values['img']) {
+            $values['image'] = $values['img'];
+        }
+        if ($values['del_file_rmv'] && $values['file']) {
+                   $is = new Toolkit_Image_Server();
+            $is->imageDelete($values['file']);
+            $values['file'] = '';
+        }
+        if ($values['file_rmv']['name']) {
+            $fs = new Toolkit_FileServer_FileAdapter();
+            try {
+                $res = $fs->upload('file_rmv');
+            } catch (Toolkit_FileServer_Exception $e) {
+                Toolkit_Logger::logException('File Server', $e);
+                echo -1;
+                return;
+            }
+            $values['file'] = $res['name'];
+        }
+        if ($values['file']) {
+            $newFile = EventFile::createByValues(
+                array(
+                    'filename' => $values['file'],
+                    'urltext'  => $values['filename']
+                )
+            );
+            $values['files'] = array($newFile);
+        } else {
+            $values['files'] = array();
+        }
+        unset($values['file']);
+        unset($values['filename']);
+               //      Get rid of any defined un-needed elements.
+               //      un-needed elements after the form is submitted are defined
+               //      by the ending _rmv name.
+               foreach ($values as $k => &$v) {
+            if (!is_array($v)) {
+                $values[$k] = preg_replace("/\r/", "\n", $v);
+            }
+                       if (preg_match('/^.+_rmv$/', $k)) {
+                               unset($values[$k]);
+                       }
+               }
+
+               if ($values['recurr']) {
+                   if ($values['dayom']) {
+                       $values['weekom'] = null;
+                       $values['daysow'] = null;
+                   } else {
+                       $values['dayom'] = null;
+                       $values['daysow'] = array_sum($values['daysow']);
+                   }
+
+               } else {
+                   $values['dayom']  = null;
+                   $values['weekom'] = null;
+                   $values['daysow'] = null;
+               }
+               $bdate = $values['bdate'];
+               $edate = $values['edate'];
+        $this->formatValue($values['btime'], '%d:%02d %s');
+        $this->formatValue($values['etime'], '%d:%02d %s');
+       if ($values['reacur']) {
+            $recur['dow']        = $values['daysow'];
+            $recur['dom']        = $values['dayom'];
+            if ($recur['dow']) {
+                $recur['recur_week'] = ($values['weekom']) ? $values['weekom'] :null;
+            } else {
+                $recur['recur_week'] = null;
+            }
+       }
+           $eventId = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT);
+        if ($values['btime']) {
+            $values['starthour'] = $values['btime'];
+        } else {
+            $values['starthour'] = null;
+        }
+        unset($values['btime']);
+        if ($values['etime']) {
+            $values['endhour'] = $values['etime'];
+        } else {
+            $values['endhour'] = null;
+        }
+        unset($values['etime']);
+        if ($values['category']) {
+            $values['category'] = $this->eventMapper->fetchCategory(
+                $values['category']
+            );
+        }
+        $event = MemberEvent::createByValues($values);
+//        var_dump($event);
+//        var_dump($values);
+//        exit;
+        return $this->eventMapper->saveEvent($event);
+
+//             return true;
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span>
+               <!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="req">{error}</div>
+               <!-- END error -->';
+               $recurTmpl = '<tr class="recur-event">
+               <td class="labelcell">'.$required.'<label>{label}</label></td>
+               <td class="fieldcell">'.$error.'{element}</td></tr>';
+               $renderer->setElementTemplate($recurTmpl, 'dayom');
+               $renderer->setElementTemplate($recurTmpl, 'weekom');
+               $renderer->setElementTemplate($recurTmpl, 'daysow');
+               $renderer->setElementTemplate(
+                       '<tr><td colspan="2">'.$required.'{label}'
+                   .$error.'{element}</td></tr>',
+            'description'
+           );
+               $renderer->setElementTemplate(
+                       '<tr align="center"><td colspan="2">'
+                   .$required.'{label}'.$error.'{element}</td></tr>', 'submit_rmv'
+               );
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Handles how to display the current step the user is at in the form
+     *
+        * destroying and resetting the captcha value dis-allows someone from
+        * re-sending a form on a previous captcha.
+        *
+     * @return string form HTML state
+     * @access public
+     */
+       public function toHtml()
+       {
+        $GLOBALS['topScripts'][] = JQUERY_CDN_JS;
+        $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/textlimit.js';
+        $baseSecureUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? BASE_SECURE_URL
+            : BASE_URL;
+        $appBaseSecueUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? GLM_APP_BASE_SECURE_URL
+            : GLM_APP_BASE_URL;
+        $GLOBALS['topScripts'][]
+            = $appBaseSecueUrl
+            . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js';
+           $GLOBALS['topScripts'][] = GLM_APP_BASE_URL.'ckeditor/current/ckeditor.js';
+
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       $this->cleanForm();
+
+                       if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) {
+                               $this->freeze();
+                               $this->emailOwner();
+                               $output = $this->successMsg;
+                               header(
+                    'Location: ' . BASE_URL . "members-only-area/?rt=CommonEvents&page_id="
+                    . $_REQUEST['page_id']
+                               );
+                               exit;
+                       }
+            $this->sent = true;
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $GLOBALS['topScripts'][]
+                = 'http://maps.googleapis.com/maps/api/js?sensor=true';
+            $GLOBALS['bottomScripts'][]
+                = BASE_URL . 'Toolkit/Maps/geoCoder.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Events/libjs/edit-event.js';
+                       $output .= parent::toHtml();
+               } else {
+                       $GLOBALS['topScripts'][]
+                = 'http://maps.googleapis.com/maps/api/js?sensor=true';
+            $GLOBALS['bottomScripts'][]
+                = BASE_URL . 'Toolkit/Maps/geoCoder.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Events/libjs/edit-event.js';
+                       $output = parent::toHtml();
+               }
+               return $output;
+       }
+
+       //      }}}
+    /**
+     * check to see if the address (old on) is different than the one submitted
+     * if the event is not found then return false
+     *
+     * @param array $values The submitted values for the edit event form
+     *
+     * @return boolean
+     */
+    private function _didAddressChange($values)
+    {
+        $didAddressChange = false;
+        if (!$values['id'] && !ctype_digit($values['id'])) {
+            return $didAddressChange;
+        }
+        try {
+            $sql = "
+            SELECT address,city,state,zip
+              FROM events.events
+             WHERE id = :id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $values['id'], PDO::PARAM_INT);
+            $stmt->execute();
+            $address = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (!$address) {
+                return $didAddressChange;
+            } else {
+                if ($address['address'] != $values['address']) {
+                    $didAddressChange = true;
+                }
+                if ($address['city'] != $values['city']) {
+                    $didAddressChange = true;
+                }
+                if ($address['state'] != $values['state']) {
+                    $didAddressChange = true;
+                }
+                if ($address['zip'] != $values['zip']) {
+                    $didAddressChange = true;
+                }
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $didAddressChange;
+    }
+    private function _didLatLonChange($values)
+    {
+        $didLatLonChange = false;
+        if (!$values['id'] && !ctype_digit($values['id'])) {
+            return $didLatLonChange;
+        }
+        try {
+            $sql = "
+            SELECT lat,lon
+              FROM events.events
+             WHERE id = :id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $values['id'], PDO::PARAM_INT);
+            $stmt->execute();
+            $location = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (!$location) {
+                return $didLatLonChange;
+            } else {
+                if ($location['lat'] != $values['lat']) {
+                    $didLatLonChange = true;
+                }
+                if ($location['lon'] != $values['lon']) {
+                    $didLatLonChange = true;
+                }
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $didLatLonChange;
+    }
+       //      {{{     updateData()
+
+    /**
+     * Inserts contact data into the contact db
+     *
+     * @param array $values submitted values
+        *
+     * @return object result of db insert query
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+               try {
+            // if the address changes then get the lat lon
+            if (  (!$this->_didLatLonChange($values)
+                && $this->_didAddressChange($values))
+                || (!$values['lat'] && !$values['lon'])
+            ) {
+                $values = $this->_geocode($values);
+            }
+
+            $sql = Toolkit_Common::createSQLUpdate(
+                $this->tableName,
+                array_keys($values),
+                array('id = :id')
+            );
+
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    // {{{ getTimeStamp()
+    /**
+    * getTimeStamp
+    *
+    * @param mixed $MySqlDate Description of $MySqlDate
+    *
+    * @access public
+    * @return void
+    */
+    function getTimeStamp($MySqlDate)
+    {
+        $date_array    = explode("-", $MySqlDate); // split the array
+        $var_year      = $date_array[0];
+        $var_month     = $date_array[1];
+        $var_day       = $date_array[2];
+        $var_timestamp = mktime(0, 0, 0, $var_month, $var_day, $var_year);
+        return $var_timestamp; // return it to the user
+    }// }}}
+    // {{{ ordinalDay()
+    /**
+    * ordinalDay
+    *
+    * @param mixed $ord   Ord
+    * @param mixed $day   Day
+    * @param mixed $month Month
+    * @param mixed $year  Year
+    *
+    * @access public
+    * @return void
+    */
+    function ordinalDay($ord, $day, $month, $year)
+    {
+        $firstOfMonth = mktime(0, 0, 30, $month, 1, $year);
+        $lastOfMonth  = $firstOfMonth + date("t", $firstOfMonth) * 86400;
+        $dayOccurs = 0;
+
+        for ($i = $firstOfMonth; $i < $lastOfMonth ; $i += 86400) {
+            if (date("w", $i) == $day) {
+                $dayOccurs++;
+                if ($dayOccurs == $ord) {
+                    $ordDay = $i;
+                }
+            }
+        }
+        return $ordDay;
+    }// }}}
+    // {{{ getEventDates()
+    /**
+    * getEventDates
+    *
+    * @param mixed  $starttime Start time
+    * @param mixed  $endtime   End time
+    * @param mixed  $recur     Recur
+    * @param string $format    Format
+    *
+    * @access public
+    * @return void
+    */
+    function getEventDates($starttime, $endtime, $recur, $format = 'm/d/Y')
+    {
+        if (!is_array($recur)) {
+            return;
+        }
+        if ($starttime == $endtime) {
+            return;
+        }
+        if (is_array($recur['dow'])) {
+            $daysow = array_sum($recur['dow']);
+        }
+        if ($recur['recur_week'] == 9) {
+            $fWeekNum = date("W", $starttime);
+            if (date('w', $starttime) == 0) {
+                $fWeekNum++;
+            }
+            $lWeekNum = date("W", $endtime);
+            if (date('w', $endtime) == 0) {
+                $lWeekNum++;
+            }
+            for ($fi = $fWeekNum; $fi <= $lWeekNum; $fi = $fi + 2) {
+                $eWeeks[] = $fi;
+            }
+        }
+        for ($i = $starttime; $i <= $endtime; $i += 86400) {
+            if ($recur['recur_week'] != '') {
+                if ($daysow) {
+                    $ri = 1;
+                    for ($r=0;$r<7;$r++) {
+                        if ($daysow & $ri) {
+                            $ord = $this->ordinalDay($recur['recur_week'], $r, date('n', $i), date('Y', $i));
+                        }
+                        $ri = $ri << 1;
+                    }
+                } else {
+                    $ord = null;
+                }
+            } else {
+                $ord = null;
+            }
+            if ($recur['dom']) {
+                if (date("j", $i) == $recur['dom']) {
+                    $events[] = date($format, $i);
+                }
+            } elseif (is_array($recur['dow'])) {
+                $cur_dow = date("w", $i);
+                switch ($cur_dow) {
+                case 0:
+                    $cur_dow = 1;
+                    break;
+                case 1:
+                    $cur_dow = 2;
+                    break;
+                case 2:
+                    $cur_dow = 4;
+                    break;
+                case 3:
+                    $cur_dow = 8;
+                    break;
+                case 4:
+                    $cur_dow = 16;
+                    break;
+                case 5:
+                    $cur_dow = 32;
+                    break;
+                case 6:
+                    $cur_dow = 64;
+                    break;
+                }
+                if ((int)$cur_dow & $daysow) {
+                    $cDateWeek = date("W", $i);
+                    if (date('w', $time) == 0) {
+                        $cDateWeek++;
+                    }
+                    if ($recur['recur_week'] == 9) {
+                        if (in_array($cDateWeek, $eWeeks)) {
+                            $events[] = date($format, $i);
+                        }
+                    } elseif ($recur['recur_week'] != '') {
+                        if ($recur['recur_week'] && $i && $ord) {
+                            if ($i == $ord) {
+                                $events[] = date($format, $i);
+                            }
+                        }
+                    } else {
+                        $events[] = date($format, $i);
+                    }
+                }
+            }
+        }
+        return $events;
+    }// }}}
+}
diff --git a/Toolkit/Members/Events/EditEvent.php b/Toolkit/Members/Events/EditEvent.php
new file mode 100755 (executable)
index 0000000..0a9a98d
--- /dev/null
@@ -0,0 +1,1671 @@
+<?php
+/**
+ * New Event Form
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members_Events
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: AddEventForm.php,v 1.20 2010/07/04 23:58:22 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+require_once BASE . 'Toolkit/Forms/Rules/Image.php';
+
+/**
+ * Toolkit_Members_Events_EditEvent
+ *
+ * @category  Toolkit
+ * @package   Members_Events
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Events_EditEvent
+    extends Toolkit_FormBuilder
+    implements Toolkit_Form
+{
+       //      {{{     properties
+
+    /**
+     * Table in Database which holds the contact data
+        *
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'event';
+
+    /**
+     * Table meta data
+        *
+        * This is used when inserting/updating data for the records
+        * so the PDO's can use explicit data types for the parameters.
+        *
+     * @var    array
+     * @access public
+     */
+       public $tableMetaData;
+
+    /**
+        * Who to send the email to when the contact form is submitted
+        *
+        * If you leave this blank, its value will get set to the OWNER_EMAIL
+        * in the constructor.
+        *
+        * If you ***DO NOT*** want any emails to go out when the form is submitted
+        * then set the value to false. Do not set it to 0 for false, because the
+        * check uses a strict type check to determine if the value is actually
+        * false. This is what allows for the empty value as an option, which sets
+        * the value to OWNER_EMAIL and won't override the $email property if
+        * this class gets subclassed and the value for this property gets set in
+        * the properties of the subclass and not in the constructor after this
+        * constructor function is called.
+        *
+        * tongue twister...I know.
+        * <code>
+        * protected $email = false;
+        * </code>
+        *
+     * @var    unknown
+     * @access protected
+     */
+       protected $email;
+
+    /**
+     * From header in the owner email
+        *
+        * This just sets the From header in the owner email
+        * SITENAME <from@email.com>
+        *
+        * It gets set to the constant SITENAME in the constructor if you leave
+        * empty here, but you can set it to something different here to override
+        * that if you desire.
+        *
+     * @var    unknown
+     * @access protected
+     */
+       protected $siteName;
+
+    /**
+        * Email subject and <h1> header in email
+        *
+        * It gets set in the constructor if you leave empty here, but you
+        * can set it to something different here to override that if you desire.
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $subject = 'New Event Submission';
+
+    /**
+     * Message to display if the form is successfully submitted
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $successMsg = '
+    <style type="text/css">
+        #category {display:none};
+        .listings {display:none};
+    </style>
+               <div id="form-sucess-top">
+            Your event has been successfully added to the events calendar,
+            however will not be visible until it has been approved by
+            the Web site administrator. Thank You.
+               </div>';
+
+    /**
+     * Extra rules for processesing
+        *
+        * This registers the Zip validation rules (and any others listed) for
+        * QuickForm.
+        *
+        * Zip validation checks both US and Canadian Zip codes
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array(
+        'phone',
+        array(
+            'checkEmail',
+            'callback',
+            'email',
+            'Validate'
+        ),
+        array(
+            'checkURI',
+            'callback',
+            'uri',
+            'Validate'
+        )
+    );
+
+    /**
+     * Options for flexy templating engine
+        *
+        * Pulls the preset options from the setup.phtml file
+        * overwrites the templateDir and compileDir to match this classes needs
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $flexyOptions;
+
+       //      }}}
+       //      {{{     __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        *
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+
+               if ($this->email !== false && empty($this->email)) {
+                       //      Set to false to turn off email function.
+                       $this->email
+                = (MEMBERS_EVENTS_NOTIFICATION_EMAIL)
+                ? MEMBERS_EVENTS_NOTIFICATION_EMAIL
+                : MEMBER_RECORD_UPDATES_ADVISOR;
+               }
+               if (empty($this->siteName)) {
+                       $this->siteName = SITENAME;
+               }
+               if (empty($this->subject)) {
+                       $this->subject = 'Contact Request from website ' . SITENAME;
+               }
+
+               $this->flexyOptions                = $GLOBALS['flexyOptions'];
+               $this->flexyOptions['templateDir'] = dirname(__FILE__) . "/templates/";
+               $this->flexyOptions['compileDir']
+                   = dirname(__FILE__) . "/templates/compiled/";
+
+               $var = basename(__FILE__, '.php');
+
+               $callbackUrl = ($_SERVER['HTTPS'] == 'on') ?
+                                                         BASE_SECURE_URL : BASE_URL;
+
+               $this->captchaOptions = array(
+                       'width' => 100,
+                       'height' => 50,
+                       'callback' => "{$callbackUrl}Toolkit/qfcaptcha.php?var=$var",
+                       'sessionVar' => $var,
+                       'imageOptions' => array(
+                               'font_size' => 16,
+                               'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/',
+                               'font_file' => 'times.ttf',
+                               'background_color' => '#cccccc',
+                               'obfuscation' => false,
+                               'angle' => true,
+                       ),
+               );
+       }
+
+       //      }}}
+
+    //  {{{ checkDate()
+
+    /**
+     * Validate date input
+     *
+     * allows for empty dates to be valid
+     *
+     * @param array $date date group from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+    public function checkDate($date)
+    {
+        if (!$date) {
+            return true;
+        } else {
+            return Validate::date($date, array('format' => '%m/%d/%Y'));
+        }
+    }
+
+    //  }}}
+    //  {{{ checkDateRange()
+
+    /**
+     * Validate date input
+     *
+     * allows for empty end date to be valid
+     *
+     * @param array $d date group from form
+     *
+     * @return boolean true if valid, false if not
+     * @access public
+     */
+    public function checkDateRange(array $d)
+    {
+        if (!$this->hasEndDate($d[1])) {
+            //  no end date is a valid date range
+            return true;
+        }
+
+        $pattern = '/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/';
+        if (preg_match($pattern, $d[0], $m)) {
+            $t1 = mktime(0, 0, 0, (int) $m[1], (int) $m[2], (int) $m[3]);
+            $bdate = new Date($t1);
+        }
+        if (preg_match($pattern, $d[1], $m)) {
+            $t2    = mktime(0, 0, 0, (int) $m[1], (int) $m[2], (int) $m[3]);
+            $edate = new Date($t2);
+        }
+        if ($bdate && $edate) {
+            //  0 if the dates are equal - valid
+            // -1 if $bdate is before $edate - valid
+            //  1 if $bdate is after $edate - invalid
+            $res = Date::compare($bdate, $edate);
+            return ($res !== 1);
+        }
+        return true;
+    }
+
+    //  }}}
+       //      {{{     configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements()
+       {
+        $e = array();
+
+               //      All Elements are created here.  This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventInfoHeader_rmv',
+            'display' => 'Event Information'
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'header',
+            'display' => 'Event Name'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'id'
+        );
+        $e[] = array(
+               'type' => 'hidden',
+               'req' => false,
+               'name' => 'member_id',
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'visable',
+            'val'  => 0
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'bdate',
+            'display' => 'Start Date',
+            'opts'     => array('id' => 'sdate')
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'edate',
+            'display' => 'End Date',
+            'opts'     => array('id' => 'edate')
+        );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'all_day',
+                       'display' => 'All Day Event?',
+                       'opts'    => 'Yes',
+                       'val'     => array(0, 1)
+               );
+        $e[] = array(
+            'type' => 'date',
+            'req' => false,
+            'name' => 'btime',
+            'display' => 'Start Time',
+            'opts' => array(
+                'format'   => 'h : i A',
+                'addEmptyOption' => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText' => array(
+                    'h' => 'hh',
+                    'i' => 'mm',
+                    'A' => 'am/pm'
+                ),
+                'optionIncrement' => array(
+                    'i' => 15,
+                ),
+            ),
+            'error' => 'ERROR: You must select a start time!',
+        );
+        $e[] = array(
+            'type' => 'date',
+            'req' => false,
+            'name' => 'etime',
+            'display' => 'End Time',
+            'opts' => array(
+                'format'   => 'h : i A',
+                'addEmptyOption' => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText' => array(
+                    'h' => 'hh',
+                    'i' => 'mm',
+                    'A' => 'am/pm'
+                ),
+                'optionIncrement' => array(
+                    'i' => 15,
+                ),
+            ),
+        );
+        $e[] = array(
+                       'type'    => 'advcheckbox',
+                       'req'     => false,
+                       'name'    => 'reacur',
+                       'display' => 'Recurring Event',
+                       'opts'    => 'Is this a recurring event?',
+                       'val'     => array(0, 1)
+               );
+               $daysOm = array(''=>'');
+               for ($i = 1; $i <= 31; ++$i) {
+                   $daysOm[$i] = $i;
+               }
+               $e[] = array(
+                   'type' => 'select',
+                       'name' => 'dayom',
+                   'display' => 'Every Month on',
+                   'opts' => $daysOm
+               );
+               $e[] = array(
+            'type' => 'select',
+            'req' => false,
+            'name' => 'weekom',
+            'display' => 'Recurs',
+            'opts' => array(
+                   '' => 'Every Week of Month',
+                   '9' => 'Every Other Week',
+                   '1' => 'Every First Week of Month',
+                   '2' => 'Every Second Week of Month',
+                   '3' => 'Every Third Week of Month',
+                   '4' => 'Every Fourth Week of Month',
+               ),
+        );
+               $weekdays = array(
+                   1 => 'Sunday',
+                       'Monday',
+                   'Tuesday',
+                   'Wednesday',
+                       'Thursday',
+                   'Friday',
+                   'Saturday'
+               );
+               $ri = 1;
+               for ($i = 1; $i <= 7; ++$i) {
+               $daysOw[] = array(
+                       'type' => 'advcheckbox',
+               'req'  => false,
+               'name' => $i,//$weekdays[$i],
+               'opts' => $weekdays[$i],
+                   'val' => array('', $ri)
+               );
+               $ri = $ri << 1;
+               }
+               //echo '<pre>'.print_r($daysOw, true).'</pre>';
+               $e[] = array(
+            'type'       => 'group',
+            'req'        => false,
+            'name'       => 'daysow',
+            'group'         => $daysOw,
+            'label'      => 'Days Of Week',
+            'seperator'  => ' ',
+            'appendName' => true
+        );
+        $e[] = array(
+            'type' => 'select',
+            'req' => true,
+            'name' => 'topicid',
+            'display' => 'Category',
+            'opts' => $this->getTopicFields(),
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'url',
+            'display' => 'Website'
+        );
+        $e[] = array(
+            'type' => 'textarea',
+            'req' => false,
+            'name' => 'descr',
+            'display' => 'Description',
+            'opts' => array('id' => 'descr')
+        );
+               $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'current_img_rmv',
+            'display' => 'Current Image'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'img'
+        );
+               $e[] = array(
+            'type' => 'file',
+            'req' => false,
+            'name' => 'img_file_rmv',
+            'display' => 'Event Image'
+        );
+               $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'img_instructions_rmv',
+            'opts' => '.jpg or .gif images only'
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventLocationInfoHeader_rmv',
+            'display' => 'Event Location Information
+                <div id="map-dialog">
+                    <div id="map_canvas" style="width:500px; height:400px"></div>
+                </div>
+                <a id="map-it" href="#">Map It</a>'
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'lat',
+            'opts' => array('id' => 'lat')
+        );
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'lon',
+            'opts' => array('id' => 'lon')
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'loc',
+            'display' => 'Place'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'address',
+            'display' => 'Address',
+            'opts'     => array('id' => 'address')
+        );
+        $e[]         = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'city',
+            'display' => 'City',
+            'opts'     => array('id' => 'city')
+        );
+        $e[]         = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'state',
+            'display' => 'State',
+            'opts'     => array('id' => 'state')
+        );
+        $e[]         = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'zip',
+            'display' => 'ZIP',
+            'opts'     => array('id' => 'zip')
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventContactHeader_rmv',
+            'display' => 'Event Contact Information'
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'contact',
+            'display' => 'Contact Person'
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'email',
+            'display' => 'Contact Email'
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'phone',
+            'display' => 'Contact Phone'
+        );
+               $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'current_file_rmv',
+            'display' => 'Current File'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'file'
+        );
+               $e[] = array(
+            'type' => 'file',
+            'req' => false,
+            'name' => 'file_rmv',
+            'display' => 'Event File'
+        );
+        $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'filename',
+            'display' => 'File Name'
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'eventInfoHeader_rmv',
+            'display' => 'Event Admin Information'
+        );
+        $e[]      = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_contact_name',
+            'display' => 'Contact Name Submitting Event'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_org_name',
+            'display' => 'Organization Name Submitting Event'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_phone',
+            'display' => 'Phone'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'admin_email',
+            'display' => 'Email Address'
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit_rmv',
+            'display' => 'Submit'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+        * Applies a data filter for the given fields when the form is submitted
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+        $f[] = array(
+            'element' => 'url',
+                       'filter' => array('Toolkit_Common', 'filterURI')
+        );
+
+        $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to handle setting up the form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureDefaults();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{     configureRules()
+
+    /**
+     * Form rule definitions
+     *
+        * Adds validation rules for the given fields
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+               //      Form Rules
+        $r = array();
+
+               $mimeTypes = array(
+                       'image/jpe',
+                       'image/jpeg',
+                       'image/jpg',
+                       'image/jfif',
+                       'image/pjpeg',
+                       'image/pjp',
+                       'image/gif',
+                       'image/png',
+               );
+
+               $r[] = array(
+            'element' => 'topicid',
+            'message' => 'ERROR: Invalid Topic!',
+            'type' => 'numeric',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Invalid Email Format!',
+            'type' => 'checkEmail',
+            'format' => array('use_rfc822' => true),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => array('bdate', 'edate'),
+            'message' => 'ERROR: Starting Date must be before Ending Date',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDateRange'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'bdate',
+            'message' => 'ERROR: Invalid date!',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDate'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'edate',
+            'message' => 'ERROR: Invalid date!',
+            'type' => 'callback',
+            'format' => array(&$this, 'checkDate'),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+        $r[] = array(
+            'element' => 'url',
+            'message' => 'ERROR: Invalid URL format',
+            'type' => 'checkURI',
+            'format' => array(
+                'allowed_schemes' => array('http', 'https'),
+                'strict' => true
+            ),
+            'validation' => $this->validationType,
+            'reset' => false,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'phone',
+            'message' => 'ERROR: Invalid Phone Format (xxx) xxx - xxxx!',
+            'type' => 'phone',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+        if ($this->useCaptcha) {
+            $r[] = array(
+                'element' => 'captcha_rmv',
+                'message' => 'ERROR: What you entered didn\'t match!',
+                'type' => 'CAPTCHA',
+                'format' => $this->captchaQuestion,
+                'validation' => $this->validationType,
+                'reset' => true,
+                'force' => false
+            );
+        }
+               if (is_uploaded_file($_FILES['img_file_rmv']['tmp_name'])) {
+                       $r[] = array(
+                'element' => 'img_file_rmv',
+                'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                'type' => 'mimetype',
+                'format' => $mimeTypes,
+                'validation' => $this->validationType,
+                'reset' => false,
+                'force' => false
+            );
+               }
+               $r[] = array(
+                       'element' => 'img_file_rmv',
+                       'message' => 'ERROR: Error uploading image!',
+                       'type' => 'Image',
+                       'format' => array(
+                               'form' => $this,
+                               'fieldName' => 'img_file_rmv',
+                               'imageField' => 'img',
+                               'is' => new Toolkit_FileServer_ImageAdapter(),
+                               'deleteExistingImage' => false,
+                               'injectImage' => array('tgtElement' => 'current_img_rmv')
+                       ),
+                       'validation' => 'server',
+                       'reset' => false,
+                       'force' => false
+               );
+        /*
+               $r[] = array(
+                       'element' => 'file_rmv',
+                       'message' => 'ERROR: Error uploading file!',
+                       'type' => 'Image',
+                       'format' => array(
+                               'form' => $this,
+                               'fieldName' => 'file_rmv',
+                               'imageField' => 'file',
+                               'is' => new Toolkit_FileServer_FileAdapter(),
+                               'deleteExistingImage' => false,
+                               'injectImage' => array('tgtElement' => 'current_file_rmv')
+                       ),
+                       'validation' => 'server',
+                       'reset' => false,
+                       'force' => false
+               );
+         */
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+       //      {{{     configureDefaults()
+
+    /**
+     * Form defaults
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+               if (ctype_digit($_GET['id'])) {
+            $sql = "
+            SELECT *
+              FROM event
+             WHERE id = :id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(":id", $_GET['id'], PDO::PARAM_INT);
+            $stmt->execute();
+            $d = $stmt->fetch(PDO::FETCH_ASSOC);
+            $d['visable'] = 0;
+            $d['current_file_rmv']
+                = ($d['file'])
+                ? '<a href="' . UPLOADED_FILES . 'original/' . $d['file'] . '">
+                '.$d['file'].'</a>
+                <input type="hidden" name="del_file_rmv" value="0">
+                <input type="checkbox" name="del_file_rmv" value="1">Delete File?'
+                : 'File not yet uploaded';
+            $d['current_img_rmv']
+                = ($d['img'])
+                ? '<img src="' . THUMB . $d['img'] . '">
+                <input type="hidden" name="del_img_rmv" value="0">
+                <input type="checkbox" name="del_img_rmv" value="1">Delete Image?'
+                : 'Image not yet uploaded';
+            $ri = 1;
+            for ($r = 1; $r <= 7; ++$r) {
+                if ($d['daysow']&$ri) {
+                    $daysow[$r] = $ri;
+                }
+                $ri = $ri << 1;
+            }
+            $d['daysow'] = $daysow;
+        } else {
+            $d['current_img_rmv'] = 'Image not yet uploaded';
+            $d['current_file_rmv'] = 'File not yet uploaded';
+        }
+        $d['member_id'] = $GLOBALS['memberAuth']->getAuthData('member_id');
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+
+       //      {{{     emailOwner()
+
+    /**
+     * Emails the owner the submitted data from the submitted form
+     *
+        * Uses a flexy template to render a nice looking html email.
+        * Fills in the supplied data from the form and doesn't add the
+        * empty fields the user didn't fill in.
+        *
+     * @param string $mailFactory What type of mail factory should we use
+     *
+     * @return boolean result of the mailing
+     * @access protected
+     */
+       protected function emailOwner($mailFactory = 'mail')
+       {
+               if (!$this->email) {
+                       return;
+               }
+
+               $topics = $this->getTopicFields();
+               $template = new HTML_Template_Flexy($this->flexyOptions);
+               $page     = new stdClass();
+
+               $page->email_from  = OWNER_EMAIL;
+               $page->subject     = $this->subject;
+               $page->client_info = $this->clientInfo;
+               $page->fname       = $this->_getMemberName();
+               $page->formData    = $this->formData;
+        // setup a link to admin section
+        $page->lname
+            = '<a href="'.BASE_URL.'admin/Events/list_events.phtml?pending=t">Events Admin</a>';
+        unset(
+            $page->formData['img'],
+            $page->formData['member_id'],
+            $page->formData['MAX_FILE_SIZE'],
+            $page->formData['comments'],
+            $page->formData['visable'],
+            $page->formData['id']
+        );
+        if ($page->formData['btime']['element']) {
+            $btime = explode(" / ", $page->formData['btime']['element']);
+            $page->formData['btime']['element']
+                = $btime[0] . ':' . (($btime[1] == '0')?'00':$btime[1]) . ' ' . $btime[2];
+        }
+        if ($page->formData['etime']['element']) {
+            $etime = explode(" / ", $page->formData['etime']['element']);
+            $page->formData['etime']['element']
+                = $etime[0] . ':' . (($etime[1] == '0')?'00':$etime[1]) . ' ' . $etime[2];
+        }
+               if ($page->formData['topicid']['element']) {
+                       //      Clean up the mail_ok flag so its human readable
+                       $page->formData['topicid']['element']
+                = $topics[$page->formData['topicid']['element']];
+               }
+
+               $template->compile('emailOwner.tpl');
+               $htmlMsg = $template->bufferedOutputObject($page);
+
+               $msg  = "{$page->subject}\n\n";
+               $msg .= "From {$page->fname} {$page->lname}\n\n";
+               $msg .= "Information\n\n";
+               foreach ($page->formData as $i) {
+                       $msg .= "{$i['label']}: {$i['element']}\n";
+               }
+
+        $mimeMail = new Mail_mime("\n");
+               $mimeMail->setFrom("Online Form <{$page->email_from}>");
+               $mimeMail->setSubject($this->subject);
+               $mimeMail->setHTMLBody($htmlMsg);
+               $mimeMail->setTXTBody($msg);
+
+               $mail =& Mail::factory($mailFactory);
+               $body = $mimeMail->get();
+
+        $setHeader['Reply-To'] = "{$this->getSubmitValue('fname')} {$this->getSubmitValue('lname')} <{$this->getSubmitValue('email')}>";
+
+               $headers = $mimeMail->headers($setHeader);
+
+               $res = $mail->send($this->email, $headers, $body);
+               if (PEAR::isError($res)) {
+                       return Toolkit_Common::handleError($res);
+               } else {
+                       return $res;
+               }
+       }
+
+       //      }}}
+
+    // {{{ _getMemberName()
+    /**
+     * return the member name from PDO call
+     *
+     * @access protected
+     * @return string
+     */
+    function _getMemberName()
+    {
+        try {
+            $sql  = "
+            SELECT member_name
+              FROM member
+             WHERE member_id = :mid";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ":mid",
+                $GLOBALS['memberAuth']->getAuthData('member_id'),
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+    // }}}
+       //      {{{     getTopicFields()
+
+    /**
+     * get event topics
+     *
+     * @return array topics
+     * @access protected
+     */
+       protected function getTopicFields()
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM topic
+                 ORDER BY descr";
+
+            $topics = array('' => '-- Select --');
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $topics[$row['id']] = $row['descr'];
+                       }
+
+                       return $topics;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ hasEndDate()
+
+    /**
+     * verifies if we have a valid end date to work with
+     *
+     * @param string $d end date
+     *
+     * @return boolean if the end date is
+     */
+    protected function hasEndDate($d)
+    {
+        $pattern = '/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/';
+        if (preg_match($pattern, $d, $m)) {
+            return checkdate((int) $m[1], (int) $m[2], (int) $m[3]);
+        } else {
+            return false;
+        }
+    }
+
+    //  }}}
+
+    //  {{{ formatValue()
+
+    /**
+     * Format an array into an acceptable string
+     *
+     * @param mixed  &$i     array values to format or null value for
+     *                       element that was not filled in
+     * @param string $format string to format values into
+     *
+     * @return string formatted string
+     * @access public
+     */
+    public function formatValue(&$i, $format)
+    {
+        //  Allow for 0 to be not empty.  This allows for minutes in the
+        //  time arrays to be valid if they are on the hour ie. (1:00 pm)
+        $notEmpty = create_function('$v', 'return strlen($v) > 0;');
+        if (is_array($i) && count(array_filter($i, $notEmpty)) == 3) {
+            list($x, $y, $z) = array_values($i);
+            eval("\$i = sprintf('$format', $x, $y, $z);");
+        } else {
+            $i = null;
+        }
+    }
+
+    //  }}}
+
+       //      {{{     insertData()
+
+    /**
+     * Inserts contact data into the contact db
+     *
+     * @param array $values submitted values
+        *
+     * @return object result of db insert query
+     * @access protected
+     */
+       protected function insertData($values)
+       {
+        $values = $this->_geocode($values);
+
+               try {
+            // need to set the dates up first
+            unset($values['id']);
+            $values['visable'] = 0;
+            $sql = Toolkit_Common::createSQLInsert(
+                $this->tableName,
+                array_keys($values)
+            );
+            $sql .= " RETURNING id";
+            $stmt = Toolkit_Common::prepareQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+            $stmt->execute();
+            return $stmt->fetchColumn();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    private function _geocode(array $values)
+    {
+        $geocoder = new GeocodeYahoo();
+        if (!$values['address'] && !$values['city'] && !$values['state']) {
+            return $values;
+        }
+        $address = array(
+                       'city'  => $values['city'],
+                       'state' => $values['state'],
+                       'zip'   => $values['zip'],
+               );
+               if (!empty($values['address'])) {
+                       $address['street'] = $values['address'];
+               }
+        try {
+            $response = $geocoder->geocodeAddress($address);
+            $responseArray = unserialize($response);
+            if ($responseArray['ResultSet']['Result'][0]['Latitude']) {
+                $values['lat'] = $responseArray['ResultSet']['Result'][0]['Latitude'];
+                $values['lon'] = $responseArray['ResultSet']['Result'][0]['Longitude'];
+            } else {
+                $values['lat'] = $responseArray['ResultSet']['Result']['Latitude'];
+                $values['lon'] = $responseArray['ResultSet']['Result']['Longitude'];
+            }
+
+            return $values;
+        } catch (BadMethodCallException $e) {
+            Toolkit_Logger::logException('Invalid Arg', $e);
+        } catch (Exception $e) {
+            Toolkit_Logger::logException('Yahoo GeoCode', $e);
+        }
+
+    }
+
+       //      {{{     processData()
+
+    /**
+     * Handles how to process the form when submitted
+     *
+     * @param array $values Form submitted values
+        *
+     * @return array Result of Insert / Update function
+     * @access protected
+     */
+       public function processData($values)
+       {
+               //      Form data used for the insert/update sql queries and
+               //      the form email.
+               $e = array();
+               $this->setFormData($e);
+
+        unset($values['MAX_FILE_SIZE']);
+        if ($values['del_img_rmv'] && $values['img']) {
+                   $is = new Toolkit_Image_Server();
+            $is->imageDelete($values['img']);
+            $values['img'] = '';
+        }
+        if ($values['del_file_rmv'] && $values['file']) {
+                   $is = new Toolkit_Image_Server();
+            $is->imageDelete($values['file']);
+            $values['file'] = '';
+        }
+        if ($values['file_rmv']['name']) {
+            $fs = new Toolkit_FileServer_FileAdapter();
+            try {
+                $res = $fs->upload('file_rmv');
+            } catch (Toolkit_FileServer_Exception $e) {
+                Toolkit_Logger::logException('File Server', $e);
+                echo -1;
+                return;
+            }
+            $values['file'] = $res['name'];
+        }
+
+               //      Get rid of any defined un-needed elements.
+               //      un-needed elements after the form is submitted are defined
+               //      by the ending _rmv name.
+               foreach ($values as $k => &$v) {
+            if (!is_array($v)) {
+                $values[$k] = preg_replace("/\r/", "\n", $v);
+            }
+                       if (preg_match('/^.+_rmv$/', $k)) {
+                               unset($values[$k]);
+                       }
+               }
+
+               if ($values['reacur']) {
+                   if ($values['dayom']) {
+                       $values['weekom'] = null;
+                       $values['daysow'] = null;
+                   } else {
+                       $values['dayom'] = null;
+                       $values['daysow'] = array_sum($values['daysow']);
+                   }
+
+               } else {
+                   $values['dayom']  = null;
+                   $values['weekom'] = null;
+                   $values['daysow'] = null;
+               }
+               $bdate = $values['bdate'];
+               $edate = $values['edate'];
+        $this->formatValue($values['btime'], '%02d:%02d %s');
+        $this->formatValue($values['etime'], '%02d:%02d %s');
+       if ($values['reacur']) {
+            $recur['dow']        = $values['daysow'];
+            $recur['dom']        = $values['dayom'];
+            if ($recur['dow']) {
+                $recur['recur_week'] = ($values['weekom']) ? $values['weekom'] :null;
+            } else {
+                $recur['recur_week'] = null;
+            }
+       }
+           $eventId = $_REQUEST['id'];
+        if (ctype_digit($eventId)) {
+            $this->updateData($values);
+        } else {
+            $eventId = $this->insertData($values);
+        }
+        $this->insertEventRecur($bdate, $edate, $eventId, $recur);
+               return true;
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span>
+               <!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="req">{error}</div>
+               <!-- END error -->';
+               $recurTmpl = '<tr class="recur-event">
+               <td class="labelcell">'.$required.'<label>{label}</label></td>
+               <td class="fieldcell">'.$error.'{element}</td></tr>';
+               $renderer->setElementTemplate($recurTmpl, 'dayom');
+               $renderer->setElementTemplate($recurTmpl, 'weekom');
+               $renderer->setElementTemplate($recurTmpl, 'daysow');
+               $renderer->setElementTemplate(
+                       '<tr><td colspan="2">'.$required.'{label}'
+                   .$error.'{element}</td></tr>',
+            'descr'
+           );
+               $renderer->setElementTemplate(
+                       '<tr align="center"><td colspan="2">'
+                   .$required.'{label}'.$error.'{element}</td></tr>', 'submit_rmv'
+               );
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Handles how to display the current step the user is at in the form
+     *
+        * destroying and resetting the captcha value dis-allows someone from
+        * re-sending a form on a previous captcha.
+        *
+     * @return string form HTML state
+     * @access public
+     */
+       public function toHtml()
+       {
+        $GLOBALS['topScripts'][] = JQUERY_CDN_JS;
+        $baseSecureUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? BASE_SECURE_URL
+            : BASE_URL;
+        $appBaseSecueUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? GLM_APP_BASE_SECURE_URL
+            : GLM_APP_BASE_URL;
+        $GLOBALS['topScripts'][]
+            = $appBaseSecueUrl
+            . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js';
+           $GLOBALS['topScripts'][] = GLM_APP_BASE_URL.'ckeditor/current/ckeditor.js';
+
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       $this->cleanForm();
+
+                       if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) {
+                               $this->freeze();
+                               $this->emailOwner();
+                               $output = $this->successMsg;
+                               header(
+                    'Location: ' . BASE_URL . "members-only-area/?rt=Events&page_id=36"
+                               );
+                               exit;
+                       }
+            $this->sent = true;
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $GLOBALS['topScripts'][]
+                = 'http://maps.googleapis.com/maps/api/js?sensor=true';
+            $GLOBALS['bottomScripts'][]
+                = BASE_URL . 'Toolkit/Maps/geoCoder.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Events/libjs/edit-event.js';
+                       $output .= parent::toHtml();
+               } else {
+                       $GLOBALS['topScripts'][]
+                = 'http://maps.googleapis.com/maps/api/js?sensor=true';
+            $GLOBALS['bottomScripts'][]
+                = BASE_URL . 'Toolkit/Maps/geoCoder.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Events/libjs/edit-event.js';
+                       $output = parent::toHtml();
+               }
+               return $output;
+       }
+
+       //      }}}
+    /**
+     * check to see if the address (old on) is different than the one submitted
+     * if the event is not found then return false
+     *
+     * @param array $values The submitted values for the edit event form
+     *
+     * @return boolean
+     */
+    private function _didAddressChange($values)
+    {
+        $didAddressChange = false;
+        if (!$values['id'] && !ctype_digit($values['id'])) {
+            return $didAddressChange;
+        }
+        try {
+            $sql = "
+            SELECT address,city,state,zip
+              FROM event
+             WHERE id = :id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $values['id'], PDO::PARAM_INT);
+            $stmt->execute();
+            $address = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (!$address) {
+                return $didAddressChange;
+            } else {
+                if ($address['address'] != $values['address']) {
+                    $didAddressChange = true;
+                }
+                if ($address['city'] != $values['city']) {
+                    $didAddressChange = true;
+                }
+                if ($address['state'] != $values['state']) {
+                    $didAddressChange = true;
+                }
+                if ($address['zip'] != $values['zip']) {
+                    $didAddressChange = true;
+                }
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $didAddressChange;
+    }
+    private function _didLatLonChange($values)
+    {
+        $didLatLonChange = false;
+        if (!$values['id'] && !ctype_digit($values['id'])) {
+            return $didLatLonChange;
+        }
+        try {
+            $sql = "
+            SELECT lat,lon
+              FROM event
+             WHERE id = :id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $values['id'], PDO::PARAM_INT);
+            $stmt->execute();
+            $location = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (!$location) {
+                return $didLatLonChange;
+            } else {
+                if ($location['lat'] != $values['lat']) {
+                    $didLatLonChange = true;
+                }
+                if ($location['lon'] != $values['lon']) {
+                    $didLatLonChange = true;
+                }
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $didLatLonChange;
+    }
+       //      {{{     updateData()
+
+    /**
+     * Inserts contact data into the contact db
+     *
+     * @param array $values submitted values
+        *
+     * @return object result of db insert query
+     * @access protected
+     */
+       protected function updateData($values)
+       {
+               try {
+            // if the address changes then get the lat lon
+            if (  (!$this->_didLatLonChange($values)
+                && $this->_didAddressChange($values))
+                || (!$values['lat'] && !$values['lon'])
+            ) {
+                $values = $this->_geocode($values);
+            }
+
+            $sql = Toolkit_Common::createSQLUpdate(
+                $this->tableName,
+                array_keys($values),
+                array('id = :id')
+            );
+
+            return Toolkit_Common::processQuery(
+                $this->dbh,
+                $this->tableName,
+                $sql,
+                $values
+            );
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    // {{{ getTimeStamp()
+    /**
+    * getTimeStamp
+    *
+    * @param mixed $MySqlDate Description of $MySqlDate
+    *
+    * @access public
+    * @return void
+    */
+    function getTimeStamp($MySqlDate)
+    {
+        $date_array    = explode("-", $MySqlDate); // split the array
+        $var_year      = $date_array[0];
+        $var_month     = $date_array[1];
+        $var_day       = $date_array[2];
+        $var_timestamp = mktime(0, 0, 0, $var_month, $var_day, $var_year);
+        return $var_timestamp; // return it to the user
+    }// }}}
+    // {{{ ordinalDay()
+    /**
+    * ordinalDay
+    *
+    * @param mixed $ord   Ord
+    * @param mixed $day   Day
+    * @param mixed $month Month
+    * @param mixed $year  Year
+    *
+    * @access public
+    * @return void
+    */
+    function ordinalDay($ord, $day, $month, $year)
+    {
+        $firstOfMonth = mktime(0, 0, 30, $month, 1, $year);
+        $lastOfMonth  = $firstOfMonth + date("t", $firstOfMonth) * 86400;
+        $dayOccurs = 0;
+
+        for ($i = $firstOfMonth; $i < $lastOfMonth ; $i += 86400) {
+            if (date("w", $i) == $day) {
+                $dayOccurs++;
+                if ($dayOccurs == $ord) {
+                    $ordDay = $i;
+                }
+            }
+        }
+        return $ordDay;
+    }// }}}
+    // {{{ getEventDates()
+    /**
+    * getEventDates
+    *
+    * @param mixed  $starttime Start time
+    * @param mixed  $endtime   End time
+    * @param mixed  $recur     Recur
+    * @param string $format    Format
+    *
+    * @access public
+    * @return void
+    */
+    function getEventDates($starttime, $endtime, $recur, $format = 'm/d/Y')
+    {
+        if (!is_array($recur)) {
+            return;
+        }
+        if ($starttime == $endtime) {
+            return;
+        }
+        if (is_array($recur['dow'])) {
+            $daysow = array_sum($recur['dow']);
+        }
+        if ($recur['recur_week'] == 9) {
+            $fWeekNum = date("W", $starttime);
+            if (date('w', $starttime) == 0) {
+                $fWeekNum++;
+            }
+            $lWeekNum = date("W", $endtime);
+            if (date('w', $endtime) == 0) {
+                $lWeekNum++;
+            }
+            for ($fi = $fWeekNum; $fi <= $lWeekNum; $fi = $fi + 2) {
+                $eWeeks[] = $fi;
+            }
+        }
+        for ($i = $starttime; $i <= $endtime; $i += 86400) {
+            if ($recur['recur_week'] != '') {
+                if ($daysow) {
+                    $ri = 1;
+                    for ($r=0;$r<7;$r++) {
+                        if ($daysow & $ri) {
+                            $ord = $this->ordinalDay($recur['recur_week'], $r, date('n', $i), date('Y', $i));
+                        }
+                        $ri = $ri << 1;
+                    }
+                } else {
+                    $ord = null;
+                }
+            } else {
+                $ord = null;
+            }
+            if ($recur['dom']) {
+                if (date("j", $i) == $recur['dom']) {
+                    $events[] = date($format, $i);
+                }
+            } elseif (is_array($recur['dow'])) {
+                $cur_dow = date("w", $i);
+                switch ($cur_dow) {
+                case 0:
+                    $cur_dow = 1;
+                    break;
+                case 1:
+                    $cur_dow = 2;
+                    break;
+                case 2:
+                    $cur_dow = 4;
+                    break;
+                case 3:
+                    $cur_dow = 8;
+                    break;
+                case 4:
+                    $cur_dow = 16;
+                    break;
+                case 5:
+                    $cur_dow = 32;
+                    break;
+                case 6:
+                    $cur_dow = 64;
+                    break;
+                }
+                if ((int)$cur_dow & $daysow) {
+                    $cDateWeek = date("W", $i);
+                    if (date('w', $time) == 0) {
+                        $cDateWeek++;
+                    }
+                    if ($recur['recur_week'] == 9) {
+                        if (in_array($cDateWeek, $eWeeks)) {
+                            $events[] = date($format, $i);
+                        }
+                    } elseif ($recur['recur_week'] != '') {
+                        if ($recur['recur_week'] && $i && $ord) {
+                            if ($i == $ord) {
+                                $events[] = date($format, $i);
+                            }
+                        }
+                    } else {
+                        $events[] = date($format, $i);
+                    }
+                }
+            }
+        }
+        //echo '<pre>'.print_r($events, true).'</pre>';exit;
+        return $events;
+    }// }}}
+        // {{{ insertEventRecur()
+    /**
+    * Description of insertEventRecur()
+    *
+    * @param date  $bdate    Description of $bdate
+    * @param date  $edate    Description of $edate
+    * @param int   $event_id Description of $event_id
+    * @param array $recur    Description of $recur
+    *
+    * @return void
+    * @access public
+    */
+    function insertEventRecur($bdate, $edate, $event_id, $recur)
+    {
+        try {
+            $sql = "
+            DELETE
+              FROM event_recur
+             WHERE event_id = :event_id";
+            $del = $this->dbh->prepare($sql);
+            $del->bindParam(":event_id", $event_id, PDO::PARAM_INT);
+            $del->execute();
+        } catch(PDOException $e) {
+            die($e->getMessage());
+        }
+
+        if (isset($recur) && is_array($recur)) {
+            $eventDates = $this->getEventDates(
+                strtotime($bdate),
+                strtotime($edate),
+                $recur
+            );
+            $fields = array('event_id', 'event_day');
+            $sql = Toolkit_Common::createSQLInsert(
+                'event_recur',
+                $fields
+            );
+            try {
+                if (isset($eventDates) && is_array($eventDates)) {
+                    foreach ($eventDates as $eventDay) {
+                        $eventValues = array(
+                            'event_id'  => $event_id,
+                            'event_day' => $eventDay
+                        );
+                        $stmt = Toolkit_Common::prepareQuery(
+                            $this->dbh,
+                            'event_recur',
+                            $sql,
+                            $eventValues
+                        );
+                        $stmt->execute();
+                    }
+                }
+            } catch (PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+        }
+    }
+    // }}}
+}
diff --git a/Toolkit/Members/Events/templates/emailOwner.tpl b/Toolkit/Members/Events/templates/emailOwner.tpl
new file mode 100755 (executable)
index 0000000..bebee85
--- /dev/null
@@ -0,0 +1,50 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+       <title>{title:h}</title>
+</head>
+<body>
+       <!-- {{{ body -->
+       <p>
+               <font size="4" face="arial, sans-serif">
+                       <b>{subject:h}</b>
+               </font>
+       </p>
+       <p>
+               <font size="3" face="arial, sans-serif">
+                       <b>From {fname:h} {lname:h}</b>
+               </font>
+       </p>
+       <table cellspacing="0" cellpadding="0" bgcolor="#c0c0c0" border="0">
+               <tr>
+                       <td>
+                               <table cellspacing="1" cellpadding="5" border="0" bgcolor="#c0c0c0" width="400">
+                                       {foreach:formData,v}
+                                               <tr flexy:if="v[element]" bgcolor="#c0c0c0">
+                                                       <td align="right" bgcolor="#ffffff">
+                                                               <font size="2" face="arial, sans-serif">
+                                                                       <b>{v[label]:h}</b>
+                                                               </font>
+                                                       </td>
+                                                       {if:v[nowrap]}
+                                                               <td nowrap bgcolor="#ffffff">
+                                                                       <font size="2" face="arial, sans-serif">{v[element]:h}</font>
+                                                               </td>
+                                                       {else:}
+                                                               <td bgcolor="#ffffff">
+                                                                       <font size="2" face="arial, sans-serif">{v[element]:h}</font>
+                                                               </td>
+                                                       {end:}
+                                               </tr>
+                                       {end:}
+                               </table>
+                       </td>
+               </tr>                                                           
+       </table>
+    <p>A new Event Record has been created from "Add Your Event"</p>
+       <p>The record needs to be approved before changes go live.</p>
+       <p>Goto <a href="{eventAdminURL}">Pending Records</a> to View and Approve their changes.</p>
+       <!-- }}} -->
+</body>
+</html>
diff --git a/Toolkit/Members/Exception.php b/Toolkit/Members/Exception.php
new file mode 100644 (file)
index 0000000..aca5575
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+/**
+ * BillingController.php
+ * 
+ * PHP version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Exception
+ * 
+ * Description of Toolkit_Members_Exception
+ * 
+ * @category  Toolkit
+ * @package   Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_Exception extends Exception
+{
+    /**
+     * Class constructor
+     * 
+     * @param string $message The exception message
+     * @param mixed  $code    The exception code
+     * 
+     * @access public
+     */
+       public function __construct($message = null, $code = 0)
+       {
+               parent::__construct($message, $code);
+       }
+}
+?>
diff --git a/Toolkit/Members/Exposure.php b/Toolkit/Members/Exposure.php
new file mode 100755 (executable)
index 0000000..6dca33e
--- /dev/null
@@ -0,0 +1,278 @@
+<?php
+/**
+ * Exposure.php
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Exposure.php,v 1.14 2009/11/10 20:09:02 jamie Exp $
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_Exposure
+ *
+ * Exposure Tracking for Member DB
+ * tracking:
+ * list view
+ * detail view
+ * click thru
+ * Tracking record in exposure table are updated if they have
+ * one already for that month.
+ * If they do not then one is added.
+ * NOTE:
+ * A check is done to see if the table exposure is there.
+ * If it is not there then it is created
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Steve Sutton
+ * @license   Gaslight Media
+ * @link      http://pear.php.net/package/Members
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Exposure implements SplObserver
+{
+    //  {{{ properties
+
+    /**
+     * PDO Object instance
+     * @var    object
+     * @access private
+     */
+    private $_dbh;
+
+    /**
+     * Member's member_id
+     * @var    int
+     * @access private
+     */
+    private $_member_id;
+
+    /**
+     * Original Table name is exposure
+     * can be changed to anything though
+     * @var    string
+     * @access private
+     */
+    private $_tableName = 'exposure';
+    /**
+     * Type of update list,detail,click
+     * @var    string
+     * @access private
+     */
+    private $_type;
+
+    //  }}}
+    // {{{ __construct($member_id, $type = 'list')
+
+    /**
+     * __construct
+     *
+     * @param int     $member_id Member
+     * @param string  $type      Which Type
+     *
+     * @return void
+     * @access public
+     */
+    function __construct($member_id, $type = 'list')
+    {
+        $this->_type      = $type;
+        $this->_member_id = $member_id;
+        if (!$this->checkType()) {
+                       throw new InvalidArgumentException('Invalid type given');
+        }
+        $this->_dbh = Toolkit_Database::getInstance();
+        $this->checkTableInstallation();
+    }
+
+    // }}}
+
+    // {{{ checkTableInstallation()
+
+    /**
+     * checkTableInstallation
+     *
+     * Check to see if $this->_tableName table exists in database
+     *
+     * @return void
+     * @access public
+     * @throws PEAR_Error
+     */
+    function checkTableInstallation()
+    {
+        try {
+            $sql  = "
+                SELECT column_name, data_type
+                  FROM information_schema.columns
+                 WHERE table_name = :tname";
+            $stmt = $this->_dbh->prepare($sql);
+            $stmt->bindParam(':tname', $this->_tableName, PDO::PARAM_STR);
+            $stmt->execute();
+            $row = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (empty($row)) {
+                $this->createTable();
+            }
+        } catch(PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+    // }}}
+    // {{{ checkType()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...type
+     *
+     * @return boolean Return description (if any) ...
+     * @access public
+     */
+    function checkType()
+    {
+        return in_array($this->_type, array('list', 'detail', 'click'));
+    }
+
+    // }}}
+    // {{{ createTable()
+
+    /**
+     * createTable
+     *
+     * Creates the $this->_tableName table for tracking views
+     *
+     * @return void
+     * @access public
+     */
+    function createTable()
+    {
+        $sql = "
+        CREATE TABLE {$this->_tableName} (
+            exposure_id SERIAL PRIMARY KEY,
+            list integer DEFAULT 0,
+            click integer DEFAULT 0,
+            detail integer DEFAULT 0,
+            edate date DEFAULT current_date,
+            member_id integer,
+            FOREIGN KEY (member_id) REFERENCES member(member_id) ON DELETE CASCADE
+        );";
+        $this->_dbh->query($sql);
+        $sql = "CREATE INDEX exp_member_id ON {$this->_tableName}(member_id)";
+        $this->_dbh->query($sql);
+        $sql = "CREATE INDEX exp_edate_id ON {$this->_tableName}(edate)";
+        $this->_dbh->query($sql);
+        $sql = "CREATE INDEX exp_edate_month_id ON {$this->_tableName}(date_part('month', edate))";
+        $this->_dbh->query($sql);
+        $sql = "CREATE INDEX exp_edate_year_id ON {$this->_tableName}(date_part('year',edate))";
+        $this->_dbh->query($sql);
+    }
+
+    // }}}
+
+    // {{{ runUpdate()
+
+    /**
+     * runUpdate()
+     *
+     * Based on $this->_type an update is maed if a record exist
+     * for that member for the current month.
+     * If there is no record then one is created.
+     *
+     * @return boolean|void
+     * @access public
+     * @throws PEAR_Error
+     */
+    public function runUpdate()
+    {
+               //      Make sure the member actually exists in the members table
+               //      before we try to manipulate its exposure count. If they don't
+               //      exists, then just get us out of here so we don't throw any errors
+               try {
+                       $sql = "
+                SELECT count(*) AS exists
+                  FROM member
+                 WHERE member_id = :member_id";
+
+                       $stmt = $this->_dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $this->_member_id, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('exists', $exists);
+                       $stmt->fetch();
+
+                       if (!$exists) {
+                               return false;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+        $sql = "
+            SELECT exposure_id
+              FROM {$this->_tableName}
+             WHERE member_id                 = :member_id
+               AND date_part('month', edate) = date_part('month', current_date)
+               AND date_part('year', edate)  = date_part('year', current_date)";
+        try {
+            $stmt = $this->_dbh->prepare($sql);
+            $stmt->bindParam(":member_id", $this->_member_id, PDO::PARAM_INT);
+            $stmt->execute();
+            $exp_data = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($exp_data['exposure_id']) {
+                // if something is found then update the exposure record
+                $sql = "
+                    UPDATE {$this->_tableName}
+                       SET {$this->_type} = {$this->_type} + 1
+                     WHERE exposure_id = :exposure_id";
+                try {
+                    $stmt2 = $this->_dbh->prepare($sql);
+                    $stmt2->bindParam(
+                        ":exposure_id",
+                        $exp_data['exposure_id'],
+                        PDO::PARAM_INT
+                    );
+                    $stmt2->execute();
+                } catch(PDOException $e) {
+                                       return Toolkit_Common::handleError($e);
+                }
+            } else {
+                // else insert a new exposure record
+                $sql = "
+                                       INSERT INTO {$this->_tableName} ({$this->_type}, member_id)
+                                       VALUES (1, :member_id)";
+                try {
+                    $stmt2 = $this->_dbh->prepare($sql);
+                    $stmt2->bindParam(
+                        ":member_id",
+                        $this->_member_id,
+                        PDO::PARAM_INT
+                    );
+                    $stmt2->execute();
+                } catch(PDOException $e) {
+                                       return Toolkit_Common::handleError($e);
+                }
+            }
+        } catch(PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+        }
+    }
+    // }}}
+
+       //      {{{     update()
+
+    /**
+     * Description for update()
+     * @param SplSubject $subject Description of $subject
+     * @access public
+     */
+       public function update(SplSubject $subject)
+       {
+               $this->runUpdate();
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/ExposureDetailReports.php b/Toolkit/Members/ExposureDetailReports.php
new file mode 100755 (executable)
index 0000000..e80cf0a
--- /dev/null
@@ -0,0 +1,184 @@
+<?php
+/**
+ * ExposureDetailReports.php
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: ExposureDetailReports.php,v 1.12 2010/01/09 19:05:38 jamie Exp $
+ * @link      <>
+ */
+
+
+/**
+ * Short description for class
+ *
+ * Exposuer Report of Member list,click,detail views
+ * for admin and member only area
+ * flag in BASE.setup.phtml of
+ *
+ * @category  MembersD
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      <>
+ */
+class Toolkit_Members_ExposureDetailReports
+       extends Toolkit_FlexyDataGridBuilder
+{
+    // {{{     properties
+
+    /**
+     * Table name for tracking
+     * @var    string
+     * @access protected
+     */
+    protected $tableName = 'exposure';
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+    protected $queryParams = array();
+
+    /**
+     * Template File
+     * @var    string
+     * @access protected
+     */
+    protected $template = 'exposureDetail.tpl';
+
+       //      }}}
+    //    {{{ __construct()
+
+    /**
+     * Class constructor
+     *
+     * define where templates for the data grid are at,
+     * then call the parent constructor which will handle
+     * finishing the settings for the datagrid.
+     *
+     * After all settings are finished you can call the toHTML()
+     * function on this object and the datagrid
+     * will be rendered and returned as a string.
+     * Optionally you could call show() and the datagrid would
+     * be rendered and output immediatley to the screen.
+     *
+        * @param PDO     $pdo          PDO object used in the datagrid
+     * @param integer $limit        The number of records to display per page.
+     * @param integer $page         The current page view. In most cases,
+        *                                                              this is useless. Note: if you specify
+        *                                                              this, the "page"GET variable will be ignored.
+     * @param string  $rendererType The type of renderer to use. You may
+        *                                                              prefer to use the $type argument of
+        *                                                              render, fill or getOutput.
+     *
+     * @access public
+     */
+    public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null
+    ) {
+        $this->pagerOptions['containerClass'] = 'pages';
+        parent::__construct($pdo, $limit, $page, $rendererType);
+    }
+
+    //    }}}
+
+    //    {{{ configureColumns()
+
+    /**
+     * Configures the columns (fields) that will be used in our datagrid renderer.
+     *
+     * @return void
+     * @access public
+     */
+    protected function configureColumns()
+    {
+        $month = new Structures_DataGrid_Column(
+                       'Month',
+            'month',
+            'month',
+            null,
+            null,
+            array(&$this, 'showMonth')
+               );
+        $this->addColumn($month);
+
+        $memberName = new Structures_DataGrid_Column(
+                       'Member Name',
+            'member_name',
+            'member_name'
+               );
+        $this->addColumn($memberName);
+
+        $list = new Structures_DataGrid_Column(
+                       'List',
+            'list',
+            'list'
+               );
+        $this->addColumn($list);
+
+        $detail = new Structures_DataGrid_Column(
+                       'Detail',
+            'detail',
+            'detail'
+               );
+        $this->addColumn($detail);
+
+        $click = new Structures_DataGrid_Column(
+                       'Click',
+            'click',
+            'click'
+               );
+        $this->addColumn($click);
+    }
+
+    //    }}}
+
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param integer $mid Member id to fetch reports for
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery($mid)
+    {
+        $sql = "
+                       SELECT e.*, date_part('epoch', e.edate) AS month, m.member_name
+                         FROM exposure e LEFT OUTER JOIN member m
+                                  ON (m.member_id = e.member_id)
+                        WHERE e.member_id = $mid";
+        parent::setQuery($sql);
+    }
+
+    //  }}}
+    //  {{{ showMonth()
+
+    /**
+     * Returns the monht for a record.
+     *
+     * @param array $data Structure Datagrid
+     *
+     * @access public
+     * @return string
+     */
+    public function showMonth($data)
+    {
+        return date('F, Y', $data['record']['month']);
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/Members/ExposureReports.php b/Toolkit/Members/ExposureReports.php
new file mode 100755 (executable)
index 0000000..44624ff
--- /dev/null
@@ -0,0 +1,399 @@
+<?php
+/**
+ * ExposureReports.php
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: ExposureReports.php,v 1.15 2010/07/14 23:31:14 jamie Exp $
+ * @link      <>
+ */
+
+
+/**
+ * Toolkit_Members_ExposureReports
+ *
+ * Exposuer Report of Member list,click,detail views
+ * for admin and member only area
+ * flag in BASE.setup.phtml of
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @link      <>
+ */
+class Toolkit_Members_ExposureReports extends Toolkit_FlexyDataGridBuilder
+{
+    // {{{ properties
+
+    /**
+     * Description for $noRecMessage
+     * @var string
+     * @acess protected
+     */
+    protected $noRecMessage = 'No Data Found';
+
+    /**
+     * Table name for tracking
+     * @var    string
+     * @access protected
+     */
+    protected $tableName = 'exposure';
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+    protected $queryParams = array();
+
+    /**
+     * Template File
+     * @var    string
+     * @access protected
+     */
+    protected $template = 'exposureList.tpl';
+
+    // }}}
+    // {{{ __construct()
+
+    /**
+     * Class constructor
+     *
+     * define where templates for the data grid are at,
+     * then call the parent constructor which will handle
+     * finishing the settings for the datagrid.
+     *
+     * After all settings are finished you can call the toHTML()
+     * function on this object and the datagrid
+     * will be rendered and returned as a string.
+     * Optionally you could call show() and the datagrid would
+     * be rendered and output immediatley to the screen.
+     *
+        * @param PDO     $pdo          PDO object used in the datagrid
+     * @param integer $limit        The number of records to display per page.
+     * @param integer $page         The current page view. In most cases,
+        *                                                              this is useless. Note: if you specify
+        *                                                              this, the "page"GET variable will be ignored.
+     * @param string  $rendererType The type of renderer to use. You may
+        *                                                              prefer to use the $type argument of
+        *                                                              render, fill or getOutput.
+     *
+     * @access public
+     */
+    public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null
+    ) {
+        $this->dbh = $pdo;
+        $this->checkTableInstallation();
+        $this->pagerOptions['containerClass'] = 'pages';
+        parent::__construct($pdo, $limit, $page, $rendererType);
+    }
+
+    // }}}
+
+    // {{{ createTable()
+
+    /**
+     * createTable
+     *
+     * Creates the $this->tableName table for tracking views
+     *
+     * @return void
+     * @access public
+     */
+    function createTable()
+    {
+        $sql = "
+            CREATE TABLE {$this->tableName} (
+                exposure_id SERIAL PRIMARY KEY,
+                list integer DEFAULT 0,
+                click integer DEFAULT 0,
+                detail integer DEFAULT 0,
+                edate date DEFAULT current_date,
+                member_id integer,
+                FOREIGN KEY (member_id) REFERENCES member(member_id) ON DELETE CASCADE
+            );";
+        $this->dbh->query($sql);
+    }
+
+    // }}}
+    // {{{ checkTableInstallation()
+
+    /**
+     * checkTableInstallation
+     *
+     * Check to see if $this->tableName table exists in database
+     *
+     * @return void
+     * @access public
+     */
+    function checkTableInstallation()
+    {
+        try {
+            $sql  = "
+                SELECT column_name, data_type
+                  FROM information_schema.columns
+                 WHERE table_name = :tname";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':tname', $this->tableName, PDO::PARAM_STR);
+            $stmt->execute();
+            $row = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (empty($row)) {
+                $this->createTable();
+            }
+        } catch(PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    // }}}
+    // {{{ configureColumns()
+
+    /**
+     * Configures the columns (fields) that will be used in our datagrid renderer.
+     *
+     * @return void
+     * @access public
+     */
+    protected function configureColumns()
+    {
+        $recordUrl = new Structures_DataGrid_Column(
+                       'DirectURL',
+            'directUrl',
+            'directUrl',
+            null,
+            null,
+            array(&$this, 'recordUrl')
+               );
+        $this->addColumn($recordUrl);
+
+        $memberName = new Structures_DataGrid_Column(
+                       'Member Name',
+            'member_name'
+               );
+        $this->addColumn($memberName);
+
+        $list = new Structures_DataGrid_Column(
+                       'List',
+            'list',
+            'list'
+               );
+        $this->addColumn($list);
+
+        $detail = new Structures_DataGrid_Column(
+                       'Detail',
+            'detail',
+            'detail'
+               );
+        $this->addColumn($detail);
+
+        $click = new Structures_DataGrid_Column(
+                       'Click',
+            'click',
+            'click'
+               );
+        $this->addColumn($click);
+    }
+
+    // }}}
+
+    // {{{ recordUrl()
+
+    /**
+     * Returns the url for a member.
+     *
+     * Used when configuring the columns for the data grid. This
+     * function generates the url to get to the member detail page
+     *
+     * @param array $data Structure_DataGrid
+     *
+     * @return string
+     * @access public
+     */
+    public function recordUrl($data)
+    {
+        $month  = $_GET['reportMonth']
+                       ? "&reportMonth={$_GET['reportMonth']}"
+                       : '';
+        $cat    = $_GET['cat']
+                       ? "&cat={$_GET['cat']}"
+                       : '';
+        $subCat = $_GET['subCat']
+                       ? "&subCat={$_GET['subCat']}"
+                       : '';
+        return "members.php?" .
+                       'rt=Members&ac=memberReports&' .
+            "member_id={$data['record']['member_id']}" .
+            $month .
+            $cat .
+            $subCat;
+    }
+
+    // }}}
+
+    // {{{ setControlObject()
+
+    /**
+     * Sets any control object variables that are going to be used in the template
+     *
+     * @return void
+     * @access public
+     */
+    protected function setControlObject()
+    {
+        try {
+            $letters = array();
+            if ($_REQUEST['reportMonth']) {
+                list($month, $year) = explode("|", $_REQUEST['reportMonth']);
+            } else {
+                $month = date('n');
+                $year  = date('Y');
+            }
+
+            $stime = date('m/d/Y', mktime(0, 0, 0, $month, 1, $year));
+            $etime = date('m/d/Y', mktime(0, 0, 0, $month +1, -1, $year));
+
+            $params = array();
+            if (isset($_GET['name']) && !empty($_GET['name'])) {
+                $noSpaceName = preg_replace('/[^[:alnum:]]/', '', urldecode($_GET['name']));
+                $spaceName = urldecode($_GET['name']);
+                $sanitizedNoSpaceName = $this->dbh->quote($noSpaceName);
+                $sanitizedSpaceName = $this->dbh->quote($spaceName);
+                $params[] = "(regexp_replace(m.member_name, '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceName)";
+            }
+
+            $sql = "
+            SELECT substr(upper(member_name), 1, 1) AS letter
+              FROM exposure e, member m
+                        WHERE e.member_id =  m.member_id
+               AND m.new_member = CAST(0 AS BOOLEAN)
+               AND e.edate     >= '$stime'
+               AND e.edate     <= '$etime'
+             ";
+            if (!empty($params)) {
+                $params = implode(' AND ', $params);
+                $sql    = "{$sql} AND $params";
+            }
+            $sql .= "
+            GROUP BY letter
+            ORDER BY letter";
+
+            foreach ($this->dbh->query($sql) as $row) {
+                $letters[$row['letter']] = $row['letter'];
+            }
+
+                       $addNumeric = false;
+                       while ($i = current($letters)) {
+                               if (is_numeric($i)) {
+                                       $addNumeric = true;
+                                       unset($letters[key($letters)]);
+                               } else {
+                                       break;
+                               }
+                       }
+
+                       if ($addNumeric) {
+                               array_unshift($letters, '0-9');
+                       }
+
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+
+        //  We only need to show the links of alphabet if we have more than
+        //  one letter to display.
+        if (count($letters) > 1) {
+            foreach ($_GET as $k => $v) {
+                if ($k != 'alpha') {
+                    if (is_array($v)) {
+                        foreach ($v as $i => $j) {
+                            $queryString .= $k . '[' . $i . ']=' . $j . '&';
+                        }
+                    } else {
+                        $queryString .= "$k=$v&";
+                    }
+                }
+            }
+            $links['All']['url'] = BASE_URL . "admin/members.php?{$queryString}";
+            $links['All']['class'] = empty($_GET['alpha']) ? 'curr' : null;
+            foreach ($letters as $v) {
+                $links[$v]['url'] = BASE_URL . "admin/members.php?{$queryString}alpha=$v";
+                if ($_GET['alpha'] == $v) {
+                    $links[$v]['class'] = 'curr';
+                }
+            }
+            $this->ctrlObj['letters'] = $links;
+        }
+    }
+
+    // }}}
+    //  {{{ setQuery()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param array $monthYear Which month to show
+     *
+     * @return void
+     * @access public
+     */
+    public function setQuery()
+    {
+        if ($_REQUEST['reportMonth']) {
+            list($month, $year) = explode("|", $_REQUEST['reportMonth']);
+        } else {
+            $month = date('n');
+            $year  = date('Y');
+        }
+
+        $stime = date('m/d/Y', mktime(0, 0, 0, $month, 1, $year));
+        $etime = date('m/d/Y', mktime(0, 0, 0, $month +1, -1, $year));
+
+        $params = array();
+        //  Limit to members whose first letter starts with the letter
+        //  a user clicked in the narrow alphabetically list.
+               if (isset($_GET['alpha']) && preg_match('/[0-9]/', $_GET['alpha'])) {
+                       $params[] = "substr(m.member_name, 1, 1) ~ '[0-9]'";
+               } elseif (isset($_GET['alpha']) && ctype_alpha($_GET['alpha'])) {
+                       $letter = $_GET['alpha'][0];
+            $params[] = "upper(substr(m.member_name, 1, 1)) = upper(" .
+                               $this->dbh->quote($letter) . ')';
+        }
+        if (isset($_GET['name']) && !empty($_GET['name'])) {
+                       $noSpaceName = preg_replace('/[^[:alnum:]]/', '', urldecode($_GET['name']));
+                       $spaceName = urldecode($_GET['name']);
+                       $sanitizedNoSpaceName = $this->dbh->quote($noSpaceName);
+                       $sanitizedSpaceName = $this->dbh->quote($spaceName);
+            $params[] = "(regexp_replace(m.member_name, '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceName)";
+               }
+
+        $sql   = "
+                       SELECT m.member_name, m.member_id, sum(e.list) AS list,
+                                  sum(e.click) as click, sum(e.detail) AS detail
+                         FROM exposure e, member m
+                        WHERE e.member_id =  m.member_id
+                          AND e.edate     >= '$stime'
+                          AND e.edate     <= '$etime'";
+
+        if (!empty($params)) {
+                       $params = implode(' AND ', $params);
+                       $sql    = "{$sql} AND $params";
+               }
+        $sql .= " GROUP BY m.member_name, m.member_id
+                        ORDER BY m.member_name";
+        parent::setQuery($sql);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/FileDownload.php b/Toolkit/Members/FileDownload.php
new file mode 100644 (file)
index 0000000..9c200a0
--- /dev/null
@@ -0,0 +1,224 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Download manager
+ * 
+ * PHP version 5
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: FileDownload.php,v 1.1 2009/08/21 14:20:56 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * File Download Manager
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_FileDownload
+{
+    //  {{{ properties
+
+
+    /**
+     * Database Handler
+     * @var    object   
+     * @access protected
+     */
+       protected $dbh;
+
+    //  }}}
+    //  {{{ __construct()
+
+
+    /**
+     * Constructor
+     * 
+     * @param PDO $pdo PHP Data Object to use for dbh
+     *
+     * @return void  
+     * @access public
+     */
+       public function __construct(PDO $pdo)
+    {
+               $this->dbh = $pdo;
+       }
+
+    //  }}}
+
+    //  {{{ fileExists()
+
+
+    /**
+     * Determine if the file exists
+     * 
+     * The file we are trying to get is determined by the file id passed in
+     * from the url.
+     * 
+     * @param integer $fid File id to retrieve
+     *
+     * @return mixed   array of file data if file exists, otherwise false
+     * @access protected
+     */
+    protected function fileExists($fid)
+    {
+        if (!is_numeric($fid) || !ctype_digit((string) $fid)) {
+            return false;
+        }
+
+        try {
+                       $sql = "
+                               SELECT *
+                                 FROM member_files
+                                WHERE member_id = :mid
+                                  AND id = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->mid, PDO::PARAM_INT);
+                       $stmt->bindParam(':id', $fid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+    //  {{{ getFile()
+
+
+    /**
+     * Get the data about the file we are requesting
+     * 
+     * @param integer $mid Member Id
+     * @param integer $fid File Id
+     *                      
+     * @return mixed   Array of file data if success, otherwise PEAR error
+     * @access public 
+     */
+       public function getFile($mid, $fid)
+    {
+        if (!$this->memberExists($mid)) {
+            return PEAR::raiseError('Invalid Member');
+        }
+
+        if (!$file = $this->fileExists($fid)) {
+            return PEAR::raiseError('Invalid File');
+        }
+
+        if (empty($file['file_name'])) {
+            $file['file_name'] = $file['original_name'];
+        }
+
+        return $file;
+       }
+
+    //  }}}
+
+    //  {{{ memberExists()
+
+
+    /**
+     * Determines if the member we are trying to get a file for is a real member
+     * 
+     * @param integer $mid member id to check for
+     *
+     * @return boolean True if real member, False if not
+     * @access protected 
+     */
+    protected function memberExists($mid)
+    {
+        if (!is_numeric($mid) || !ctype_digit((string) $mid)) {
+            return false;
+        }
+
+        try {
+            $sql = "
+                SELECT count(*) AS total
+                  FROM member
+                 WHERE member_id = :mid";
+
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':mid', $mid, PDO::PARAM_INT);
+            $stmt->execute();
+            $stmt->bindColumn('total', $total);
+            $row = $stmt->fetch();
+
+            if ($total) {
+                $this->mid = $mid;
+                return true;
+            } else {
+                return false;
+            }
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+    //  {{{ sendFileToBrowser()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Sends the file to the browser via headers
+     * 
+     * @param array $file File data to use
+     *
+     * @return void   
+     * @access public 
+     */
+    public function sendFileToBrowser(array $file)
+    {
+        extract($file);
+
+        $ext = pathinfo(MEMBER_UPLOADED_FILES . $name_on_disk, PATHINFO_EXTENSION);
+        switch ($ext) {
+        case 'txt' :
+            $type = 'text/plain';
+            break;
+
+        case 'doc' :
+            $type = 'application/msword';
+            break;
+
+        case 'xls' :
+            $type = 'application/vnd.ms-excel';
+            break;
+
+        case 'pdf' :
+            $type = 'application/pdf';
+            break;
+
+        default :
+            $type = 'application/pdf';
+            break;
+        }
+               // now get the pdf from file and push out to browser
+               // using header()
+               header("Content-Type: $type;");
+               header('Content-Disposition: attachment; filename="'.$file_name.'";');
+               header('Content-Length: '.(string) $size);
+               header('Cache-Control: maxage=3600;'); //Adjust maxage appropriately
+               header('Pragma: public;');
+               readfile(MEMBER_UPLOADED_FILES.$name_on_disk);
+               exit();
+    }
+
+    //  @codeCoverageIgnoreEnd
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/ActionDisplay.php b/Toolkit/Members/Import/ActionDisplay.php
new file mode 100644 (file)
index 0000000..1361f2f
--- /dev/null
@@ -0,0 +1,52 @@
+<?php
+
+/**
+ * Controls functionality to build page
+ * 
+ * PHP version 5
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ActionDisplay.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Checks to see if the form is built and if not builds it
+ * 
+ * Once the form is built, the appropriate action is taken to display the page
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_ActionDisplay
+    extends HTML_QuickForm_Action_Display
+{
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param  object  &$page      Parameter description (if any) ...
+     * @param  unknown $actionName Parameter description (if any) ...
+     * @return void   
+     * @access public 
+     */
+    public function perform(&$page, $actionName)
+    {
+        $page->isFormBuilt() or $page->buildForm();
+        parent::perform($page, $actionName);
+    }
+}
+?>
diff --git a/Toolkit/Members/Import/ActionUpload.php b/Toolkit/Members/Import/ActionUpload.php
new file mode 100644 (file)
index 0000000..7b79a14
--- /dev/null
@@ -0,0 +1,82 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ActionUpload.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_ActionUpload extends HTML_QuickForm_Action
+{
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param  object  &$page      Parameter description (if any) ...
+     * @param  unknown $actionName Parameter description (if any) ...
+     * @return void   
+     * @access public 
+     */
+    public function perform(&$page, $actionName)
+    {
+        $page->isFormBuilt() or $page->buildForm();
+
+        $pageName = $page->getAttribute('id');
+        $data = $page->controller->container();
+        $data['values'][$pageName] = $page->exportValues();
+        if (PEAR::isError($valid = $page->validate())) {
+            return $valid;
+        }
+        $data['valid'][$pageName] = $valid;
+
+        if (!$data['valid'][$pageName]) {
+            return $page->handle('display');
+        }
+
+        //  Get the element containing the upload
+        $element = $page->getElement('file');
+
+        //  Move the file and store the data
+        if ($element->isUploadedFile()) {
+            $newName = mktime() . '.csv';
+            $element->moveUploadedFile('./uploads', $newName);
+            $value = $element->getValue();
+            $data['_upload'] = basename($newName);
+        }
+
+        // redirect to next page
+        $next = $page->controller->getPage($page->controller->getNextName($pageName));
+        $next->handle('jump');
+
+    }
+}
+?>
diff --git a/Toolkit/Members/Import/AnalyzePage.php b/Toolkit/Members/Import/AnalyzePage.php
new file mode 100644 (file)
index 0000000..908331b
--- /dev/null
@@ -0,0 +1,104 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: AnalyzePage.php,v 1.2 2009/10/14 11:04:16 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_AnalyzePage
+    extends Toolkit_Members_Import_OpPage
+{
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->configureElements();
+        $this->insertData();
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureElements()
+    {
+        $e = array();
+
+        $prevNext = array();
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('back'),
+            'display' => '<< Previous Step'
+        );
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('next'),
+            'display' => 'Next Step >>'
+        );
+
+        $e[] = array(
+            'type' => 'group',
+            'req' => false,
+            'name' => 'control_buttons',
+            'group' => $prevNext,
+            'label' => '',
+            'seperator' => '&nbsp;',
+            'appendName' => false
+        );
+        
+        $this->setupElements($e);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/ConversionPage.php b/Toolkit/Members/Import/ConversionPage.php
new file mode 100644 (file)
index 0000000..1cc3ffe
--- /dev/null
@@ -0,0 +1,318 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ConversionPage.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Description for require_once
+ */
+require_once 'HTML/QuickForm/ElementGrid.php';
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_ConversionPage
+    extends Toolkit_Members_Import_Page
+{
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->configureElements();
+        $this->configureFilters();
+
+        $this->setDefaultAction('next');
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureElements()
+    {
+        $host = $this->controller->exportValue('serverPage', 'host');
+        $db   = $this->controller->exportValue('dbPage', 'database');
+        $cols = $this->controller->exportValue('fieldsPage', 'columns');
+
+        $dbh = new PDO("pgsql:host=$host user=postgres dbname=$db");
+
+        $gridColNames = array(
+            '[Import Field]',
+            'Cnvts To',
+            '[Database Field]',
+        );
+
+        $tables = $columns = $this->getAvailableTables($dbh);
+
+        $columns = array();
+        foreach ($tables as $i) {
+            $columns[$i] = $this->getTableColumns($dbh, $i);
+        }
+
+        $tables = array('' => '-- Select --') + $tables;
+
+        $e = array();
+
+        $prevNext = array();
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('back'),
+            'display' => '<< Previous Step'
+        );
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('next'),
+            'display' => 'Next Step >>'
+        );
+
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'header_rmv',
+            'display' => 'Select fields to import',
+        );
+        $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'info_rmv',
+            'display' => null,
+            'opts' => 'Select the field(s) you want to import from the file.<br>
+                       To select more than one field, hold down the CTRL key
+                       while selecting items.'
+        );
+        $e[] = array(
+            'type' => 'elementGrid',
+            'req' => false,
+            'name' => 'conversions',
+            'display' => 'Field Conversions',
+            'opts' => array('actAsGroup' => true)
+        );
+        $e[] = array(
+            'type' => 'group',
+            'req' => false,
+            'name' => 'control_buttons',
+            'group' => $prevNext,
+            'label' => '',
+            'seperator' => '&nbsp;',
+            'appendName' => false
+        );
+        
+        $this->setupElements($e);
+        $this->configureElementGrid(
+            'conversions',
+            $gridColNames,
+            $tables,
+            $columns,
+            $cols
+        );
+    }
+
+    //  }}}
+    //  {{{ configureFilters()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim',
+        );
+
+        $this->setupFilters($f);
+    }
+
+    //  }}}
+    //  {{{ configureElementGrid()
+
+
+    /**
+     * Short description for configureElementGrid()
+     * 
+     * Long description (if any) ...
+     * 
+     * @param unknown $eName    Parameter description (if any) ...
+     * @param unknown $colNames Parameter description (if any) ...
+     * @param unknown $tables   Parameter description (if any) ...
+     * @param unknown $columns  Parameter description (if any) ...
+     * @param array   $cols     Parameter description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureElementGrid(
+        $eName,
+        $colNames,
+        $tables,
+        $columns,
+        $cols
+    ) {
+        $e =& $this->getElement($eName);
+        $e->setColumnNames($colNames);
+        foreach ($cols as $i) {
+            unset($rec);
+
+            $rec[] =& $this->createElement(
+                'static',
+                null,
+                null,
+                $i
+            );
+
+            $rec[] =& $this->createElement(
+                'static',
+                null,
+                null,
+                ' > '
+            );
+            
+            $select =& $this->createElement(
+                'hierSelect',
+                $i
+            );
+            $select->setOptions(
+                array(
+                    $tables, 
+                    $columns,
+                )
+            );
+            $rec[] = $select;
+
+            $rec[] =& $this->createElement(
+                'text',
+                "{$i}_group"
+            );
+
+            $e->addRow(&$rec, '&nbsp;');
+        }
+    }
+
+    //  }}}
+    //  {{{ getAvailableTables()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param PDO $dbh Databse handler
+     * 
+     * @return array     $tables
+     * @access protected
+     */
+    protected function getAvailableTables(PDO $dbh)
+    {
+        try {
+            $sql = "
+                 SELECT table_name
+                   FROM information_schema.tables
+                  WHERE table_type = 'BASE TABLE'
+                    AND table_schema NOT IN ('pg_catalog',
+                    'information_schema')
+                  ORDER BY table_name";
+
+            $tables = array();
+            foreach ($dbh->query($sql) as $i) {
+                $tables[$i['table_name']] = $i['table_name'];
+            }
+            return $tables;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+    //  {{{ getTableColumns()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param PDO    $dbh   Database handler
+     * @param string $table Parameter description (if any) ...
+     * 
+     * @return array $cols
+     * @access protected
+     */
+    protected function getTableColumns(PDO $dbh, $table)
+    {
+        try {
+            $sql = "
+                 SELECT column_name
+                   FROM information_schema.columns
+                  WHERE table_name = '$table'
+                  ORDER BY column_name";
+
+            $cols = array('' => '-- Select --');
+            foreach ($dbh->query($sql) as $i) {
+                $cols[$i['column_name']] = $i['column_name'];
+            }
+            return $cols;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/DBPage.php b/Toolkit/Members/Import/DBPage.php
new file mode 100644 (file)
index 0000000..c8f692a
--- /dev/null
@@ -0,0 +1,241 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: DBPage.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_DBPage extends Toolkit_Members_Import_Page
+{
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->configureElements();
+        $this->configureDefaults();
+        $this->configureFilters();
+
+        $this->setDefaultAction('next');
+    }
+
+    //  }}}
+    //  {{{ getAvailableDatabases()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return array     Return description (if any) ...
+     * @access protected
+     */
+    protected function getAvailableDatabases()
+    {
+        $host = $this->controller->exportValue('serverPage', 'host');
+        try {
+            $sql = '
+                SELECT pgd1.datname AS "name"
+                  FROM pg_database pgd1, pg_user pgu
+                 WHERE pgd1.datdba = pgu.usesysid
+                 UNION 
+                SELECT pgd2.datname AS "name"
+                  FROM pg_database pgd2
+                 WHERE pgd2.datdba NOT IN (
+                        SELECT usesysid
+                  FROM pg_user)
+                 ORDER BY "name"';
+
+            $dbs = array('' => '-- Select --');
+            foreach ($this->dbh->query($sql) as $db) {
+                $dbs[$db['name']] = $db['name'];
+            }
+            return $dbs;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureElements()
+    {
+        $dbs = $this->getAvailableDatabases();
+        $e = array();
+
+        $existingRecs = array();
+        $existingRecs[] = array(
+            'type' => 'radio',
+            'req' => false,
+            'name' => 'duplicates',
+            'opts' => 'Delete',
+            'att' => 'delete'
+        );
+        $existingRecs[] = array(
+            'type' => 'radio',
+            'req' => false,
+            'name' => 'duplicates',
+            'opts' => 'Keep',
+            'att' => 'keep'
+        );
+
+        $prevNext = array();
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('back'),
+            'display' => '<< Previous Step'
+        );
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('next'),
+            'display' => 'Next Step >>'
+        );
+
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'header_rmv',
+            'display' => 'Select database to import to',
+        );
+        $e[] = array(
+            'type' => 'select',
+            'req' => true,
+            'name' => 'database',
+            'display' => 'Database',
+            'opts' => $dbs
+        );
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'configure_rmv',
+            'display' => 'Import Configuration',
+        );
+        $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'instructions_rmv',
+            'display' => null,
+            'opts' => 'Existing records will be dictated by email address'
+        );
+        $e[] = array(
+            'type' => 'group',
+            'req' => false,
+            'name' => 'existing',
+            'group' => $existingRecs,
+            'label' => 'Remove prior records from database?',
+            'seperator' => '&nbsp;',
+            'appendName' => false
+        );
+        $e[] = array(
+            'type' => 'group',
+            'req' => false,
+            'name' => 'control_buttons',
+            'group' => $prevNext,
+            'label' => '',
+            'seperator' => '&nbsp;',
+            'appendName' => false
+        );
+        
+        $this->setupElements($e);
+    }
+
+    //  }}}
+    //  {{{ configureFilters()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim',
+        );
+
+        $this->setupFilters($f);
+    }
+
+    //  }}}
+    //  {{{ configureDefaults()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureDefaults()
+    {
+        $d = array(
+            'duplicates' => 'keep'
+        );
+
+        $this->setupDefaults($d);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/FieldsPage.php b/Toolkit/Members/Import/FieldsPage.php
new file mode 100644 (file)
index 0000000..7e3aaeb
--- /dev/null
@@ -0,0 +1,192 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: FieldsPage.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Description for require_once
+ */
+require_once 'HTML/QuickForm/advmultiselect.php';
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_FieldsPage extends Toolkit_Members_Import_Page
+{
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->configureElements();
+        $this->configureFilters();
+
+        $this->setDefaultAction('next');
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureElements()
+    {
+        $fields = $this->_getCSVFields();
+        $e = array();
+
+        $prevNext = array();
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('back'),
+            'display' => '<< Previous Step'
+        );
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('next'),
+            'display' => 'Next Step >>'
+        );
+
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'header_rmv',
+            'display' => 'Select fields to import',
+        );
+        $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'info_rmv',
+            'display' => null,
+            'opts' => 'Select the field(s) you want to import from the file.<br>
+                       To select more than one field, hold down the CTRL key
+                       while selecting items.'
+        );
+        $e[] = array(
+            'type' => 'advmultiselect',
+            'req' => false,
+            'name' => 'columns',
+            'display' => 'Import Fields',
+            'labels' => array('Fields', 'Available', 'Selected'),
+            'opts' => $fields,
+            'att' => array(
+                'multiple' => 'multiple',
+                'size' => 40,
+                'style' => 'width:  200px;'
+            )
+        );
+        $e[] = array(
+            'type' => 'group',
+            'req' => false,
+            'name' => 'control_buttons',
+            'group' => $prevNext,
+            'label' => '',
+            'seperator' => '&nbsp;',
+            'appendName' => false
+        );
+        
+        $this->setupElements($e);
+    }
+
+    //  }}}
+    //  {{{ configureFilters()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim',
+        );
+
+        $this->setupFilters($f);
+    }
+
+    //  }}}
+    //  {{{ _getCSVFields()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return array   Return description (if any) ...
+     * @access private
+     */
+    private function _getCSVFields()
+    {
+        $data =& $this->controller->container();
+
+        $row = 0;
+        $handle = fopen("./uploads/{$data['_upload']}", 'r');
+        $fields = fgetcsv($handle, 1000, ',');
+        fclose($handle);
+
+        $cleanFields = array();
+        foreach ($fields as $i) {
+            $j = $this->clean($i);
+            $cleanFields[$j] = $j;
+        }
+
+        return $cleanFields;
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/FilePage.php b/Toolkit/Members/Import/FilePage.php
new file mode 100644 (file)
index 0000000..6121a1b
--- /dev/null
@@ -0,0 +1,173 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: FilePage.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_FilePage extends Toolkit_Members_Import_Page
+{
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+
+        $this->setDefaultAction('upload');
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureElements()
+    {
+        $e = array();
+
+        $prevNext = array();
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('back'),
+            'display' => '<< Previous Step'
+        );
+        $prevNext[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('upload'),
+            'display' => 'Next Step >>'
+        );
+
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'header_rmv',
+            'display' => 'Select CSV file to import',
+        );
+        $e[] = array(
+            'type' => 'file',
+            'req' => true,
+            'name' => 'file',
+            'display' => 'CSV Import File',
+        );
+        $e[] = array(
+            'type' => 'group',
+            'req' => false,
+            'name' => 'control_buttons',
+            'group' => $prevNext,
+            'label' => '',
+            'seperator' => '&nbsp;',
+            'appendName' => false
+        );
+        
+        $this->setupElements($e);
+    }
+
+    //  }}}
+    //  {{{ configureFilters()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim',
+        );
+
+        $this->setupFilters($f);
+    }
+
+    //  }}}
+    //  {{{ configureRules()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureRules()
+    {
+        $r = array();
+        $r[] = array(
+            'element' => 'file',
+            'message' => 'ERROR: Missing File!',
+            'type' => 'uploadedfile',
+            'format' => null
+        );
+        $r[] = array(
+            'element' => 'file',
+            'message' => 'ERROR: Must be *.csv!',
+            'type' => 'filename',
+            'format' => '/\.(csv|xls)$/i'
+        );
+            
+        $this->setupRules($r);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/ImportPage.php b/Toolkit/Members/Import/ImportPage.php
new file mode 100644 (file)
index 0000000..5d3fee1
--- /dev/null
@@ -0,0 +1,59 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ImportPage.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_ImportPage extends Toolkit_Members_Import_OpPage
+{
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->insertData($testRun = false);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/OpPage.php b/Toolkit/Members/Import/OpPage.php
new file mode 100644 (file)
index 0000000..2e3eaf0
--- /dev/null
@@ -0,0 +1,258 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: OpPage.php,v 1.2 2009/10/14 11:04:40 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_OpPage extends Toolkit_Members_Import_Page
+{
+    //  {{{ properties
+
+
+    /**
+     * Description for protected
+     * @var    array    
+     * @access protected
+     */
+    protected $data;
+
+    /**
+     * Description for protected
+     * @var    unknown  
+     * @access protected
+     */
+    protected $host;
+
+    /**
+     * Description for protected
+     * @var    unknown  
+     * @access protected
+     */
+    protected $dbName;
+
+    /**
+     * Description for protected
+     * @var    string   
+     * @access protected
+     */
+    protected $existing;
+
+    /**
+     * Description for protected
+     * @var    array    
+     * @access protected
+     */
+    protected $converts;
+
+    /**
+     * Description for protected
+     * @var    unknown  
+     * @access protected
+     */
+    protected $memberName;
+
+    //  }}}
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->data     =& $this->controller->container();
+        $this->host     = $this->controller->exportValue('serverPage', 'host');
+        $this->dbName   = $this->controller->exportValue('dbPage', 'database');
+        $this->existing = $this->controller->exportValue('dbPage', 'duplicates');
+        $conversions    = $this->controller->exportValue('conversionPage', 'conversions');
+
+        foreach ($conversions as $i => $j) {
+            //  make sure we aren't dealing w/ the empty option
+            if (!empty($i)) {
+                //  make sure we're dealing w/ a conversion and not a group
+                //  assignment
+                if (substr_compare($i, '_group', -6) != 0) {
+                    $this->converts[$j[0][0]][$j[1][0]] = array(
+                        'field' => $i,
+                        'group' => $conversions["{$i}_group"]
+                    );
+                }
+            }
+        }
+
+        $this->setDefaultAction('next');
+    }
+
+    //  }}}
+
+    //  {{{ insertData()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param  boolean   $testRun Parameter description (if any) ...
+     * @return unknown   Return description (if any) ...
+     * @access protected
+     */
+    protected function insertData($testRun = true)
+    {
+        try {
+            $dsn = "pgsql:host={$this->host} user=postgres dbname={$this->dbName}";
+            $dbh = new PDO($dsn);
+            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+
+            $dbh->beginTransaction();
+
+            $dbh->query("SET CLIENT_ENCODING TO 'WIN'");
+            
+            $csvFile = $this->getCSVFile("./uploads/{$this->data['_upload']}");
+
+            foreach ($this->converts as $table => $fields) {
+                if ($this->existing == 'delete') {
+                    $dbh->query("DELETE FROM $table");
+                }
+
+                $sql = $this->getTableQuery($table, $fields);
+                $stmt = $dbh->prepare($sql);
+
+                $success = $failed = 0;
+                //  Loop through all rows of the csv file
+                foreach ($csvFile as $csvRow) {
+                    //  loop through all conversion fields in the table
+                    foreach ($fields as $field => $data) {
+                        $bind = ":$field";
+                        //  if the csv field value contians data
+                        $value = trim($csvRow[$data['field']]);
+                        if (!empty($value)) {
+                            $stmt->bindValue($bind, $value);
+                        } else {
+                            $stmt->bindValue($bind, null, PDO::PARAM_NULL);
+                        }
+                    }
+                    $stmt->execute() ? ++$success : ++$failed;
+                }
+            }
+
+            if ($testRun) {
+                $dbh->rollBack();
+                echo '<div id="failReport">';
+                echo "There will be $success inserts and $failed failed inserts";
+                echo '</div>';
+            } else {
+                $dbh->commit();
+                echo "You succussfully inserted $success new records";
+            }
+        } catch (PDOException $e) {
+            $dbh->rollBack();
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+    //  {{{ getCSVFile()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param  unknown   $file Parameter description (if any) ...
+     * @return array     Return description (if any) ...
+     * @access protected
+     */
+    protected function getCSVFile($file)
+    {
+        //  Read in the CSV file that was uploaded.
+        $row = 0;
+        $handle = fopen($file, 'r');
+        while (false !== ($tiers = fgetcsv($handle, 1000, ','))) {
+            $num = count($tiers);
+            if ($row == 0) {
+                $columns = array();
+                for ($c = 0; $c < $num; ++$c) {
+                    $columns[$c] = $tiers[$c];
+                    $tiers[$c] = array();
+                }
+            } else {
+                for ($c = 0; $c < $num; ++$c) {
+                    $csvFile[$row][$columns[$c]] = $tiers[$c];
+                }
+            }
+            ++$row;
+        }
+
+        return $csvFile;
+    }
+
+    //  }}}
+    //  {{{ getTableQuery()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param  unknown   $table  Parameter description (if any) ...
+     * @param  array     $fields Parameter description (if any) ...
+     * @return string    Return description (if any) ...
+     * @access protected
+     */
+    protected function getTableQuery($table, array $fields)
+    {
+        foreach ($fields as $field => $data) {
+            //  Get the table columns we need to map to
+            $cols[] = $field;
+        }
+
+        //  Create the sql insert query
+        $columns = implode(', ', $cols);
+        $binds   = ':' . implode(', :', $cols);
+
+        return "INSERT INTO $table ($columns) VALUES ($binds)";
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/Page.php b/Toolkit/Members/Import/Page.php
new file mode 100644 (file)
index 0000000..82cfc9b
--- /dev/null
@@ -0,0 +1,375 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Page.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+abstract class Toolkit_Members_Import_Page extends HTML_QuickForm_Page
+{
+       //      {{{     __construct()
+
+       /**
+        * Class constructor
+        *
+     * @param PDO    $pdo         PHP Data Object
+     * @param string $formName    Form's name.
+     * @param string $method      (optional)Form's method defaults to 'POST'
+     * @param string $action      (optional)Form's action
+     * @param string $target      (optional)Form's target defaults to '_self'
+     * @param mixed  $attributes  (optional)Extra attributes for <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+        *                                                        submitted by adding a special hidden field
+        * 
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               //      T_VARIABLE error when passing this server
+               //      var in on the constructors params.
+        $action = empty($action)
+                 ? BASE_URL . 'Toolkit/Members/Import/index.php'
+                 : $action;
+        $this->HTML_QuickForm(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               $this->dbh = $pdo;
+       }
+
+       //      }}}
+       //      {{{ setupElements()
+
+    /**
+     * Sets up all the elements to the form
+     * 
+        * Takes a multi-dimensional array of form elements and uses them
+        * to set up the form objects elements
+     * 
+     * @param  array     $elements Multi-Dimensional array of form elements.
+        *
+     * @return void     
+     * @access protected
+     */
+       protected function setupElements(array $elements)
+       {
+               $this->formElements = $elements;
+               foreach ($elements as $e) {
+                       switch ($e['type']) {
+                       case 'group' :
+                               if (is_array($e['group']) && !empty($e['group'])) {
+                                       //      Special rendering for grouped elements.
+                                       unset($field);
+                                       foreach ($e['group'] as $g) {
+                                               $field[] =& HTML_QuickForm::createElement(
+                            $g['type'],
+                            $g['name'],
+                            $g['display'],
+                            $g['opts'],
+                            $g['att'],
+                            $g['val']
+                        );
+                                       }
+                                       $source =& $this->addGroup(
+                        $field,
+                        $e['name'],
+                        $e['label'],
+                        $e['seperator'],
+                        $e['appendName']
+                    );
+                               }
+                               break;
+
+                       case 'elementGrid' :
+                               $source =& $this->addElement(
+                    $e['type'],
+                    $e['name'],
+                    $e['display'],
+                    $e['opts'],
+                    $e['att'],
+                    $e['val']
+                );
+                               break;
+
+                       default :
+                               //      Render all elements except groups
+                               try {
+                                       $source =& $this->addElement(
+                        $e['type'],
+                        $e['name'],
+                        $e['display'],
+                        $e['opts'],
+                        $e['att'],
+                        $e['val']
+                    );
+
+                                       if (PEAR::isError($source)) {
+                                               throw new Exception ('PEAR QuickForm Element Error');
+                                       }
+                               } catch (HTML_QuickForm_Error $e) {
+                                       Toolkit_Common::dieGracefully(null, $e);
+                               } catch (Exception $e) {
+                                       Toolkit_Common::handleError($e);
+                               }
+
+                               if ($e['type'] == 'advmultiselect') {
+                                       $source->setLabel($e['labels']);
+                               }
+                               if ($e['name'] == 'categories') {
+                                       $res = $source->loadArray($this->categories);
+                                       if (PEAR::isError($res)) {
+                                               Toolkit_Common::dieGracefully(null, $res);
+                                       }
+                               }
+                               if ($e['type'] == 'header') {
+                                       $this->formHeaders[$e['display']] = $e;
+                               }
+                               break;
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{ setupRules()
+
+       /**
+        * Apply rules to the form
+        *
+        * 100 & 1000 char length limitations are automatically assigned to
+        * text/textarea elements to help reduce load limitations on the server.
+        * -request per Chuck in a conference call on (5/22/2009 @ 12:15pm)
+        *
+        * Applies rules that are defined in child classes to the form elements
+        * group rules can be kind of tricky, since you can't apply a rule
+        * directly to an element inside of a rule you have to define
+        * the rule inside a nest of array's and then add a group rule.
+        * the array will contain all the elements inside the group you wish
+        * to apply rules to.
+        *
+        * You can assign as many rules as you would like to individual elements,
+        * and you aren't required to make the array associative, although it is
+        * easier to see whats going on.
+        *
+        * see: http://pear.activeventure.com/package/package.html.html-quickform.html-quickform.addgrouprule.html
+        * for another example.
+        * <code>
+        * //   Define the rules for each element in the group.
+        * $num_rule = array(
+     *   'ERROR: Must contain a valid decimal number!',
+     *   'numeric'
+     * );
+        * //   Collect together the rules for each element.
+        * $lat_rules = array('lat' => array($num_rule));
+        * $lon_rules = array('lon' => array($num_rule));
+        * $r[] = array(
+     *   'element'    => 'latitude',
+        *   'message'    => 'ERROR:',
+        *   'type'       => 'group',
+        *   'format'     => $lat_rules,
+        *   'validation' => $this->validationType,
+        *   'reset'      => false,
+        *   'force'      => false
+     * );
+        * </code>
+        *
+        * To make a group required but not require every element in the group
+        * you can use the addGroupRule function again
+        * for example:  say you have a group of checkboxes and you only only
+        * require 1 be checked.  a simple group rule such as the following
+        * will handle this.
+        * N.B. notice the extra "howMany" index.
+        * <code>
+        * $r[] = array(
+     *   'element'   => 'element_name',
+        *   'message'   => 'ERROR: Error to display!',
+        *   'type'      => 'required',
+        *   'format'    => null,
+        *   'howMany'   => 1,
+        *   'validation'=> $this->validationType,
+        *   'reset'     => true,
+        *   'force'     => false,
+     * );
+        * </code>
+        *
+        * @param array $rules Multi-Dimensional array of rules for form elements.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function setupRules(array $rules = null)
+       {
+               if (is_array($this->formElements)) {
+                       foreach ($this->formElements as $e) {
+                               if ($this->validationType == 'client') {
+                                       $label = $e['display'];
+                               }
+                               if ($e['req']) {
+                                       if ($e['type'] == 'group') {
+                                               foreach ($e['group'] as $ge) {
+                                                       if ($ge['req']) {
+                                                               $rule[$ge['name']][] = array(
+                                    'ERROR: You must complete this field!',
+                                    'required',
+                                    null,
+                                    $this->validationType
+                                );
+                                                       }
+                                               }
+                                               $this->addGroupRule($e['name'], $rule);
+                                               unset($rule);
+                                       } elseif ($e['type'] == 'date') {
+                        if (!empty($e['error'])) {
+                            //  Custom error message for the date element.
+                            $error = $e['error'];
+                        } else {
+                            //  Default error message for the date element.
+                            $error = 'ERROR: You must enter a date!';
+                        }
+                                               $this->addGroupRule(
+                            $e['name'],
+                            $error,
+                            'required',
+                            3,
+                            $this->validationType
+                        );
+                                               if ($this->autoValidateDateElements) {
+                                                       $this->addRule(
+                                $e['name'],
+                                'ERROR: Date is invalid!',
+                                'callback',
+                                array(&$this, 'checkDateInput')
+                            );
+                                               }
+                                       } else {
+                                               $this->addRule(
+                            $e['name'],
+                            "$label ERROR: You must complete this field!",
+                            'required',
+                            null,
+                            $this->validationType
+                        );
+                                       }
+                               }
+                       }
+               }
+               if (is_array($rules)) {
+                       foreach ($rules as $r) {
+                               if (!is_array($r['element'])) {
+                                       $group = ($this->getElementType($r['element']) == 'group');
+                               }
+                               if ($group) {
+                                       $this->addGroupRule(
+                        $r['element'],
+                        $r['message'],
+                        $r['type'],
+                        $r['format'],
+                        $r['howMany'],
+                        $r['validation'],
+                        $r['reset']
+                    );
+                               }
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     setupFilters()
+
+    /**
+     * Sets any filters needed for the form elements when submitting
+     * 
+     * @param  array     $filters Element filters.
+        *
+        * @return void
+     * @access protected
+     */
+       protected function setupFilters($filters)
+       {
+               foreach ($filters as $f) {
+                       $res = $this->applyFilter($f['element'], $f['filter']);
+
+            if (PEAR::isError($res)) {
+                Toolkit_Common::handleError($res);
+            }
+               }
+       }
+
+       //      }}}
+       //      {{{     setupDefaults()
+
+    /**
+     * Sets the form default values
+     * 
+     * @param  array     $defaults Associative array of form default values.
+        *
+     * @return void     
+     * @access protected
+     */
+       protected function setupDefaults($defaults)
+       {
+               $this->setDefaults($defaults);
+       }
+
+       //      }}}
+    //  {{{ clean()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @param  unknown   $node Parameter description (if any) ...
+     * @return unknown   Return description (if any) ...
+     * @access protected
+     */
+    protected function clean($node)
+    {
+        $cleanNode = str_replace(' ', '_', $node);
+        return $cleanNode;
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/ServerPage.php b/Toolkit/Members/Import/ServerPage.php
new file mode 100644 (file)
index 0000000..2e847e4
--- /dev/null
@@ -0,0 +1,133 @@
+<?php
+
+/**
+ * Short description for file
+ * 
+ * Long description (if any) ...
+ * 
+ * PHP version 5
+ * 
+ * The license text...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ServerPage.php,v 1.1 2009/10/13 13:23:00 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Short description for class
+ * 
+ * Long description (if any) ...
+ * 
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Import_ServerPage extends Toolkit_Members_Import_Page
+{
+    //  {{{ buildForm()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void  
+     * @access public
+     */
+    public function buildForm()
+    {
+        parent::buildForm();
+
+        $this->configureElements();
+        $this->configureFilters();
+
+        $this->setDefaultAction('next');
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureElements()
+    {
+        $hosts = array(
+            '' => '-- Select --',
+            'localhost' => 'Localhost',
+            'devsys' => 'Development Server (devsys)',
+            'devsys2' => 'Development Server (devsys2)',
+            'ds1' => 'Live Server (ds1)',
+            'ds3' => 'Live Server (ds3)',
+        );
+
+        $e = array();
+        $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'header_rmv',
+            'display' => 'Upload destination',
+        );
+        $e[] = array(
+            'type' => 'select',
+            'req' => true,
+            'name' => 'host',
+            'display' => 'Select Host',
+            'opts' => $hosts
+        );
+        $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => $this->getButtonName('next'),
+            'display' => 'Next Step >>'
+        );
+        
+        $this->setupElements($e);
+    }
+
+    //  }}}
+    //  {{{ configureFilters()
+
+
+    /**
+     * Short description for function
+     * 
+     * Long description (if any) ...
+     * 
+     * @return void     
+     * @access protected
+     */
+    protected function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim',
+        );
+
+        $this->setupFilters($f);
+    }
+
+    //  }}}
+}
+?>
diff --git a/Toolkit/Members/Import/index.php b/Toolkit/Members/Import/index.php
new file mode 100644 (file)
index 0000000..a2b937f
--- /dev/null
@@ -0,0 +1,97 @@
+<?php
+/**
+ * index.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Members_Import
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id$
+ * @link      <>
+ */
+
+require_once '../../../setup.phtml';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$page = new stdClass();
+$page->styles = array(
+    BASE_URL . 'styles.css',
+    BASE_URL . 'forms.css'
+);
+$page->scripts = array(
+    GLM_APP_BASE_URL . 'glmPEAR/HTML/QuickForm/qfamsHandler.js'
+);
+
+ob_start();
+$wizard = new HTML_QuickForm_Controller('Wizard');
+$wizard->addPage(
+       new Toolkit_Members_Import_ServerPage(
+               Toolkit_Database::getInstance(),
+               'serverPage'
+       )
+);
+$wizard->addPage(
+       new Toolkit_Members_Import_DBPage(
+               Toolkit_Database::getInstance(),
+               'dbPage'
+       )
+);
+$wizard->addPage(
+       new Toolkit_Members_Import_FilePage(
+               Toolkit_Database::getInstance(),
+               'filePage'
+       )
+);
+$wizard->addPage(
+       new Toolkit_Members_Import_FieldsPage(
+               Toolkit_Database::getInstance(),
+               'fieldsPage'
+       )
+);
+$wizard->addPage(
+       new Toolkit_Members_Import_ConversionPage(
+               Toolkit_Database::getInstance(),
+               'conversionPage'
+       )
+);
+/*
+$wizard->addPage(
+       new Toolkit_Members_Import_ConfirmationPage(
+               Toolkit_Database::getInstance(),
+               'confirmationPage'
+       )
+);
+*/
+$wizard->addPage(
+       new Toolkit_Members_Import_AnalyzePage(
+               Toolkit_Database::getInstance(),
+               'analyzePage'
+       )
+);
+$wizard->addPage(
+       new Toolkit_Members_Import_ImportPage(
+               Toolkit_Database::getInstance(),
+               'importPage'
+       )
+);
+
+$wizard->addAction('upload', new Toolkit_Members_Import_ActionUpload());
+$wizard->addAction('display', new Toolkit_Members_Import_ActionDisplay());
+
+$wizard->run();
+$page->form = ob_get_contents();
+ob_end_clean();
+
+$options = $flexyOptions;
+$options['templateDir'] = dirname(__FILE__) . '/templates';
+$options['compileDir'] = dirname(__FILE__) . '/templates/compiled';
+
+$template = new HTML_Template_Flexy($options);
+$template->compile('template.html');
+$template->outputObject($page);
+?>
diff --git a/Toolkit/Members/Import/templates/template.html b/Toolkit/Members/Import/templates/template.html
new file mode 100644 (file)
index 0000000..1042e48
--- /dev/null
@@ -0,0 +1,28 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<title>Member CSV File Import</title>
+<meta http-equiv="content-type" content="text/html;charset=utf-8">
+<meta http-equiv="imagetoolbar" content="no">
+<meta http-equiv="imagetoolbar" content="false">
+{foreach:styles,v}
+<link rel="stylesheet" type="text/css" href="{v}">
+{end:}
+{foreach:scripts,v}
+<script type="text/javascript" src="{v}"></script>
+{end:}
+<style type="text/css">
+#failReport {
+    border: 2px solid red;
+    background-color: #ff9999;
+    padding: 10px;
+    margin: 10px auto;
+    text-align: center;
+}
+</style>
+</head>
+<body>
+    {form:h}
+</body>
+</html>
diff --git a/Toolkit/Members/Leads/ExportFileForm.php b/Toolkit/Members/Leads/ExportFileForm.php
new file mode 100644 (file)
index 0000000..e624992
--- /dev/null
@@ -0,0 +1,491 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Admin search functionality for memberdb
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ExportFileForm.php,v 1.3 2010/07/07 12:44:01 matrix Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Form to search the members database
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Leads_ExportFileForm
+    extends Toolkit_FormBuilder
+{
+    /**
+     * Description of $registeredRules
+     * 
+     * @var array
+     * @access protected
+     */
+       protected $registeredRules = array();
+       //      {{{ configureConstants()
+
+    /**
+     * Form constant definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+               $c = array(
+                       'Action' => $_GET['Actoin'],
+                       'Option' => $_GET['Option'],
+                       'search' => 1,
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+    /**
+     * Form default value definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureDefaults()
+       {
+        $storedQuery = $this->getStoredQuery();
+        if ($storedQuery) {
+            $d = array(
+                'start_date' => $storedQuery['start_date'],
+                'end_date'   => $storedQuery['end_date'],
+                'discover'   => $storedQuery['discover'],
+                'interest'   => $storedQuery['interest']
+            );
+        } else {
+            $d = array(
+                'start_date' => date('m/d/Y'),
+                'end_date'   => date('m/d/Y')
+            );
+        }
+
+               $this->setupDefaults($d);
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements()
+       {
+        $e = array();
+
+               //      All Grouped Elements are created here.
+               //$this->setDiscoveryGroups();
+               //$this->dGroups =& $this->getDiscoveryGroups();
+               $this->setInterestFields();
+               $this->interestsGroups =& $this->getInterestFields();
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'search'
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'dateHeader',
+            'display' => 'Dates'
+        );
+        $e[] = array(
+            'type' => 'date',
+            'req' => true,
+            'name' => 'start_date',
+            'display' => 'Start Date',
+            'opts' => array(
+                'format'   => 'm / d / Y',
+                'minYear'  => 2010,//date('Y') - 5,
+                'maxYear'  => date('Y'),
+                'addEmptyOption' => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText' => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy'
+                ),
+            ),
+            'att' => array('id' =>'sdate'),
+        );
+        $e[] = array(
+            'type' => 'date',
+            'req' => true,
+            'name' => 'end_date',
+            'display' => 'End Date',
+            'opts' => array(
+                'format'   => 'm / d / Y',
+                'minYear'  => 2010,//date('Y') - 5,
+                'maxYear'  => date('Y'),
+                'addEmptyOption' => true,
+                'emptyOptionValue' => '',
+                'emptyOptionText' => array(
+                    'm' => 'mm',
+                    'd' => 'dd',
+                    'Y' => 'yyyy'
+                ),
+            ),
+            'att' => array('id' =>'edate'),
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'name'    => 'interestHeader',
+            'display' => 'Interest'
+        );
+        if (is_array($this->interestsGroups)) {
+            foreach ($this->interestsGroups as $group => $gData) {
+                $this->myGroups[] = $gData;
+                $e[] = array(
+                    'type'       => 'group',
+                    'req'        => false,
+                    'name'       => 'interest['.$group.']',
+                    'group'         => $gData,
+                    'label'      => $group,
+                    'seperator'  => ' ',
+                    'appendName' => true
+                );
+            }
+        }
+        if (is_array($this->dGroups)) {
+            $e[] = array(
+                'type'    => 'header',
+                'name'    => 'howHearHeader',
+                'display' => 'How Did You Hear About Us?'
+            );
+            foreach ($this->dGroups as $i => $j) {
+                $this->myGroups[] = $j;
+                $e[] = array(
+                    'type'       => 'group',
+                    'req'        => false,
+                    'name'       => 'discover['.$i.']',
+                    'group'         => $j,
+                    'label'      => $i,
+                    'seperator'  => ' ',
+                    'appendName' => true
+                );
+            }
+        }
+               $e[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit',
+            'display' => 'Export Contacts'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper function to configure an entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureConstants();
+        $this->configureDefaults();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureRules()
+       {
+               $r = array();
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     getDiscoveryGroups()
+
+    /**
+     * Returns the field definitions of the contact db interest fields
+     *
+     * @return array     Group definitions for the interest fields
+     * @access protected
+     */
+       protected function getDiscoveryGroups()
+       {
+               if (is_array($this->discoveryGroups)) {
+            foreach ($this->discoveryGroups as $group => $data) {
+                foreach ($data as $k => $v) {
+                    $interests[$group][] = array('type' => 'checkbox',
+                                             'req' => false,
+                                             'name' => $k,
+                                             'opts' => $v);
+                }
+                       }
+               }
+
+               return $interests;
+       }
+
+       //      }}}
+       //      {{{     getInterestFields()
+
+    /**
+     * Returns the field definitions of the contact db interest fields
+     *
+     * @return array     Group definitions for the interest fields
+     * @access protected
+     */
+       protected function getInterestFields()
+       {
+               if (is_array($this->inquiries)) {
+            foreach ($this->inquiries as $group => $data) {
+                foreach ($data as $k => $v) {
+                    $interests[$group][] = array('type' => 'checkbox',
+                                             'req' => false,
+                                             'name' => $k,
+                                             'opts' => $v);
+                }
+                       }
+               }
+
+               return $interests;
+       }
+
+       //      }}}
+    // {{{ getStoredQuery()
+    
+    /**
+     * Get stored query
+     * 
+     * @return boolean|mixed
+     * @access public
+     * @throws PEAR_Error
+     */
+    function getStoredQuery()
+    {
+               $mid = $GLOBALS['memberAuth']->getAuthData('member_id');
+        try {
+            $sql = "
+            SELECT *
+              FROM member_leads
+             WHERE member_id = :mid";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(":mid", $mid, PDO::PARAM_INT);
+            $stmt->execute();
+            $data = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (!$data) {
+                // if none exists create one
+                $sql = "
+                INSERT INTO member_leads
+                (member_id)
+                VALUES
+                (:mid)";
+                $stmt2 = $this->dbh->prepare($sql);
+                $stmt2->bindParam(":mid", $mid, PDO::PARAM_INT);
+                $stmt2->execute();
+                return false;
+            } else {
+                return unserialize($data['query']);
+            }
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+        }
+    }// }}}
+
+       //      {{{     setDiscoveryGroups()
+
+    /**
+     * Contact DB interests
+     *
+     * @return void
+     * @access protected
+     * @throws PEAR_Error
+     */
+       protected function setDiscoveryGroups()
+       {
+               try {
+                       $sql = "
+                SELECT cd.*, dg.name as group
+                  FROM contact_disc cd LEFT OUTER JOIN discovery_groups dg ON (cd.groupid = dg.id)
+                 ORDER BY groupid, pos";
+
+            $i = array();
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $i[$row['group']][$row['id']] = $row['name'];
+                       }
+
+                       $this->discoveryGroups = $i;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setInterestFields()
+
+    /**
+     * Contact DB interests
+     *
+     * @return void
+     * @access protected
+     * @throws PEAR_Error
+     */
+       protected function setInterestFields()
+       {
+               try {
+            if (get_class($this) != 'Toolkit_Contacts_ContactUs') {
+                $where = 'inq_group.id != 6';
+            } else {
+                $where = 'inq_group.id = 6';
+            }
+                       $sql = "
+                SELECT contact_inq.*, inq_group.name as group
+                  FROM contact_inq LEFT OUTER JOIN inq_group ON (contact_inq.groupid = inq_group.id)
+                 WHERE $where
+                 ORDER BY groupid, pos";
+
+            $i = array();
+                       foreach ($this->dbh->query($sql) as $row) {
+                               $i[$row['group']][$row['id']] = $row['header'];
+                       }
+
+                       $this->inquiries = $i;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req"> * </span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="req"> {error} </div><!-- END error -->';
+               $tpl = '<tr align="center"><td colspan="2">{element}</td></tr>';
+        if (is_array($this->interestsGroups)) {
+            foreach ($this->interestsGroups as $group => $gData) {
+                $renderer->setGroupTemplate('<br>{content}', 'interest['.$group.']');
+                $renderer->setGroupElementTemplate('{element}', 'interest['.$group.']');
+                       $renderer->setElementTemplate('<tr><td colspan="2">'.$required.'{label}'.$error.'{element}</td></tr>', 'interest['.$group.']');
+            }
+        }
+        if (is_array($this->dGroups)) {
+            foreach ($this->dGroups as $group => $gData) {
+                $renderer->setGroupTemplate('{content}', 'discover['.$group.']');
+                $renderer->setGroupElementTemplate('{element}', 'discover['.$group.']');
+                       $renderer->setElementTemplate('<tr><td colspan="2">'.$required.'<b>{label}</b>'.$error.'{element}</td></tr>', 'discover['.$group.']');
+            }
+        }
+               $renderer->setElementTemplate($tpl, 'submit');
+       }
+
+    //  @codeCoverageIgnoreEnd
+       //      }}}
+    // {{{ storeQuery()
+    
+    /**
+     * Description for storeQuery()
+     * 
+     * @return void
+     * @access public
+     * @throws PEAR_Error
+     */
+    function storeQuery()
+    {
+               $mid = $GLOBALS['memberAuth']->getAuthData('member_id');
+        try {
+            $query = serialize($_POST);
+            $sql = "
+            UPDATE member_leads
+               SET query = :query
+             WHERE member_id = :mid";
+            $stmt2 = $this->dbh->prepare($sql);
+            $stmt2->bindParam(":mid", $mid, PDO::PARAM_INT);
+            $stmt2->bindParam(":query", $query, PDO::PARAM_STR);
+            $stmt2->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+        }
+    }// }}}
+       //      {{{     toHtml()
+
+       /**
+        * Call the rendering function to get the form in a string
+     * 
+     * @param PDO $dbh PDO
+        *
+        * @access public
+        * @return string $file The Form to be rendered or success msg.
+        */
+       public function toHtml(PDO $dbh)
+       {
+               $this->setupRenderers();
+        $GLOBALS['styleSheets'][] = GLM_APP_BASE_URL . 'libjs/Jscal/system.css';
+        $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/Jscal/utils.js';
+        $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/Jscal/calendar.js';
+        $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/Jscal/calendar-en.js';
+        $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/Jscal/calendar-setup.js';
+        $GLOBALS['bottomScripts'][] = BASE_URL . 'Toolkit/Members/Leads/libjs/visitorLeads.js';
+
+               if ($this->validate()) {
+                       $export = new Toolkit_Members_Leads_ExportLeads($dbh);
+                       $export->setQuery();
+            $this->storeQuery();
+                       $export->setDefaultSort(array('sort_field' => 'ASC'));
+                       $file = $export->exportAsFile($dbh);
+            if ($file) {
+                return $file;
+            } else {
+                return '<div id="form-warning-top">Nothing Matched your Search. Try again.</div>'
+                    . parent::toHTML();
+            }
+               }
+               return parent::toHTML();
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Leads/ExportLeads.php b/Toolkit/Members/Leads/ExportLeads.php
new file mode 100644 (file)
index 0000000..32da058
--- /dev/null
@@ -0,0 +1,700 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * ExportMembers.php
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: ExportLeads.php,v 1.7 2010/07/21 19:39:01 jamie Exp $
+ * @link      <>
+ */
+
+/**
+ * using our extension of the Pear Structures Datagrid set the
+ * renderer to CSV so we can send it out as a file.
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      <>
+ */
+class Toolkit_Members_Leads_ExportLeads extends Toolkit_DataGridBuilder
+{
+       //      {{{ properties
+
+    /**
+     * Options to pass to DataGrid
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $options;
+
+    /**
+     * Rendering options for DataGrid
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $rendererOptions = array(
+               'buildFooter' => true,
+               'buildHeader' => true,
+               'delimiter' => ',',
+               'enclosure' => '"',
+               'encoding' => 'ISO-8859-1',
+               'filename' => false,
+               'fillWithEmpytRows' => false,
+               'lineBreak' => "\n",
+               'numberAlign' => true,
+               'saveToFile' => false,
+               'useQuotes' => true,
+       );
+
+    /**
+     * SQL query used to obtain the DataGrid
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $sql;
+
+    /**
+     * How many records must exist in the Datagrid before the sort form shows up
+        *
+     * @var    integer
+     * @access protected
+     */
+       protected $sortableAfter = 10;
+
+    /**
+     * The HTML table id of the DataGrid
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $tableId = 'dataGrid';
+
+    /**
+     * The HTML class name of the DataGrid
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $tableClass = 'dataGrid';
+
+    /**
+     * The HTML id of the DataGrid sorting form (when present)
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $sortFormId = 'gridSorter';
+
+       /**
+        * Message to display to users if no records were found
+        *
+        * @var         String
+        * @access      Protected
+        * @see         Toolkit_DataGridBuilder::setNoRecordMessage()
+        */
+       protected $noRecMessage = 'No Records';
+    /**
+     * Path to create the export file 
+     * 
+     * @var string
+     * @access protected
+     */
+    protected $csvDirPath = '';
+
+       //      }}}
+       //      {{{ configureColumns()
+
+       /**
+        * Configures the columns (fields) that will be used in our datagrid renderer.
+        *
+        * @return void
+        * @access public
+        */
+    protected function configureColumns()
+       {
+        //  get reference to [controlledCities] section of config file
+               $memberName = new Structures_DataGrid_Column(
+                   'Member Name',
+            'member_name'
+        );
+               $this->addColumn($memberName);
+
+               $active = new Structures_DataGrid_Column(
+                   'Active',
+            'active'
+        );
+               $this->addColumn($active);
+
+               $street = new Structures_DataGrid_Column(
+                   'Street Address',
+            'street'
+        );
+               $this->addColumn($street);
+
+        if ($ctrlCities) {
+                       $city = new Structures_DataGrid_Column(
+                               'City',
+                               'city_name'
+                       );
+                       $this->addColumn($city);
+        } else {
+                       $city = new Structures_DataGrid_Column(
+                               'City',
+                               'city'
+                       );
+                       $this->addColumn($city);
+               }
+
+               $state = new Structures_DataGrid_Column(
+                       'State',
+                       'state_name'
+               );
+               $this->addColumn($state);
+
+               $zip = new Structures_DataGrid_Column(
+                       'Zip',
+                       'zip'
+               );
+               $this->addColumn($zip);
+
+               $phone = new Structures_DataGrid_Column(
+                       'Phone',
+                       'phone'
+               );
+               $this->addColumn($phone);
+
+               $fax = new Structures_DataGrid_Column(
+                       'Fax',
+                       'fax'
+               );
+               $this->addColumn($fax);
+
+               $tollFree = new Structures_DataGrid_Column(
+                       'Toll Free Phone Number',
+                       'toll_free'
+               );
+               $this->addColumn($tollFree);
+
+               $url = new Structures_DataGrid_Column(
+                       'Website Address',
+                       'url'
+               );
+               $this->addColumn($url);
+
+               $primaryContactFname = new Structures_DataGrid_Column(
+                       'Primary Contact First Name',
+                       'primary_contact_fname'
+               );
+               $this->addColumn($primaryContactFname);
+
+               $primaryContactLname = new Structures_DataGrid_Column(
+                       'Primary Contact Last Name',
+                       'primary_contact_lname'
+               );
+               $this->addColumn($primaryContactLname);
+
+               $primaryContactEmail = new Structures_DataGrid_Column(
+                       'Primary Contact Email',
+                       'process_email'
+               );
+               $this->addColumn($primaryContactEmail);
+
+               $emailAddress = new Structures_DataGrid_Column(
+                       'Email on Website',
+                       'member_contact_email'
+               );
+               $this->addColumn($primaryContactEmail);
+
+        if ($ctrlCities) {
+                       $mailingCity = new Structures_DataGrid_Column(
+                               'Mailing City Address',
+                               'mailing_city_name'
+                       );
+                       $this->addColumn($mailingCity);
+        } else {
+                       $mailingCity = new Structures_DataGrid_Column(
+                               'Mailing City Address',
+                               'mailing_city'
+                       );
+                       $this->addColumn($mailingCity);
+               }
+
+               $mailingState = new Structures_DataGrid_Column(
+                       'Mailing State',
+                       'mailing_state_name'
+               );
+               $this->addColumn($mailingState);
+
+               $mailingZip = new Structures_DataGrid_Column(
+                       'Mailing Zip',
+                       'mailing_zip'
+               );
+               $this->addColumn($mailingZip);
+
+               $joinDate = new Structures_DataGrid_Column(
+                       'Join Date',
+                       'join_date'
+               );
+               $this->addColumn($joinDate);
+       }
+
+       //      }}}
+    // {{{ exportAsFile()
+
+    /**
+     * throws out headers to the browser so the file can be downloaded
+     * there's a case for IE browsers which may change in future depending on
+     * Microsoft Whim:(
+     *
+     * @param PDO $dbh PDO
+     * 
+     * @access public
+     * @return boolean
+     */
+    public function exportAsFile(PDO $dbh)
+    {
+        // if the file is other than csv then set delimeter
+        if ($_REQUEST['file_type']) {
+            switch ($_REQUEST['file_type']) {
+            case "pipe":
+                $delimiter = "|";
+                break;
+            case "tab":
+                $delimiter = "\t";
+                break;
+            default:
+                $delimiter = ",";
+                break;
+            }
+            $this->rendererOptions['delimiter'] = $delimiter;
+        }
+        $fileOut = $this->toCSV($dbh);
+        if ($fileOut) {
+            if (ini_get('zlib.output_compression')) {
+                 ini_set('zlib.output_compression', 'Off');
+            }
+            header("Content-Type: application/force-download\n");
+            /* Correction for the stupid MSIE thing */
+            if (strstr(getenv('HTTP_USER_AGENT'), 'MSIE')) {
+                header("Content-Disposition: inline; filename=\"Member-Export.csv\"");
+            } else {
+                header("Content-Disposition: attachment; filename=\"Member-Export.csv\"");
+            }
+                       header('Content-Length: ' . filesize($fileOut));
+                       $fp = fopen($fileOut, 'rb');
+                       if (fpassthru($fp)) {
+                               unlink($fileOut);
+                       }
+            exit();
+        } else {
+            return false;
+        }
+    }
+    // }}}
+
+    // {{{ getDiscovery()
+    
+    /**
+     * Description for getDiscovery()
+     * 
+     * @return array|mixed $return or Toolkit_Common
+     * @access public 
+     */
+    function getDiscovery()
+    {
+        try {
+            $dbh = $GLOBALS['dbh'];
+            $sql = "
+              SELECT id, name
+                FROM contact_disc
+               ORDER BY groupid, pos";
+            $stmt = $dbh->query($sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $return[$row['id']] = $row['name'];
+            }
+            return $return;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+        }
+    }// }}}
+    // {{{ getInterest()
+    
+    /**
+     * Description for getInterest()
+     * 
+     * @param PDO $dbh PDO
+     * 
+     * @return array|mixed $return or Toolkit_Common 
+     * @access public
+     */
+    function getInterest(PDO $dbh)
+    {
+        try {
+            $sql = "
+              SELECT id, header as name
+                FROM contact_inq
+               ORDER BY groupid, pos";
+            $stmt = $dbh->query($sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $return[$row['id']] = $row['name'];
+            }
+            return $return;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+        }
+    }// }}}
+
+       //      {{{ setQuery()
+
+    /**
+     * Sets the sql query to use in the DataGrid to get the results
+     *
+     * @return void
+     * @access public
+     */
+       public function setQuery()
+       {
+        $params = $params2 = array();
+        $sql = "
+                       SELECT id, create_date, fname, lname, company,
+                              address, address2, city, state, zip, phone, fax, email,
+                                  discover, interest
+              FROM contact";
+        if (   $_REQUEST['interest']
+                       && is_array($_REQUEST['interest'])
+                       && !empty($_REQUEST['interest'])
+               ) {
+            // code to get interest out
+            foreach ($_REQUEST['interest'] as $groupName => $gData) {
+                foreach ($gData as $intId => $boolVal) {
+                    $params2[] = "interest like '%:{$intId}:%'";
+                }
+            }
+        }
+        if (   $_REQUEST['discover']
+                       && is_array($_REQUEST['discover'])
+                       && !empty($_REQUEST['discover'])
+               ) {
+            // code to get interest out
+            foreach ($_REQUEST['discover'] as $groupName => $gData) {
+                foreach ($gData as $intId => $boolVal) {
+                    $params2[] = "discover like '%:{$intId}:%'";
+                }
+            }
+        }
+        // for now the start and end date are required
+        if (   is_array($_REQUEST['start_date'])
+                       && !empty($_REQUEST['start_date'])
+            && is_array($_REQUEST['end_date'])
+                       && !empty($_REQUEST['end_date'])
+        ) {
+            $start_date = implode("/", $_REQUEST['start_date']);
+            $end_date = implode("/", $_REQUEST['end_date']);
+            $params[] = "create_date BETWEEN '{$start_date}'::date AND '{$end_date}'::date";
+        }
+        $params[] = "members = true";
+        if (!empty($params)) {
+            $sql .= " WHERE " . implode(" AND ", $params);
+        }
+        if (!empty($params2)) {
+            $sql .= " AND (" . implode(" OR ", $params2). ")";
+        }
+        $sql .= " ORDER BY id";
+        //echo '<p>'.$sql.'</p>';exit;
+        parent::setQuery($sql);
+       }
+
+       //      }}}
+       //      {{{     _getDate()
+
+    /**
+     * Description for _getDate()
+     * 
+     * @param mixed $key Description for key
+     * 
+     * @return string
+     * @throws RuntimeException 
+     * @access private
+     */
+       private function _getDate($key)
+       {
+               if (   filter_var($_POST[$key]['m'], FILTER_VALIDATE_INT)
+                       && filter_var($_POST[$key]['d'], FILTER_VALIDATE_INT)
+                       && filter_var($_POST[$key]['Y'], FILTER_VALIDATE_INT)
+               ) {
+                       return $_POST[$key]['Y'] . $_POST[$key]['m'] . $_POST[$key]['d'];
+               } else {
+
+                       throw new RuntimeException("Invalid date values for `$key`");
+               }
+       }
+
+       //      }}}
+       //      {{{     _getFieldIds()
+
+    /**
+     * Description for _getFieldIds()
+     * 
+     * @param mixed $key Key
+     * 
+     * @return string|void 
+     * @access private
+     */
+       private function _getFieldIds($key)
+       {
+               if (!isset($_POST[$key])) {
+                       return;
+               } elseif (!is_array($_POST[$key])) {
+                       return;
+               } else {
+                       $identifier = '';
+                       foreach ($_POST[$key] as $group => $values) {
+                               $identifier .= "$group-";
+                               foreach ($values as $id => $selected) {
+                                       if ($selected == '1') {
+                                               $identifier .= $id;
+                                       }
+                               }
+                       }
+                       return $identifier;
+               }
+       }
+
+       //      }}}
+       //      {{{     _getContactDiscoverFields()
+
+    /**
+     * Get contact discover fields
+     * 
+     * @param int   $total   Description of $total
+     * @param array $contact Description of $contact
+     * 
+     * @return array $discoverFields
+     * @access private
+     */
+       private function _getContactDiscoverFields($total, $contact)
+       {
+               $discoverFields = array();
+               for ($i = 0, $j = 1; $i < $total; ++$i, ++$j) {
+                       $discoverFields["How did you hear field $j"]
+                               = $contact[$i] ? '"' . $contact[$i] .'"' : null;
+               }
+
+               return $discoverFields;
+       }
+
+       //      }}}
+       //      {{{     _getContactInterestFields()
+
+    /**
+     * Get contact interest fields
+     * 
+     * @param int   $total   Description for $total
+     * @param array $contact Description for $contact
+     * 
+     * @return array
+     * @access private 
+     */
+       private function _getContactInterestFields($total, $contact)
+       {
+               $interestFields = array();
+               for ($i = 0, $j = 1; $i < $total; ++$i, ++$j) {
+                       $interestFields["Interest field $j"]
+                               = $contact[$i] ? '"' . $contact[$i] . '"' : null;
+               }
+               return $interestFields;
+       }
+
+       //      }}}
+       //      {{{     _getContactDiscoverValues()
+
+    /**
+     * Get contact discover values
+     * 
+     * @param array $contact         Contact array
+     * @param array $discover        Discover array
+     * @param array &$discoverValues Discover values
+     * 
+     * @return void 
+     * @access private
+     */
+       private function _getContactDiscoverValues(
+               array $contact,
+               array $discover,
+               array &$discoverValues
+       ) {
+               $discoverKeys = array_filter(explode(':', $contact['discover']));
+               foreach ($discoverKeys as $key) {
+                       $discoverValues[$contact['id']][] = $discover[$key];
+               }
+               return;
+       }
+
+       //      }}}
+       //      {{{     _getContactInterestValues()
+
+    /**
+     * Get contact interest values
+     * 
+     * @param array $contact         Contact array
+     * @param array $interest        Interest array
+     * @param array &$interestValues Interest values array
+     * 
+     * @return void
+     * @access private
+     */
+       private function _getContactInterestValues(
+               array $contact,
+               array $interest,
+               array &$interestValues
+       ) {
+               $interestKeys = array_filter(explode(':', $contact['interest']));
+               foreach ($interestKeys as $key) {
+                       $interestValues[$contact['id']][] = $interest[$key];
+               }
+               return;
+       }
+
+       //      }}}
+    
+    /**
+     * Set CSV path
+     * 
+     * @return void
+     * @access public 
+     */
+    function setCsvPath()
+    {
+        $this->csvDirPath = BASE . 'Toolkit/Members/Leads/csv_leads';
+        if (!is_dir($this->csvDirPath)) {
+            $curMask = umask(0);
+            mkdir($this->csvDirPath, 0775, true);
+            umask($curMask);
+        }
+    }
+       //      {{{ toCSV()
+
+    /**
+     * returns a CSV file of the datagrid
+     * 
+     * @param PDO $dbh PDO
+     *
+     * @return string|boolean|mixed Mixed from Toolkit_Common
+     * @access public
+     */
+       public function toCSV(PDO $dbh)
+       {
+        $this->setCsvPath();
+        //$discover = $this->getDiscovery();
+        $interest = $this->getInterest($dbh);
+        $discoverValues = $interestValues = array();
+        try {
+            $totalDisc = $totalInt = 0;
+            $stmt = $dbh->query($this->sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                // discovery part
+                if (!is_null($row['discover'])) {
+                                       $this->_getContactDiscoverValues(
+                                               $row,
+                                               $discover,
+                                               $discoverValues
+                                       );
+                                       $numOfContactDisc = count($discoverValues[$row['id']]);
+                                       if ($numOfContactDisc > $totalDisc) {
+                                               $totalDisc = $numOfContactDisc;
+                                       }
+                }
+                               if (!is_null($row['interest'])) {
+                                       $this->_getContactInterestValues(
+                                               $row,
+                                               $interest,
+                                               $interestValues
+                                       );
+                                       $numOfContactInt = count($interestValues[$row['id']]);
+                                       if ($numOfContactInt > $totalInt) {
+                                               $totalInt = $numOfContactInt;
+                                       }
+                               }
+                $data[$row['id']] = $row;
+            }
+                       $sdate = $this->_getDate('start_date');
+                       $edate = $this->_getDate('end_date');
+                       $interests = $this->_getFieldIds('interest');
+                       $discover = $this->_getFieldIds('discover');
+
+                       $hash = md5($sdate . $edate . $interests . $discover);
+                       $fname = $this->csvDirPath . "/$hash-" . time();
+
+                       if (!$fh = fopen($fname, 'w')) {
+                               throw new RuntimeException('Unable to create CSV file');
+                       }
+
+            $fileContents = array();
+            if (isset($data) && !empty($data)) {
+                $fileHeaders = false;
+                foreach ($data as $contactId => $row) {
+                    unset(
+                        $row['id'],
+                        $row['discover'],
+                        $row['interest']
+                    );
+
+                                       if (!$fileHeaders) {
+                                               $fileHeaders = true;
+                                               $contactDiscoverHeaders = $this->_getContactDiscoverFields(
+                                                       $totalDisc,
+                                                       $discoverValues[$contactId]
+                                               );
+                                               $contactInterestHeaders = $this->_getContactInterestFields(
+                                                       $totalInt,
+                                                       $interestValues[$contactId]
+                                               );
+
+                                               fwrite($fh, '"' . implode('","', array_keys($row)) . '"');
+                                               fwrite($fh, ',"' . implode('","', array_keys($contactDiscoverHeaders)) . '"');
+                                               fwrite($fh, ',"' . implode('","', array_keys($contactInterestHeaders)) . '"');
+                                               fwrite($fh, "\n");
+                                       }
+
+                                       fwrite($fh, '"' . implode('","', $row) . '"');
+                                       $contactDiscoverValues = $this->_getContactDiscoverFields(
+                                               $totalDisc,
+                                               $discoverValues[$contactId]
+                                       );
+                                       fwrite($fh, ',' . implode(',', $contactDiscoverValues));
+                                       $contactInterestValues = $this->_getContactInterestFields(
+                                               $totalInt,
+                                               $interestValues[$contactId]
+                                       );
+                                       fwrite($fh, ',' . implode(',', $contactInterestValues));
+                                       fwrite($fh, "\n");
+                }
+                               fclose($fh);
+                               return $fname;
+            } else {
+                return false;
+            }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+        }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Leads/libjs/visitorLeads.js b/Toolkit/Members/Leads/libjs/visitorLeads.js
new file mode 100644 (file)
index 0000000..96fcbf5
--- /dev/null
@@ -0,0 +1,75 @@
+var Event =
+{
+       calendar: 'http://app.gaslightmedia.com/assets/icons/calendar.png',
+
+       init: function()
+       {
+               if ($('#sdate1').is('select')) {
+                       Event.setupSDateCalendar();
+                       var fromCal = new Zapatec.Calendar.setup({
+                               weekNumbers             : false,
+                               ifFormat                : '%m/%d/%Y',
+                               button                  : 'startcal',
+                               onUpdate                : Event.updateFrom,
+                               showsTime               : false
+                       });
+               }
+
+               if ($('#edate1').is('select')) {
+                       Event.setupEDateCalendar();
+                       var toCal = new Zapatec.Calendar.setup({
+                               weekNumbers             : false,
+                               ifFormat                : '%m/%d/%Y',
+                               button                  : 'endcal',
+                               onUpdate                : Event.updateTo,
+                               showsTime               : false
+                       });
+               }
+       },
+
+       updateFrom: function(cal)
+       {
+               var date = cal.date;
+               var month = date.getMonth() + 1;
+               var day = date.getDate();
+               var year = date.getFullYear();
+
+               $("#sdate1 option[value='"+month+"']").attr('selected', 'selected');
+               $("#sdate2 option[value='"+day+"']").attr('selected', 'selected');
+               $("#sdate3 option[value='"+year+"']").attr('selected', 'selected');
+        Event.updateTo(cal);
+       },
+
+       updateTo: function(cal)
+       {
+               var date = cal.date;
+               var month = date.getMonth() + 1;
+               var day = date.getDate();
+               var year = date.getFullYear();
+
+               $("#edate1 option[value='"+month+"']").attr('selected', 'selected');
+               $("#edate2 option[value='"+day+"']").attr('selected', 'selected');
+               $("#edate3 option[value='"+year+"']").attr('selected', 'selected');
+       },
+
+       setupSDateCalendar: function()
+       {
+               var img = '&nbsp;<img id="startcal" height="16" width="16" ' +
+                                               'style="float:none;display:inline;vertical-align: middle" ' +
+                                               'src="' + Event.calendar + '">';
+               $('#sdate3').after(img);
+        //$("#startcal").css('display', 'inline');
+       },
+
+       setupEDateCalendar: function()
+       {
+               var img = '&nbsp;<img id="endcal" height="16" width="16" ' +
+                                               'style="float:none;display:inline;vertical-align: middle" ' +
+                                               'src="' + Event.calendar + '">';
+               $('#edate3').after(img);
+        //$("#endcal").css('display', 'inline');
+       }
+
+};
+
+$(document).ready(Event.init);
diff --git a/Toolkit/Members/Map.php b/Toolkit/Members/Map.php
new file mode 100644 (file)
index 0000000..409ce68
--- /dev/null
@@ -0,0 +1,99 @@
+<?php
+/**
+ * Map.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id$
+ * @link      <>
+ */
+
+/**
+ * Short description for class
+ *
+ * Long description (if any) ...
+ *
+ * @category  Toolkit
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      <>
+ */
+class Toolkit_Members_Map
+{
+       //      {{{     __construct()
+
+    /**
+     * Class constructor
+     * 
+     * @access public 
+     */
+       public function __construct()
+       {
+       }
+
+       //      }}}
+
+       //      {{{     getMemberXML()
+
+    /**
+     * Description of getMemberXML
+     * 
+     * @param array $members Members array
+     * 
+     * @return DOMDocument
+     * @access public 
+     */
+       public function getMemberXML(array $members)
+       {
+               $dom     = new DOMDocument("1.0");
+
+               $node    = $dom->createElement("markers");
+               $parNode = $dom->appendChild($node);
+
+               foreach ($members as $i) {
+                       $node    = $dom->createElement("marker");
+                       $newNode = $parNode->appendChild($node);
+
+                       foreach ($i as $k => $v) {
+                               $newNode->setAttribute($k, $v);
+                       }
+               }
+
+               return $dom->saveXML();
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Description for toHtml
+     * 
+     * @param string $id Description of $id
+     * @param string $w  Description of $w
+     * @param string $h  Description of $h
+     * 
+     * @return string 
+     */
+       public function toHtml($id = "map-canvas", $w = "100%", $h = "300px")
+       {
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/google-map.js';
+               $GLOBALS['bottomScripts'][]
+                       = 'http://maps.google.com/maps/api/js?sensor=false';
+
+               $format = '<div id="%s" style="width: %s;height: %s"></div>';
+
+               return sprintf($format, $id, $w, $h);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/Member.php b/Toolkit/Members/Member.php
new file mode 100644 (file)
index 0000000..3707ea0
--- /dev/null
@@ -0,0 +1,105 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles member interactions
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Member.php,v 1.2 2009/09/16 00:31:53 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Handle member record interaction
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_Member
+{
+    //  {{{ properties
+
+
+    /**
+     * Description for protected
+     * @var    unknown
+     * @access protected
+     */
+    protected $pdo;
+
+    //  /// }}}
+    //  {{{ __construct()
+    //  @codeCoverageIgnoreStart
+
+    /**
+     * Constructor
+     *
+     * @param PDO              $pdo PHP Data Object
+     * @param Config_Container $c   Application configuration
+     *
+     * @return void
+     * @access public
+     */
+    public function __construct(PDO $pdo, Config_Container $c)
+    {
+        $this->dbh = $pdo;
+        $this->config = $c;
+    }
+
+    //  @codeCoverageIgnoreEnd
+    //  }}}
+
+    //  {{{ canAddPhotos()
+
+    /**
+     * calculate if a member can add more photos to their record
+     *
+     * @param Toolkit_Members_Photos $ll Linked List of member photos
+     *
+     * @return boolean
+     * @access public
+     */
+    public function canAddPhotos(Toolkit_Members_Photos $ll)
+    {
+        //  get reference to [conf] section of config file
+        $section =& $this->config->getItem('section', 'photos');
+        $maxPhotos =& $section->getItem('directive', 'maxPhotos');
+
+               return ($ll->getListSize() < $maxPhotos->getContent());
+    }
+
+    //  }}}
+
+    //  {{{ hasUploadedPhotos()
+
+    /**
+     * Deterimines of the member has any photos uploaded to their record
+     *
+     * @param Toolkit_Members_Photos $ll   Linked List of member photos
+     * @param boolean                $fltr Filter pending when calculating
+     *
+     * @return boolean
+     * @access public
+     */
+    public function hasUploadedPhotos(
+        Toolkit_Members_Photos $ll,
+        $fltr = false
+    ) {
+        $size = $ll->getListSize($fltr);
+
+        return ($size > 0);
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/Members/MemberImport/Category.php b/Toolkit/Members/MemberImport/Category.php
new file mode 100644 (file)
index 0000000..0336b12
--- /dev/null
@@ -0,0 +1,179 @@
+<?php
+/**
+ * Category.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Toolkit
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_MemberImport_Category
+ * 
+ * Category class for members
+ *
+ * @category Toolkit
+ * @package  Toolkit
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_MemberImport_Category
+{
+    /**
+     * Description of $category_id
+     * @var integer
+     * @access protected 
+     */
+    protected $category_id;
+    
+    /**
+     * Description of $name
+     * @var string
+     * @access protected
+     */
+    protected $name;
+    
+    /**
+     * Description of $parent_id
+     * @var integer
+     * @access protected
+     */
+    protected $parent_id = 0;
+
+    /**
+     * Helps to create functions for any class variable if the variable does
+     * exists
+     *
+     * @param String $name Name of variable
+     * @param mixed  $args Argument for the varable (if set)
+     *
+     * @return Toolkit_Table
+     */
+    public function __call($name, $args)
+    {
+        if (preg_match('/^(get|set)(\w+)/', strtolower($name), $match)
+            && $attribute = $this->validateAttribute($match[2])
+        ) {
+            if ('get' == $match[1]) {
+                return $this->$attribute;
+            } else {
+                $this->$attribute = $args[0];
+            }
+        } else {
+            throw new Exception(
+                'Call to undefined method Member::' . $name
+            );
+        }
+    }
+    /**
+     * insert the object
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return Toolkit_Table
+     */
+    private function _insert(PDO $dbh)
+    {
+        $classData = get_object_vars($this);
+        unset($classData['category_id']);
+        //echo '<pre>'.print_r($classData, true).'</pre>';
+        //exit;
+        $sql = Toolkit_Common::createSQLInsert(
+            'category',
+            array_keys($classData)
+        );
+        $sql .= " RETURNING category_id";
+        $stmt = Toolkit_Common::prepareQuery(
+            $dbh,
+            'category',
+            $sql,
+            $classData
+        );
+        $stmt->execute();
+        $this->setCategoryId($stmt->fetchColumn());
+    }
+    /**
+     * given a category name return id create category if needed
+     *
+     * @param PDO    $dbh  Database connection
+     * @param String $name Category Name
+     *
+     * @return Object
+     */
+    function fetchByName(PDO $dbh, $name)
+    {
+        $sql = "
+        SELECT " . implode(',', $this->getClassVars())."
+          FROM category
+         WHERE name = :name";
+        $stmt = $dbh->prepare($sql);
+        $stmt->bindParam(":name", $name, PDO::PARAM_STR);
+        $stmt->execute();
+        $row = $stmt->fetch(PDO::FETCH_ASSOC);
+        if ($row) {
+            $category = new Toolkit_Members_MemberImport_Category();
+            $category->setCategoryId($row['category_id']);
+            $category->setName($row['name']);
+            $category->setParent_id($row['parent_id']);
+            return $category;
+        } else {
+            return false;
+        }
+    }
+    /**
+     * get all clas properties as an array (just names)
+     *
+     * @return Array
+     */
+    public function getClassVars()
+    {
+        return array_keys(get_class_vars(get_class($this)));
+    }
+    /**
+     * set category id
+     *
+     * @param Int $id Category id
+     *
+     * @return void
+     */
+    public function setCategoryId($id)
+    {
+        if (!$this->category_id) {
+            $this->category_id = $id;
+        }
+    }
+    /**
+     * Checks the id of the object if it is set then calls update othervise
+     * calls insert function
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return viod
+     */
+    public function save(PDO $dbh)
+    {
+        if ($this->category_id) {
+            $this->_update($dbh);
+        } else {
+            $this->_insert($dbh);
+        }
+    }
+    /**
+     * Validates the property
+     *
+     * @param String $name property name
+     *
+     * @return String
+     */
+    protected function validateAttribute($name)
+    {
+        if (property_exists(get_class($this), $name)) {
+            return strtolower($name);
+        }
+    }
+}
diff --git a/Toolkit/Members/MemberImport/City.php b/Toolkit/Members/MemberImport/City.php
new file mode 100644 (file)
index 0000000..d48d8b2
--- /dev/null
@@ -0,0 +1,135 @@
+<?php
+/**
+ * City.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_MemberImport_City
+ *
+ * member city table class
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_MemberImport_City
+{
+    /**
+     * Description of $city_id
+     * @var integer 
+     * @access protected
+     */
+    protected $city_id;
+    
+    /**
+     * Description of $city_name
+     * @var string
+     * @access protected
+     */
+    protected $city_name;
+    
+    /**
+     * Description of $state_id
+     * @var integer
+     * @access protected
+     */
+    protected $state_id;
+
+    /**
+     * Helps to create functions for any class variable if the variable does
+     * exists
+     *
+     * @param String $name Name of variable
+     * @param mixed  $args Argument for the varable (if set)
+     *
+     * @return Toolkit_Table
+     */
+    public function __call($name, $args)
+    {
+        if (preg_match('/^(get|set)(\w+)/', strtolower($name), $match)
+            && $attribute = $this->validateAttribute($match[2])
+        ) {
+            if ('get' == $match[1]) {
+                return $this->$attribute;
+            } else {
+                $this->$attribute = $args[0];
+            }
+        } else {
+            throw new Exception(
+                'Call to undefined method Member::' . $name
+            );
+        }
+    }
+    /**
+     * given a city name search for and get id create city if needed
+     *
+     * @param PDO    $dbh  Database connection
+     * @param String $name City Name
+     *
+     * @return Object
+     */
+    public function fetchByName(PDO $dbh, $name)
+    {
+        $sql = "
+        SELECT city_id,city_name,state_id
+          FROM city
+         WHERE lower(city_name) = :city_name";
+        $stmt = $dbh->prepare($sql);
+        $stmt->setFetchMode(
+            PDO::FETCH_CLASS, 
+            'Toolkit_Members_MemberImport_City'
+        );
+        $stmt->bindParam(":city_name", strtolower($name));
+        $stmt->execute();
+        return $stmt->fetch(PDO::FETCH_CLASS);
+    }
+    /**
+     * Checks the id of the object if it is set then calls update othervise
+     * calls insert function
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return viod
+     */
+    public function save(PDO $dbh)
+    {
+        $classData = get_object_vars($this);
+        unset($classData['city_id']);
+        $sql = Toolkit_Common::createSQLInsert(
+            'city',
+            array_keys($classData)
+        );
+        $sql .= " RETURNING city_id";
+        $stmt = Toolkit_Common::prepareQuery(
+            $dbh,
+            'city',
+            $sql,
+            $classData
+        );
+        $stmt->execute();
+        $this->setCity_id($stmt->fetchColumn());
+    }
+    /**
+     * Validates the property
+     *
+     * @param String $name property name
+     *
+     * @return String
+     */
+    protected function validateAttribute($name)
+    {
+        if (property_exists(get_class($this), $name)) {
+            return strtolower($name);
+        }
+    }
+}
diff --git a/Toolkit/Members/MemberImport/FileForm.php b/Toolkit/Members/MemberImport/FileForm.php
new file mode 100644 (file)
index 0000000..73fcc0b
--- /dev/null
@@ -0,0 +1,149 @@
+<?php
+/**
+ * FileForm.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit_Members
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_MemberImport_FileForm
+ *
+ * Build the form for uploading the file
+ *
+ * @category Toolkit_Members
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_MemberImport_FileForm 
+    extends Toolkit_FormBuilder implements Toolkit_Form
+{
+    /**
+     * Description of $uploadDir
+     * @var string
+     * @access protected
+     */
+    protected $uploadDir = './upload/';
+    
+    /**
+     * Description of $successMessage
+     * @var string
+     * @access protected
+     */
+    protected $successMsg = '<div>file uploaded now processing</div>';
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e = array();
+
+        // All Elements are created here.
+        // This includes group element definitions.
+        $e[] = array(
+            'type'    => 'file',
+            'req'     =>  true,
+            'name'    => 'file_upload',
+            'display' => 'File Upload'
+        );
+        $e[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit_rmv',
+            'display' => 'Submit Form'
+        );
+
+        $this->setupElements($e);
+    }
+
+    /**
+     * Helper function, configures the entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+    }
+
+    /**
+     * Form rule definitions
+     *
+     * Adds validation rules for the given fields
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules()
+    {
+        $r = array();
+        $this->setupRules($r);
+    }
+
+    /**
+     * Process the form
+     *
+     * @param Array $values Array of values from the form (filtered)
+     *
+     * @return Boolean
+     */
+    function processForm($values)
+    {
+        $uploadedFile = move_uploaded_file(
+            $values['file_upload']['tmp_name'],
+            $this->uploadDir . 'members.csv'
+        );
+        if ($uploadedFile) {
+            $import = new Toolkit_Members_MemberImport_Import(
+                Toolkit_Database::getInstance()
+            );
+            $data = $import->readFile($this->uploadDir . 'members.csv');
+            $import->createTmpTable();
+            $import->importFile();
+            return true;
+        } else {
+            echo 'failed';
+        }
+    }
+
+    /**
+     * Handles how to display the current step the user is at in the form
+     *
+     * destroying and resetting the captcha value dis-allows someone from
+     * re-sending a form on a previous captcha.
+     *
+     * @return string form HTML state
+     * @access public
+     */
+    public function toHtml()
+    {
+        $this->fileImported = false;
+        if ($this->validate()) {
+            $this->cleanForm();
+
+            if ($this->process(array(&$this, 'processForm'), $this->mergeFiles)) {
+                $this->freeze();
+                $output = $this->successMsg;
+                $this->fileImported = true;
+            }
+        } elseif ($this->isSubmitted()) {
+            $output  = $this->errorMsg;
+            $output .= parent::toHTML();
+        } else {
+            $output = parent::toHTML();
+        }
+        return $output;
+    }
+}
diff --git a/Toolkit/Members/MemberImport/Import.php b/Toolkit/Members/MemberImport/Import.php
new file mode 100644 (file)
index 0000000..788ebd9
--- /dev/null
@@ -0,0 +1,181 @@
+<?php
+/**
+ * Import.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit_Members
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_MemberImport_Import
+ *
+ * handles the import of the members from a temp table to the actual members
+ * table
+ *
+ * @category Toolkit_Members
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_MemberImport_Import
+{
+    
+    /**
+     * Description for $fieldNames
+     * @var array
+     * @access public
+     */
+    public $fieldNames = array();
+    
+    /**
+     * Description for $_dropEnd
+     * @var boolean
+     * @access private
+     */
+    private $_dropEnd = false;
+    
+    /**
+     * Description for $_headCount
+     * @var integer
+     * @access private
+     */
+    private $_headCount = 0;
+    
+    /**
+     * Description for $tmpTableName
+     * @var string
+     * @access protected
+     */
+    protected $tmpTableName = 'tmp_members';
+    
+    /**
+     * Description for $headerFile
+     * @var string
+     * @access protected
+     */
+    protected $headerFile = 'fileHeaders.txt';
+    
+    /**
+     * Description for $dbh
+     * @var PDO
+     * @access protected
+     */
+    protected $dbh;
+    
+    /**
+     * Description for $data
+     * @var array
+     * @access protected
+     */
+    protected $data = array();
+    
+    /**
+     * constructor of class Sets the pdo to protected $dbh variable
+     *
+     * @param PDO $pdo Database connection
+     *
+     * @return void
+     * @access public
+     */
+    public function __construct(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+    /**
+     * readFile
+     * 
+     * Read in the file uploaded and return an array of values from each row 
+     *
+     * @param String $file Name of the file uploaded
+     *
+     * @throws Exception If file is not found
+     * @return Array
+     * @access public
+     */
+    public function readFile($file)
+    {
+        if (!is_file($file)) {
+            throw new Exception("File $file not found!");
+        }
+        if (($handle = fopen($file, 'r')) !== false) {
+            while (($line = fgetcsv($handle, 1000, ",")) !== false) {
+                $this->data[] = $line;
+            }
+        }
+        return $this->data;
+    }
+    /**
+     * Create a tmp_member table
+     *
+     * @return void
+     * @access public
+     */
+    public function createTmpTable()
+    {
+        $this->dbh->query("DROP TABLE IF EXISTS {$this->tmpTableName}");
+        // get the first row of the csv file
+        $headers = array_values($this->data[0]);
+        $headers = array_filter($headers);
+        $this->fieldNames = array_map(array($this, "_cleanFieldName"), $headers);
+        $this->_headCount = count($headers);
+        file_put_contents($this->headerFile, serialize($this->fieldNames));
+        $sql = "
+        CREATE TABLE {$this->tmpTableName}(
+        ".implode(" TEXT,", $this->fieldNames)." TEXT
+        )";
+        $this->dbh->query($sql);
+    }
+    /**
+     * Clean the field name for creation of a tmp_member table with the 
+     * first header row as the field names
+     *
+     * @param String $name Name of the field
+     *
+     * @return String
+     * @access private
+     */
+    private function _cleanFieldName($name)
+    {
+        $name = str_replace("-", "_", $name);
+        return strtolower(str_replace(" ", "_", $name));
+    }
+    /**
+     * importFile
+     *
+     * Takes the file uploaded and imports the rows into a tmp_member table
+     *
+     * @return void
+     * @access public
+     */
+    public function importFile()
+    {
+        $sql = Toolkit_Common::createSQLInsert(
+            $this->tmpTableName,
+            $this->fieldNames
+        );
+        try {
+            foreach ($this->data as $key => $row) {
+                // skip first row
+                if ($key == 0) {
+                    continue;
+                }
+                // only get part of the row Length of headers
+                $row = array_slice($row, 0, $this->_headCount);
+                $values = array_combine($this->fieldNames, $row);
+                Toolkit_Common::processQuery(
+                    $this->dbh,
+                    $this->tmpTableName,
+                    $sql,
+                    $values
+                );
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/Members/MemberImport/ImportForm.php b/Toolkit/Members/MemberImport/ImportForm.php
new file mode 100644 (file)
index 0000000..1d63d02
--- /dev/null
@@ -0,0 +1,234 @@
+<?php
+/**
+ * ImportForm.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit
+ * @package  Members_MemberImport
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_MemberImport_ImportForm
+ *
+ * Build the form for defining whihc fields can be imported from the file
+ * and to which field they get imported to
+ *
+ * @category Toolkit
+ * @package  Members_MemberImport
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_MemberImport_ImportForm 
+    extends Toolkit_FormBuilder
+    implements Toolkit_Form
+{
+    
+    /**
+     * Description for $tmpTableName
+     * @var string
+     * @access protected
+     */
+    protected $tmpTableName = 'tmp_members';
+    
+    /**
+     * Description for $headerFile
+     * @var string
+     * @access protected
+     */
+    protected $headerFile = 'fileHeaders.txt';
+    
+    /**
+     * Description for $successMsg
+     * @var string
+     * @access protected
+     */
+    protected $successMsg = '<div>Inserting new members</div>';
+
+    /**
+     * _cleanFieldName
+     *
+     * Cleans the fieldname takes out the spaces and puts in underscore
+     *
+     * @param String $name Field name to be cleaned
+     *
+     * @return String
+     */
+    private function _cleanFieldName($name)
+    {
+        return ucwords(str_replace("_", " ", $name));
+    }
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e = array();
+        $member = new Toolkit_Members_MemberImport_Member();
+        $flds = $member->getClassVars();
+        $fieldOption = array(
+            '' => 'Ignore',
+            'member_category' => 'Member Category'
+        );
+        foreach ($flds as $fieldName) {
+            if ($fieldName != 'member_id') {
+                $fieldOption[$fieldName] = $this->_cleanFieldName($fieldName);
+            }
+        }
+
+        //     All Elements are created here.  This includes group element definitions.
+        $headers = unserialize(file_get_contents($this->headerFile));
+        foreach ($headers as $field) {
+            $title = ucwords(str_replace("_", " ", $field));
+            $e[] = array(
+                'type'    => 'select',
+                'req'     =>  false,
+                'name'    => $field,
+                'display' => $title,
+                'opts'    => $fieldOption
+            );
+        }
+        $e[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit_rmv',
+            'display' => 'Submit Form'
+        );
+
+        $this->setupElements($e);
+    }
+
+    /**
+     * Helper function, configures the entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureRules();
+    }
+
+    /**
+     * Form rule definitions
+     *
+     * Adds validation rules for the given fields
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules()
+    {
+        $r = array();
+        $this->setupRules($r);
+    }
+
+    /**
+     * Process the form and import members according to their placement
+     *
+     * @param Array $values Array of values from the form (filtered)
+     *
+     * @return Boolean
+     */
+    function processForm($values)
+    {
+        unset($values['submit_rmv']);
+        $memberCategoryFields = array();
+        foreach ($values as $fromField => $toField) {
+            if ($toField && $toField != 'member_categories') {
+                $fromFieldArray[] = $fromField;
+            } else if ($toField == 'member_categories') {
+                $fromFieldArray[] = $fromField;
+                $memberCategoryFields[] = $fromField;
+            }
+        }
+        $ignore = array(
+            'city',
+            'state',
+            'mailing_city',
+            'mailing_state',
+            'member_category'
+        );
+        $sql = "
+        SELECT ".implode(',', $fromFieldArray)."
+          FROM {$this->tmpTableName}";
+        $stmt = $this->dbh->query($sql);
+        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+            $member = new Toolkit_Members_MemberImport_Member();
+            $member_categories = array();
+            foreach ($row as $prop => $val) {
+                if (in_array($prop, $memberCategoryFields)) {
+                    $member_categories[] = $val;
+                    continue;
+                }
+                // we need to get the state done first before the city 
+                if (!in_array(strtolower($prop), $ignore)) {
+                    if ($val != '') {
+                        $propertyName = $values[$prop];
+                        $setprop = "set$propertyName";
+                        $member->$setprop($val);
+                    }
+                } else {
+                    if (strtolower($prop) == 'city') {
+                        $city = $val;
+                    }
+                    if (strtolower($prop) == 'state') {
+                        $state = $val;
+                    }
+                    if (strtolower($prop) == 'mailing_city') {
+                        $mailing_city = $val;
+                    }
+                    if (strtolower($prop) == 'mailing_state') {
+                        $mailing_state = $val;
+                    }
+                }
+            }
+            $member->setState($this->dbh, $state);
+            $member->setCity($this->dbh, $city);
+            $member->setMailingState($this->dbh, $mailing_state);
+            $member->setMailingCity($this->dbh, $mailing_city);
+            if (!empty($member_categories)) {
+                $member->setMember_categories($member_categories);
+            }
+            $member->save($this->dbh);
+            $this->members[] = $member;
+        }
+        echo '<pre>'.print_r($this->members, true).'</pre>';
+        return true;
+    }
+
+    /**
+     * Handles how to display the current step the user is at in the form
+     *
+     * destroying and resetting the captcha value dis-allows someone from
+     * re-sending a form on a previous captcha.
+     *
+     * @return string form HTML state
+     * @access public
+     */
+    public function toHtml()
+    {
+        if ($this->validate()) {
+            $this->cleanForm();
+
+            if ($this->process(array(&$this, 'processForm'), $this->mergeFiles)) {
+                $this->freeze();
+                $output = $this->successMsg;
+            }
+        } elseif ($this->isSubmitted()) {
+            $output  = $this->errorMsg;
+            $output .= parent::toHTML();
+        } else {
+            $output = parent::toHTML();
+        }
+        return $output;
+    }
+}
diff --git a/Toolkit/Members/MemberImport/Member.php b/Toolkit/Members/MemberImport/Member.php
new file mode 100644 (file)
index 0000000..54d4516
--- /dev/null
@@ -0,0 +1,667 @@
+<?php
+/**
+ * Member.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit_Members
+ * @package  Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_MemberImport_Member
+ *
+ * Member class for importing member
+ *
+ * @category Toolkit_Members
+ * @package  Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_MemberImport_Member
+{
+    
+    /**
+     * Description for $active
+     * @var boolean
+     * @access protected
+     */
+    protected $active = true;
+    
+    /**
+     * Description for $join_date
+     * @var date
+     * @access protected
+     */
+    protected $join_date;
+    
+    /**
+     * Description for $member_id
+     * @var integer
+     * @access protected
+     */
+    protected $member_id;
+    
+    /**
+     * Description for $member_name
+     * @var string
+     * @access protected
+     */
+    protected $member_name;
+    
+    /**
+     * Description for $street
+     * @var string
+     * @access protected
+     */
+    protected $street;
+    
+    /**
+     * Description for $country
+     * @var string
+     * @access protected
+     */
+    protected $country;
+    
+    /**
+     * Description for $phone_area
+     * @var string
+     * @access protected
+     */
+    protected $phone_area; // not real field
+    
+    /**
+     * Description for $phone
+     * @var string
+     * @access protected
+     */
+    protected $phone;
+    
+    /**
+     * Description for $fax_area
+     * @var string
+     * @access protected
+     */
+    protected $fax_area;    // not real field
+    
+    /**
+     * Description for $fax
+     * @var string
+     * @access protected
+     */
+    protected $fax;
+    
+    /**
+     * Description for $process_email
+     * @var string
+     * @access protected
+     */
+    protected $process_email;
+    
+    /**
+     * Description for $url
+     * @var string
+     * @access protected
+     */
+    protected $url;
+    
+    /**
+     * Description for $city
+     * @var string
+     * @access protected
+     */
+    protected $city;
+    
+    /**
+     * Description for $city_id
+     * @var integer
+     * @access protected
+     */
+    protected $city_id;
+    
+    /**
+     * Description for $state
+     * @var string
+     * @access protected
+     */
+    protected $state;
+    
+    /**
+     * Description for $state_id
+     * @var integer
+     * @access protected
+     */
+    protected $state_id;
+    
+    /**
+     * Description for $description
+     * @var integer
+     * @access protected
+     */
+    protected $description;
+    
+    /**
+     * Description for $zip
+     * @var string
+     * @access protected
+     */
+    protected $zip;
+    
+    /**
+     * Description for $toll_free_area
+     * @var string
+     * @access protected
+     */
+    protected $toll_free_area; // not real field
+    
+    /**
+     * Description for $toll_free
+     * @var string
+     * @access protected
+     */
+    protected $toll_free;
+    
+    /**
+     * Description for $member_contact_email
+     * @var string
+     * @access protected
+     */
+    protected $member_contact_email;
+    
+    /**
+     * Description for $mailing_address
+     * @var string
+     * @access protected
+     */
+    protected $mailing_address;
+    
+    /**
+     * Description for $primary_contact
+     * @var string
+     * @access protected
+     */
+    protected $primary_contact;
+    
+    /**
+     * Description for $primary_contact_fname
+     * @var string
+     * @access protected
+     */
+    protected $primary_contact_fname;
+    
+    /**
+     * Description for $primary_contact_lname
+     * @var string
+     * @access protected
+     */
+    protected $primary_contact_lname;
+    
+    /**
+     * Description for $mailing_state
+     * @var string
+     * @access protected
+     */
+    protected $mailing_state;
+    
+    /**
+     * Description for $mailing_state_id
+     * @var integer
+     * @access protected
+     */
+    protected $mailing_state_id;
+    
+    /**
+     * Description for $mailing_city
+     * @var string
+     * @access protected
+     */
+    protected $mailing_city;
+    
+    /**
+     * Description for $mailing_city_id
+     * @var integer
+     * @access protected
+     */
+    protected $mailing_city_id;
+    
+    /**
+     * Description for $mailing_zip
+     * @var string
+     * @access protected
+     */
+    protected $mailing_zip;
+    
+    /**
+     * Description for $lat
+     * @var double
+     * @access protected
+     */
+    protected $lat;
+    
+    /**
+     * Description for $lon
+     * @var double
+     * @access protected
+     */
+    protected $lon;
+    
+    /**
+     * Description for $member_categories
+     * @var array
+     * @access protected
+     */
+    protected $member_categories = array(); // not real field
+
+    /**
+     * created setters and getters for the class properties
+     * checks for existance of the property before running getter/setter
+     *
+     * @param String $name Function name
+     * @param Mixed  $args if set the arg to set
+     *
+     * @return mixed
+     * @throws Exception
+     * @access public
+     */
+    public function __call($name, $args)
+    {
+        if (preg_match('/^(get|set)(\w+)/', strtolower($name), $match)
+            && $attribute = $this->validateAttribute($match[2])
+        ) {
+            if ('get' == $match[1]) {
+                return $this->$attribute;
+            } else {
+                $this->$attribute = $args[0];
+            }
+        } else {
+            throw new Exception(
+                'Call to undefined method Member::' . $name
+            );
+        }
+    }
+    /**
+     * _insert
+     *
+     * create the record in database
+     *
+     * @param PDO $dbh Databese connection
+     *
+     * @return void
+     * @access public
+     */
+    private function _insert(PDO $dbh)
+    {
+        $classData = get_object_vars($this);
+        unset(
+            $classData['member_id'],
+            $classData['member_categories'],
+            $classData['phone_area'],
+            $classData['fax_area'],
+            $classData['toll_free_area'],
+            $classData['mailing_state']
+        );
+        $sql = Toolkit_Common::createSQLInsert(
+            'member',
+            array_keys($classData)
+        );
+        $sql .= " RETURNING member_id";
+        $stmt = Toolkit_Common::prepareQuery(
+            $dbh,
+            'member',
+            $sql,
+            $classData
+        );
+        $stmt->execute();
+        $this->setMemberId($stmt->fetchColumn());
+    }
+    /**
+     * getCLassVars
+     *
+     * get all class properties
+     *
+     * @return Array Keys of the class properties
+     * @access public
+     */
+    public function getClassVars()
+    {
+        return array_keys(get_class_vars(get_class($this)));
+    }
+    /**
+     * check the date given to see if its a valid date first before setting it
+     *
+     * @param String $date date
+     *
+     * @return void
+     * @access public
+     */
+    public function setJoinDate($date)
+    {
+        if (strtotime($date)) {
+            $this->join_date = $date;
+        }
+    }
+    /**
+     * check the number given to make sure it is numeric
+     *
+     * @param String $lat latitude
+     *
+     * @return void
+     * @access public
+     */
+    public function setLat($lat)
+    {
+        if (is_numeric($lat)) {
+            $this->lat = $lat;
+        }
+    }
+    /**
+     * check the number given to make sure it is numeric
+     *
+     * @param String $lon longitude
+     *
+     * @return void
+     * @access public
+     */
+    public function setLon($lon)
+    {
+        if (is_numeric($lon)) {
+            $this->lon = $lon;
+        }
+    }
+    /**
+     * check the number given to make sure it is numeric
+     *
+     * @param Int $id member id must be numeric
+     *
+     * @throws Exception if not numeric
+     * @return void
+     * @access public
+     */
+    public function setMemberId($id)
+    {
+        if (!is_numeric($id)) {
+            throw new Exception('Id must be numeric');
+        }
+        if (!$this->member_id) {
+            $this->member_id = $id;
+        }
+    }
+    /**
+     * create the city if not found then set member property
+     *
+     * @param PDO    $dbh      Database connection
+     * @param String $cityName City Name
+     *
+     * @return Int
+     * @access public
+     */
+    public function setCity(PDO $dbh, $cityName)
+    {
+        if (!$cityName) {
+            return false;
+        }
+        // update the city name so each first letter is upper case
+        $cityName = ucwords(strtolower($cityName));
+        $city = new Toolkit_Members_MemberImport_City();
+        $newCity = $city->fetchByName($dbh, $cityName);
+        if ($newCity) {
+            $cityId = $newCity->getCity_id();
+            $this->setCity_id($cityId);
+        } else {
+            // need to create new city
+            $city->setCity_name($cityName);
+            $city->setState_id($this->getState_id());
+            $city->save($dbh);
+            $this->setCity_id($city->getCity_id());
+        }
+    }
+    /**
+     * create the city if not found then set member property
+     *
+     * @param PDO    $dbh      Database connection
+     * @param String $cityName City Name
+     *
+     * @return boolean
+     * @access public
+     */
+    public function setMailingCity(PDO $dbh, $cityName)
+    {
+        if (!$cityName) {
+            return false;
+        }
+        $city = new Toolkit_Members_MemberImport_City();
+        $newCity = $city->fetchByName($dbh, $cityName);
+        if ($newCity) {
+            $cityId = $newCity->getCity_id();
+            $this->setMailing_city_id($cityId);
+        } else {
+            // need to create new city
+            $city->setCity_name($cityName);
+            $city->setState_id($this->getMailing_state_id());
+            $city->save($dbh);
+            $this->setMailing_city_id($city->getCity_id);
+        }
+    }
+    /**
+     * create the state if not found then set member property
+     *
+     * @param PDO    $dbh      Database connection
+     * @param String $stateAbb State Abbreviation
+     *
+     * @return boolean
+     * @access public
+     */
+    public function setMailingState(PDO $dbh, $stateAbb)
+    {
+        if (!$stateAbb) {
+            return false;
+        }
+        $state = new Toolkit_Members_MemberImport_State();
+        $newState = $state->fetchByAbb($dbh, $stateAbb);
+        if (is_object($newState)) {
+            if ($stateId = $newState->getState_id()) {
+                $this->setMailing_state_id($stateId);
+            } else {
+                // ?
+            }
+        } else {
+            var_dump($stateId);
+            var_dump($stateAbb);
+        }
+    }
+    /**
+     * also set the member_contact_email at same time
+     *
+     * @param String $email Email address
+     *
+     * @return void
+     * @access public
+     */
+    public function setProcessEmail($email)
+    {
+        if ($email != '') {
+            $this->process_email        = $email;
+            $this->member_contact_email = $email;
+        }
+    }
+    /**
+     * phone field may come in two seperate fields from the file
+     * here it's appending the fields area and
+     *
+     * @param <type> $phone_area phone area code
+     *
+     * @return void
+     * @access public
+     */
+    public function setPhoneArea($phone_area)
+    {
+        $this->phone = $phone_area . ' ';
+    }
+    /**
+     * set phone
+     *
+     * @param <type> $phone phone number
+     *
+     * @return void
+     * @access public
+     */
+    public function setPhone($phone)
+    {
+        $this->phone .= $phone;
+        $this->phone = trim($this->phone);
+    }
+    /**
+     * set fax
+     *
+     * @param String $fax_area fax area code part
+     *
+     * @return void
+     * @access public
+     */
+    public function setFaxArea($fax_area)
+    {
+        $this->fax = $fax_area. ' ';
+    }
+    /**
+     * set fax number
+     *
+     * @param String $fax fax number part
+     *
+     * @return void
+     * @access public
+     */
+    public function setFax($fax)
+    {
+        $this->fax .= $fax;
+        $this->fax = trim($this->fax);
+    }
+    /**
+     * set toll free area code
+     *
+     * @param String $toll_free_area toll free area code
+     *
+     * @return void
+     * @access public
+     */
+    public function setTollFreeArea($toll_free_area)
+    {
+        $this->toll_free = $toll_free_area . ' ';
+    }
+    /**
+     * set toll free number
+     *
+     * @param String $toll_free Toll free number
+     *
+     * @return void
+     * @access public
+     */
+    public function setTollFree($toll_free)
+    {
+        $this->toll_free .= $toll_free;
+        $this->toll_free = trim($this->toll_free);
+    }
+    /**
+     * create the state if not found then set member property
+     *
+     * @param PDO    $dbh      Database connection
+     * @param String $stateAbb State Abbreviation
+     *
+     * @return boolean
+     * @access public
+     */
+    public function setState(PDO $dbh, $stateAbb)
+    {
+        if (!$stateAbb) {
+            return false;
+        }
+        $state = new Toolkit_Members_MemberImport_State();
+        $state = new Toolkit_Members_MemberImport_State();
+        $newState = $state->fetchByAbb($dbh, $stateAbb);
+        if ($stateId = $newState->getState_id()) {
+            $this->setState_id($stateId);
+        } else {
+            // ?
+        }
+    }
+    /**
+     * save
+     *
+     * check to see if the id is set if it is then update else call insert
+     * also set the member categories
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return void
+     * @access public
+     */
+    public function save(PDO $dbh)
+    {
+        if ($this->member_id) {
+            $this->_update($dbh);
+        } else {
+            $this->_insert($dbh);
+        }
+        // now we can add categories
+        if (!empty($this->member_categories)) {
+            $addMemberCatSql = "
+            INSERT INTO member_category
+            (member_id, category_id)
+            VALUES
+            (:member_id, :category_id)";
+            $addMemberCat = $dbh->prepare($addMemberCatSql);
+            foreach ($this->member_categories as $catName) {
+                $category = new Toolkit_Members_MemberImport_Category();
+                if ($catName
+                    && $oldCategory = $category->fetchByName($dbh, $catName)
+                ) {
+                    // can now add this category to this member
+                    $addMemberCat->bindParam(
+                        ":member_id",
+                        $this->getMember_id(),
+                        PDO::PARAM_INT
+                    );
+                    $addMemberCat->bindParam(
+                        ":category_id",
+                        $oldCategory->getCategory_id(),
+                        PDO::PARAM_INT
+                    );
+                    $addMemberCat->execute();
+                } else if ($catName) {
+                    // not found must add 
+                    $category->setName($catName);
+                    $category->save($dbh);
+                    $addMemberCat->bindParam(
+                        ":member_id",
+                        $this->getMember_id(),
+                        PDO::PARAM_INT
+                    );
+                    $addMemberCat->bindParam(
+                        ":category_id",
+                        $category->getCategory_id(),
+                        PDO::PARAM_INT
+                    );
+                    $addMemberCat->execute();
+                }
+            }
+        }
+    }
+    /**
+     * validateAttribute
+     *
+     * checks to see if the properties exists
+     *
+     * @param String $name property name
+     * 
+     * @return String
+     * @access public
+     */
+    protected function validateAttribute($name)
+    {
+        if (property_exists(get_class($this), $name)) {
+            return strtolower($name);
+        }
+    }
+}
diff --git a/Toolkit/Members/MemberImport/State.php b/Toolkit/Members/MemberImport/State.php
new file mode 100644 (file)
index 0000000..ac1bf38
--- /dev/null
@@ -0,0 +1,106 @@
+<?php
+/**
+ * State.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Toolkit
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_Members_MemberImport_State
+ * 
+ * member state class
+ *
+ * @category Toolkit
+ * @package  Toolkit
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_Members_MemberImport_State
+{
+    /**
+     * Description of $state_abb
+     * @var string 
+     * @access protected
+     */
+    protected $state_abb;
+    
+    /**
+     * Description of $city_name
+     * @var string
+     * @access protected
+     */
+    protected $state_name;
+    
+    /**
+     * Description of $state_id
+     * @var integer
+     * @access protected
+     */
+    protected $state_id;
+
+    /**
+     * Helps to create functions for any class variable if the variable does
+     * exists
+     *
+     * @param String $name Name of variable
+     * @param mixed  $args Argument for the varable (if set)
+     *
+     * @return Toolkit_Table
+     */
+    public function __call($name, $args)
+    {
+        if (preg_match('/^(get|set)(\w+)/', strtolower($name), $match)
+            && $attribute = $this->validateAttribute($match[2])
+        ) {
+            if ('get' == $match[1]) {
+                return $this->$attribute;
+            } else {
+                $this->$attribute = $args[0];
+            }
+        } else {
+            throw new Exception(
+                'Call to undefined method Member::' . $name
+            );
+        }
+    }
+    /**
+     * given a state abbreviation search for the state id
+     *
+     * @param PDO    $dbh Database connection
+     * @param String $abb State Abbreviation
+     *
+     * @return Object
+     */
+    public function fetchByAbb(PDO $dbh, $abb)
+    {
+        $sql = "
+        SELECT state_id,state_name,state_abb
+          FROM state
+         WHERE state_abb = :abb";
+        $stmt = $dbh->prepare($sql);
+        $stmt->setFetchMode(PDO::FETCH_CLASS, 'Toolkit_Members_MemberImport_State');
+        $stmt->bindParam(":abb", $abb);
+        $stmt->execute();
+        return $stmt->fetch(PDO::FETCH_CLASS);
+    }
+    /**
+     * Validates the property
+     *
+     * @param String $name property name
+     *
+     * @return String
+     */
+    protected function validateAttribute($name)
+    {
+        if (property_exists(get_class($this), $name)) {
+            return strtolower($name);
+        }
+    }
+}
diff --git a/Toolkit/Members/MemberImport/index.php b/Toolkit/Members/MemberImport/index.php
new file mode 100644 (file)
index 0000000..2930626
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+/**
+ * index.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit_Members
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+require_once '../../../setup.phtml';
+if (!isset($_REQUEST['_qf__import-members']) && (!$_GET['skip'] == 't')) {
+    $form = new Toolkit_Members_MemberImport_FileForm(
+        'import-file',
+        'post',
+        'index.php',
+        null,
+        null,
+        true
+    );
+    $form->configureForm();
+    if (is_file('./upload/members.csv')) {
+        echo '<a href="index.php?skip=t">Use Current Uploaded File</a><br />';
+    }
+    echo $form->toHtml();
+}
+if (isset($_REQUEST['_qf__import-file'])
+    || isset($_REQUEST['_qf__import-members'])
+    || $_GET['skip'] == 't'
+) {
+    // next page
+    $form2 = new Toolkit_Members_MemberImport_ImportForm(
+        'import-members',
+        'post',
+        'index.php',
+        null,
+        null,
+        true
+    );
+    $form2->configureForm();
+    echo $form2->toHtml();
+}
diff --git a/Toolkit/Members/MembersOnly/BreadCrumbs.php b/Toolkit/Members/MembersOnly/BreadCrumbs.php
new file mode 100644 (file)
index 0000000..b7c55c9
--- /dev/null
@@ -0,0 +1,65 @@
+<?php
+/**
+ * BreadCrumbs.php
+ * 
+ * PHP Version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ *  
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_BreadCrumbs
+ * 
+ * Description of Toolkit_Members_MembersOnly_BreadCrumbs
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_BreadCrumbs
+       extends Toolkit_Template_BreadCrumbs
+{
+    /**
+     * Description of getBreadCrumbsArray()
+     * 
+     * @param int $id ID
+     * 
+     * @return array 
+     * @access protected
+     */
+       protected function getBreadCrumbsArray($id)
+       {
+               $stack = array();
+               $page  = $this->pageGateway->find($id);
+               array_unshift($stack, $page['navigation_name']);
+               $parent = $page['parent'];
+
+               while ($parent != 0) {
+                       $page = $this->pageGateway->find($parent);
+                       $seoUrl = Toolkit_Template_Page::getSeoUrl(
+                               $this->pageGateway,
+                               $parent
+                       );
+                       $anchor = '<a href="'.$seoUrl.'">'.$page['navigation_name'].'</a>';
+                       array_unshift($stack, $anchor);
+                       $parent = $page['parent'];
+               }
+
+               $anchor = '<a href="' . BASE_URL . 'index.php">Home</a>';
+               array_unshift($stack, $anchor);
+
+               return $stack;
+       }
+}
+?>
diff --git a/Toolkit/Members/MembersOnly/CommonEventsController.php b/Toolkit/Members/MembersOnly/CommonEventsController.php
new file mode 100644 (file)
index 0000000..7bb7217
--- /dev/null
@@ -0,0 +1,193 @@
+<?php
+/**
+ * EventsController.php
+ *
+ * PHP Version 5.2
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+if (!defined('COMMON_APP_BASE')) {
+    define('COMMON_APP_BASE', '/var/www/server/CommonApps/');
+}
+require_once COMMON_APP_BASE . 'EventCalendar/V0/models/EventMapper.php';
+/**
+ * Toolkit_Members_MembersOnly_EventsController
+ *
+ * Description of Toolkit_Members_MembersOnly_EventsController
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+
+class Toolkit_Members_MembersOnly_CommonEventsController
+       extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+       //      {{{     _creatPage()
+
+    /**
+     * Description of _createPage()
+     *
+     * @param string $eventContent Description of $eventcontent
+     *
+     * @return void
+     * @access private
+     */
+       private function _createPage($eventContent)
+       {
+               $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+                       new Toolkit_Toolbox_PageGatewayPublishFactory(
+                               $this->registry->dbh
+                       )
+               );
+               $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+                       new Toolkit_Toolbox_PageGatewayPublish(
+                               $this->registry->dbh
+                       )
+               );
+               $tEngine = new HTML_Template_Flexy($this->registry->flexyOptions);
+               $glmPage = new Toolkit_Page(
+                       new Toolkit_Template_Page(),
+                       $breadCrumbsFactory,
+                       new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Members_MembersOnly_Navigation_Factory(),
+                       $keywordReplacement,
+                       MEMBERS_EVENTS_PAGE
+               );
+
+               $glmPage->fetchPage();
+
+               $glmPage->toolboxContent .= $eventContent;
+        $baseSecureUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? BASE_SECURE_URL
+            : BASE_URL;
+        $appBaseSecueUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? GLM_APP_BASE_SECURE_URL
+            : GLM_APP_BASE_URL;
+        $GLOBALS['styleSheets'][]
+            = $baseSecureUrl . 'css/contactform.css';
+        $GLOBALS['styleSheets'][]
+            = $baseSecureUrl . 'Toolkit/Members/css/member-admin.css';
+        $GLOBALS['styleSheets'][]
+            = $appBaseSecueUrl
+            . 'libjs/jqueryui/1.8.13/development-bundle/themes/base/jquery.ui.all.css';
+
+               $glmPage->topScripts    = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile('template.html');
+               $tEngine->outputObject($glmPage);
+
+       }
+
+       //      }}}
+
+       //      {{{     indexAction()
+
+    /**
+     * Description for indexAction()
+     *
+     * @return void
+     * @throws Toolkit_Members_Exception
+     * @access public
+     */
+       public function indexAction()
+       {
+        $eventMapper = new EventMapper(Toolkit_Database::getInstance());
+        $data = $eventMapper->fetchAllMemberEvents(
+            $this->registry->memberId
+        );
+        $html = '';
+        if (is_array($data) && !empty($data)) {
+            $html .= '<table style="float:left;" class="member-admin-table">';
+            $html .= '<tr>
+                <th>&nbsp;</th>
+                <th>Event</th>
+                <th>Status</th>
+                <th>Start</th>
+                <th>End</th>
+                    </tr>';
+            foreach( $data as $row ){
+                $html .= '<tr>
+                    <td>
+                        <div class="buttons">
+                            <a href="'.$this->page.'?rt=CommonEvents&amp;ac=addEvent&amp;id='.$row->getId().'">
+                            Edit
+                        </a>
+                        </div>
+                    </td>
+                    <td>
+                        '.$row->getHeader().'
+                    </td>
+                    <td>
+                        '.( ( $row->getActive() == 't' ) ? 'Active' : 'Pending').'
+                    </td>
+                    <td>
+                        '.$row->getStarting().'
+                    </td>
+                    <td>
+                        '.$row->getEnding().'
+                    </td>
+                </tr>';
+            }
+            $html .= '</table>';
+        }
+
+               $this->_createPage($html);
+       }
+
+       //      }}}
+       //      {{{     addEventAction()
+    /**
+     * Description of addEventAction()
+     *
+     * @return void
+     * @access public
+     */
+       public function addEventAction()
+       {
+        // get code for edit event here
+        //  application configuration
+        $conf = new Config;
+        $root =& $conf->parseConfig(
+                       BASE . 'Toolkit/Members/config.ini',
+                       'IniFile'
+               );
+        $eventMapper = new EventMapper(Toolkit_Database::getInstance());
+        $form = new Toolkit_Members_Events_CommonEditEvent(
+            $this->registry->dbh,
+                       'edit_event',
+            $method = 'post',
+            '',
+            '',
+            null,
+            false,
+            $eventMapper
+               );
+
+               $form->configureForm();
+               $html = $form->toHtml(
+                       Toolkit_Database::getInstance(),
+                       new Toolkit_Image_Server()
+               );
+
+               $this->_createPage($html);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/MembersOnly/Controller.php b/Toolkit/Members/MembersOnly/Controller.php
new file mode 100644 (file)
index 0000000..3f06b0e
--- /dev/null
@@ -0,0 +1,290 @@
+<?php
+/**
+ * Controller.php
+ *
+ * PHP Version 5.2
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_Controller
+ *
+ * Description of Toolkit_Members_MembersOnly_Controller
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_Controller
+{
+       //      {{{     properties
+
+    /**
+     * Member ID
+     * @var int
+     * @access private
+     */
+       private $_mid;
+
+       //      }}}
+
+       //      {{{     __construct()
+
+    /**
+     * Class constructor
+     *
+     * @param integer $mid
+     *
+     * @throws InvalidArgumentException
+     * @access public
+     */
+       public function __construct($mid)
+       {
+               if (!ctype_digit((string)$mid)) {
+                       throw new InvalidArgumentException(
+                               '$mid must be an integer'
+                       );
+               }
+
+               $this->_mid = $mid;
+               $_GET['catid'] = $page_id = ($_REQUEST['page_id'])
+                       ? $_REQUEST['page_id']
+                       : MEMBERS_ONLY_CATEGORY;
+       }
+
+       //      }}}
+
+       //      {{{     getPage()
+
+
+    /**
+     * Description of getPage()
+     *
+     * @param PDO                                    $dbh      Database handler
+     * @param Config_Container                       $config   Config COntainer
+     * @param Toolkit_Members_MembersOnly_Navigation $nav      Description of $nav..
+     * @param string                                 $template Description of $template..
+     *
+     * @return string|mixed Mixed only from error
+     * @access public
+     */
+       public function getPage(
+               PDO $dbh,
+               Config_Container $config,
+               Toolkit_Members_MembersOnly_Navigation $nav,
+               $template
+       ) {
+               $toolbox = new GLM_TEMPLATE($_GET['catid']);
+               $tEngine =  new HTML_Template_Flexy($GLOBALS['flexyOptions']);
+               $page    =  new Toolkit_Page($toolbox);
+
+               $navArray      = $nav->getNavStructure($dbh, $config);
+               $page->sideNav = $nav->renderPageNav($navArray, 'tree');
+               $page->title   = $toolbox->title();
+
+               $page->toolboxContent = '';
+
+               if (isset($_GET['Option']) && isset($_GET['Action'])) {
+                       if (   $_GET['Option'] == 'Member'
+                               && $_GET['Action'] == 'Edit'
+                       ) {
+                               $toolbox->set_catid(MEMBERS_PROFILE_FORM_PAGE);
+                               $page->toolboxContent = $toolbox->get_page();
+                       } elseif (   $_GET['Option'] == 'Coupons'
+                                         && $_GET['Action'] == 'List'
+                       ) {
+                               $toolbox->set_catid(MEMBERS_COUPONS_PAGE);
+                               $page->toolboxContent = $toolbox->get_page();
+                       } elseif (   $_GET['Option'] == 'Events'
+                                         && $_GET['Action'] == 'List'
+                       ) {
+                               $toolbox->set_catid(MEMBERS_EVENTS_PAGE);
+                               $page->toolboxContent = $toolbox->get_page();
+                       } elseif (   $_GET['Option'] == 'Reports'
+                                     && $_GET['Action'] == 'List'
+                       ) {
+                               $toolbox->set_catid(MEMBERS_REPORTS_PAGE);
+                               $page->toolboxContent = $toolbox->get_page();
+                       }
+               }
+
+               try {
+                       $method = $this->_getMethod();
+               } catch (BadMethodCallException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+
+               if ($method = $this->_getMethod()) {
+                       $page->toolboxContent .= $this->$method();
+               } else {
+                       $page->toolboxContent .= $toolbox->get_page();
+               }
+
+               $page->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $page->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile($template);
+               return $tEngine->bufferedOutputObject($page);
+       }
+
+       //      }}}
+       //      {{{     _getMethod()
+
+    /**
+     * Description of _getMethod
+     *
+     * @return boolean|string
+     * @access private
+     * @throws BadMethodCallException
+     */
+       private function _getMethod()
+       {
+               $act = strtolower($_GET['Action']);
+               $opt = ucfirst($_GET['Option']);
+
+               if (!empty($opt) && !empty($act)) {
+                       $methodName =  "_{$act}{$opt}";
+
+                       if (!method_exists($this, $methodName)) {
+                               throw new BadMethodCallException(
+                                       "Invalid method $methodName"
+                               );
+                       }
+
+                       return $methodName;
+               } else {
+                       //      no method to call
+                       return false;
+               }
+       }
+
+       //      }}}
+    // {{{ _deleteEvents()
+    /**
+     * description for _deleteEvents()
+     *
+     * @return string
+     * @access public
+     */
+    function _deleteEvents()
+    {
+        $event = new Toolkit_Event(
+            Toolkit_Database::getInstance()
+        );
+        if (ctype_digit($_REQUEST['event_id'])) {
+            $event->fetch($_REQUEST['event_id']);
+            $event->delete();
+        }
+        $out = '<p>Event Succesfully Deleted!</p>';
+        return $out . $this->_listEvents();
+
+    }// }}}
+
+       //      {{{     _editMember()
+
+    /**
+     *  Description for _editMember()
+     *
+     * @return string
+     * @access private
+     */
+       private function _editMember()
+       {
+               //      need to work at removing this
+               $_REQUEST['id'] = $_GET['id'] = $this->_mid;
+
+               $dbh = Toolkit_Database::getInstance();
+               $member = new Toolkit_Membersonly();
+               return $member->toHtml($dbh, $this->_mid);
+       }
+
+       //      }}}
+
+       //      {{{     _listReports()
+
+    /**
+     * Description for _listReports
+     *
+     * @return string
+     * @access private
+     */
+       private function _listReports()
+       {
+               $dReport = new Toolkit_Members_ExposureDetailReports(
+                       Toolkit_Database::getInstance()
+               );
+               $dReport->setQuery($this->_mid);
+               $dReport->setDefaultSort(array('month' => 'desc'));
+
+               $rEngine = new Structures_DataGrid_Renderer_Flexy();
+               $tplOpts = Toolkit_Members::getFlexyOptions();
+               $tEngine = new HTML_Template_Flexy($tplOpts);
+               $rEngine->setContainer($tEngine);
+
+               $out = $dReport->toHtml($rEngine);
+
+               if (   defined('EXPOSURE_REPORTS_LIST')
+                       && EXPOSURE_REPORTS_LIST
+               ) {
+                       $eReports = new Toolkit_Members_ExposureReports(
+                               Toolkit_Database::getInstance()
+                       );
+                       $eReports->setQuery($_REQUEST['reportMonth']);
+
+                       $out .= $eReports->toHtml($rEngine);
+               } else {
+                       $out .= "<h1>Exposure Reports</h1>\n";
+                       $out .= "<p>\n";
+                       $out .= "Exposure Reports - Check the statistics being compiled that include:\n";
+                       $out .= "<ul>\n";
+                       $out .= "\t<li>Listed - Number of times your member record was viewed in search result page.</li>\n";
+                       $out .= "\t<li>Details - Number of times your member profile page was visited.</li>\n";
+                       $out .= "\t<li>Clicks - Number of times your web site address was clicks on.</li>\n";
+                       $out .= "</ul\n";
+                       $out .= "</p>\n";
+                       $out .= "<br clear=\"all\"></hr>\n";
+               }
+
+               return $out;
+       }
+
+       //      }}}
+
+       //      {{{     _pageToolbox()
+
+    /**
+     * Description of _pageToolbox
+     *
+     * @return string
+     * @throws RuntimeException
+     * @access private
+     */
+       private function _pageToolbox()
+       {
+               if (!ctype_digit($_GET['page_id'])) {
+                       throw new RuntimeException(
+                               '$_GET[\'page_id\'] must be an integer'
+                       );
+               }
+
+               $toolbox = new GLM_TEMPLATE($_GET['page_id']);
+               $out  = $toolbox->get_category();
+               $out .= $toolbox->get_listings();
+
+               return $out;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/MembersOnly/CouponsController.php b/Toolkit/Members/MembersOnly/CouponsController.php
new file mode 100644 (file)
index 0000000..0d18a4b
--- /dev/null
@@ -0,0 +1,216 @@
+<?php
+/**
+ * CouponsController.php
+ *
+ * PHP Version 5.2
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_IndexController
+ *
+ * Description of Toolkit_Members_MembersOnly_IndexController
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_CouponsController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     _creatPage()
+
+    /**
+     * Description for _createPage()
+     *
+     * @param string $couponContent
+     *
+     * @return void
+     * @access private
+     */
+       private function _createPage($couponContent)
+       {
+               $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+                       new Toolkit_Toolbox_PageGatewayPublishFactory(
+                               $this->registry->dbh
+                       )
+               );
+               $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+                       new Toolkit_Toolbox_PageGatewayPublish(
+                               $this->registry->dbh
+                       )
+               );
+               $tEngine = new HTML_Template_Flexy($this->registry->flexyOptions);
+               $glmPage = new Toolkit_Page(
+                       new Toolkit_Template_Page(),
+                       $breadCrumbsFactory,
+                       new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Members_MembersOnly_Navigation_Factory(),
+                       $keywordReplacement,
+                       MEMBERS_COUPONS_PAGE
+               );
+
+               //$glmPage->title = $toolbox->title();
+
+               $glmPage->fetchPage();
+
+               $glmPage->toolboxContent .= $couponContent;
+        $baseSecureUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? BASE_SECURE_URL
+            : BASE_URL;
+        $appBaseSecueUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? GLM_APP_BASE_SECURE_URL
+            : GLM_APP_BASE_URL;
+        $GLOBALS['styleSheets'][]
+            = $baseSecureUrl . 'css/contactform.css';
+        $GLOBALS['styleSheets'][]
+            = $baseSecureUrl . 'Toolkit/Members/css/member-admin.css';
+
+               $glmPage->topScripts    = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile('template.html');
+               $tEngine->outputObject($glmPage);
+
+       }
+
+       //      }}}
+
+       //      {{{     indexAction()
+
+    /**
+     * Description for indexAction()
+     *
+     * @return void
+     * @access public
+     * @throws Toolkit_Members_Exception
+     */
+       public function indexAction()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM coupons
+                                WHERE member = :mid
+                                ORDER BY sdate desc, edate desc, title";
+
+                       $stmt = $this->registry->dbh->prepare($sql);
+                       $stmt->bindParam(
+                               ':mid',
+                               $this->registry->memberId,
+                               PDO::PARAM_INT
+                       );
+                       $stmt->execute();
+
+                       $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
+
+                       $html = '';
+                       if (is_array($data) && !empty($data)) {
+                               $format = '<a href="%s">Edit</a>';
+                               $html  = "<table style=\"float: left;\" class=\"member-admin-table\">\n";
+                               $html .= "<tr>\n";
+                               $html .= "\t<th>&nbsp;</th>\n";
+                               $html .= "\t<th>Coupons</th>\n";
+                               $html .= "\t<th>Status</th>\n";
+                               $html .= "\t<th>Start</th>\n";
+                               $html .= "\t<th>End</th>\n";
+                               $html .= "\t<th>Expire</th>\n";
+                               $html .= "</tr>\n";
+                               foreach ($data as $row) {
+                                       $link = sprintf(
+                                               $format,
+                                               BASE_URL . "members-only-area/?rt=Coupons&ac=addCoupon&page_id={$_REQUEST['page_id']}&id={$row['id']}"
+                                       );
+                                       if ($row['pending']) {
+                                               $status = 'Pending';
+                                       } elseif ($row['active']) {
+                                               $status = 'Active';
+                                       } else {
+                                               $status = 'Disabled';
+                                       }
+                                       $html .= "<tr>\n";
+                                       $html .= "\t<td>$link</td>\n";
+                                       $html .= "\t<td>{$row['title']}</td>\n";
+                                       $html .= "\t<td>$status</td>\n";
+                                       $html .= "\t<td>{$row['sdate']}</td>\n";
+                                       $html .= "\t<td>{$row['edate']}</td>\n";
+                                       $html .= "\t<td>{$row['expiration']}</td>\n";
+                                       $html .= "</tr>\n";
+                               }
+                               $html .= "</table>\n";
+                       }
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               'Error fetching member coupons list'
+                       );
+               }
+
+               $this->_createPage($html);
+       }
+
+       //      }}}
+       //      {{{     addCouponAction()
+
+    /**
+     * Description of addCouponAction()
+     *
+     * @return void
+     * @access public
+     */
+       public function addCouponAction()
+       {
+        //  application configuration
+        $conf = new Config;
+        $root =& $conf->parseConfig(
+                       BASE . 'Toolkit/Members/config.ini',
+                       'IniFile'
+               );
+
+               $couponMailerTemplateData = new stdClass();
+               $couponMailerTemplateData->memberName = $this->registry->memberName;
+
+               $flexyOptions = $this->registry->flexyOptions;
+               $flexyOptions['templateDir'] = BASE . 'Toolkit/Members/templates';
+               $flexyOptions['compileDir'] = BASE . 'Toolkit/Members/templates/compiled';
+               $tEngine = new HTML_Template_Flexy($flexyOptions);
+               $tEngine->compile('editCouponEmail.tpl');
+               $mailer = new Toolkit_Members_Coupons_Mailer(
+                       $tEngine,
+                       new Mail_mime("\n"),
+                       Mail::factory('mail')
+               );
+
+               $form = new Toolkit_Members_Coupons_EditCouponForm(
+                       'edit_coupon'
+               );
+
+               $form->configureForm($this->registry->dbh, $root);
+               $html = $form->toHtml(
+                       Toolkit_Database::getInstance(),
+            new Toolkit_Image_Server(),
+                       new Toolkit_Coupons_MemberCouponFactory(),
+                       $mailer,
+                       $couponMailerTemplateData
+               );
+
+               $this->_createPage($html);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/MembersOnly/EditProfileController.php b/Toolkit/Members/MembersOnly/EditProfileController.php
new file mode 100644 (file)
index 0000000..96fe87c
--- /dev/null
@@ -0,0 +1,86 @@
+<?php
+/**
+ * EditProfileController.php
+ * 
+ * PHP Version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_EditProfileController
+ * 
+ * Description of Toolkit_Members_MembersOnly_EditProfileController
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_EditProfileController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+
+    /**
+     * Description of indexAction()
+     * 
+     * @return void
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+                       new Toolkit_Toolbox_PageGatewayPublishFactory(
+                               $this->registry->dbh
+                       )
+               );
+               $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+                       new Toolkit_Toolbox_PageGatewayPublish(
+                               $this->registry->dbh
+                       )
+               );
+               $tEngine = new HTML_Template_Flexy($this->registry->flexyOptions);
+               $glmPage = new Toolkit_Page(
+                       new Toolkit_Template_Page(),
+                       $breadCrumbsFactory,
+                       new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Members_MembersOnly_Navigation_Factory(),
+                       $keywordReplacement,
+                       MEMBERS_PROFILE_FORM_PAGE
+               );
+
+               //$glmPage->title = $toolbox->title();
+
+               $glmPage->fetchPage();
+
+               //      need to work at removing this
+               $_REQUEST['id'] = $_GET['id'] = $this->registry->memberId;
+
+               $member = new Toolkit_Membersonly();
+               $glmPage->toolboxContent .= $member->toHtml(
+                       $this->registry->dbh,
+                       $this->registry->memberId
+               );
+
+               $glmPage->topScripts    = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile('template.html');
+               $tEngine->outputObject($glmPage);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/MembersOnly/EventsController.php b/Toolkit/Members/MembersOnly/EventsController.php
new file mode 100644 (file)
index 0000000..fdc85ef
--- /dev/null
@@ -0,0 +1,200 @@
+<?php
+/**
+ * EventsController.php
+ *
+ * PHP Version 5.2
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_EventsController
+ *
+ * Description of Toolkit_Members_MembersOnly_EventsController
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+
+class Toolkit_Members_MembersOnly_EventsController
+       extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+       //      {{{     _creatPage()
+
+    /**
+     * Description of _createPage()
+     *
+     * @param string $eventContent Description of $eventcontent
+     *
+     * @return void
+     * @access private
+     */
+       private function _createPage($eventContent)
+       {
+               $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+                       new Toolkit_Toolbox_PageGatewayPublishFactory(
+                               $this->registry->dbh
+                       )
+               );
+               $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+                       new Toolkit_Toolbox_PageGatewayPublish(
+                               $this->registry->dbh
+                       )
+               );
+               $tEngine = new HTML_Template_Flexy($this->registry->flexyOptions);
+               $glmPage = new Toolkit_Page(
+                       new Toolkit_Template_Page(),
+                       $breadCrumbsFactory,
+                       new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Members_MembersOnly_Navigation_Factory(),
+                       $keywordReplacement,
+                       MEMBERS_EVENTS_PAGE
+               );
+
+               $glmPage->fetchPage();
+
+               $glmPage->toolboxContent .= $eventContent;
+        $baseSecureUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? BASE_SECURE_URL
+            : BASE_URL;
+        $appBaseSecueUrl
+            = ($_SERVER['HTTPS'] == 'on')
+            ? GLM_APP_BASE_SECURE_URL
+            : GLM_APP_BASE_URL;
+        $GLOBALS['styleSheets'][]
+            = $baseSecureUrl . 'css/contactform.css';
+        $GLOBALS['styleSheets'][]
+            = $baseSecureUrl . 'Toolkit/Members/css/member-admin.css';
+        $GLOBALS['styleSheets'][]
+            = $appBaseSecueUrl
+            . 'libjs/jqueryui/1.8.13/development-bundle/themes/base/jquery.ui.all.css';
+
+               $glmPage->topScripts    = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile('template.html');
+               $tEngine->outputObject($glmPage);
+
+       }
+
+       //      }}}
+
+       //      {{{     indexAction()
+
+    /**
+     * Description for indexAction()
+     *
+     * @return void
+     * @throws Toolkit_Members_Exception
+     * @access public
+     */
+       public function indexAction()
+       {
+               try {
+            // get code for list events
+            $sql = "
+              SELECT *
+                FROM event
+               WHERE member_id = :mid
+            ORDER BY bdate DESC,edate DESC,header";
+                       $stmt = $this->registry->dbh->prepare($sql);
+                       $stmt->bindParam(
+                               ':mid',
+                               $this->registry->memberId,
+                               PDO::PARAM_INT
+                       );
+                       $stmt->execute();
+
+                       $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
+                       $html = '';
+                       if (is_array($data) && !empty($data)) {
+                $html .= '<table style="float:left;" class="member-admin-table">';
+                $html .= '<tr>
+                    <th>&nbsp;</th>
+                    <th>Event</th>
+                    <th>Status</th>
+                    <th>Start</th>
+                    <th>End</th>
+                        </tr>';
+                foreach( $data as $row ){
+                    $html .= '<tr>
+                        <td>
+                            <div class="buttons">
+                                <a href="'.$this->page.'?rt=Events&amp;ac=addEvent&amp;id='.$row["id"].'">
+                                Edit
+                            </a>
+                            </div>
+                        </td>
+                        <td>
+                            '.$row["header"].'
+                        </td>
+                        <td>
+                            '.( ( $row['visable'] == 't' ) ? 'Active' : 'Pending').'
+                        </td>
+                        <td>
+                            '.$row["bdate"].'
+                        </td>
+                        <td>
+                            '.$row["edate"].'
+                        </td>
+                    </tr>';
+                }
+                $html .= '</table>';
+            }
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               'Error fetching member Events list'
+                       );
+               }
+               $this->_createPage($html);
+       }
+
+       //      }}}
+       //      {{{     addEventAction()
+    /**
+     * Description of addEventAction()
+     *
+     * @return void
+     * @access public
+     */
+       public function addEventAction()
+       {
+        // get code for edit event here
+        //  application configuration
+        $conf = new Config;
+        $root =& $conf->parseConfig(
+                       BASE . 'Toolkit/Members/config.ini',
+                       'IniFile'
+               );
+        $form = new Toolkit_Members_Events_EditEvent(
+            $this->registry->dbh,
+                       'edit_event'
+               );
+
+               $form->configureForm();
+               $html = $form->toHtml(
+                       Toolkit_Database::getInstance(),
+                       new Toolkit_Image_Server()
+               );
+
+               $this->_createPage($html);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/MembersOnly/IndexController.php b/Toolkit/Members/MembersOnly/IndexController.php
new file mode 100644 (file)
index 0000000..c67095c
--- /dev/null
@@ -0,0 +1,76 @@
+<?php
+/**
+ * IndexController.php
+ * 
+ * PHP Version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_IndexController
+ * 
+ * Description of Toolkit_Members_MembersOnly_IndexController
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_IndexController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+
+    /**
+     * Description of indexAction()
+     * 
+     * @return void
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+                       new Toolkit_Toolbox_PageGatewayPublishFactory(
+                               $this->registry->dbh
+                       )
+               );
+               $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+                       new Toolkit_Toolbox_PageGatewayPublish(
+                               $this->registry->dbh
+                       )
+               );
+               $tEngine = new HTML_Template_Flexy($this->registry->flexyOptions);
+               $glmPage = new Toolkit_Page(
+                       new Toolkit_Template_Page(),
+                       $breadCrumbsFactory,
+                       new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Members_MembersOnly_Navigation_Factory(),
+                       $keywordReplacement,
+                       $this->registry->pageid
+               );
+
+               //$glmPage->title = $toolbox->title();
+
+               $glmPage->fetchPage();
+
+               $glmPage->topScripts    = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile('template.html');
+               $tEngine->outputObject($glmPage);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/MembersOnly/LeadsController.php b/Toolkit/Members/MembersOnly/LeadsController.php
new file mode 100644 (file)
index 0000000..58e6ba8
--- /dev/null
@@ -0,0 +1,88 @@
+<?php
+/**
+ * LeadsController.php
+ * 
+ * PHP Version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ *  
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_LeadsController
+ * 
+ * Description of Toolkit_Members_MembersOnly_LeadsController
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_LeadsController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+
+    /**
+     * Description of indexAction()
+     * 
+     * @return void
+     * @access public 
+     */
+       public function indexAction()
+       {
+               $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+                       new Toolkit_Toolbox_PageGatewayPublishFactory(
+                               $this->registry->dbh
+                       )
+               );
+               $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+                       new Toolkit_Toolbox_PageGatewayPublish(
+                               $this->registry->dbh
+                       )
+               );
+               $tEngine = new HTML_Template_Flexy($this->registry->flexyOptions);
+               $glmPage = new Toolkit_Page(
+                       new Toolkit_Template_Page(),
+                       $breadCrumbsFactory,
+                       new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Members_MembersOnly_Navigation_Factory(),
+                       $keywordReplacement,
+                       MEMBERS_LEADS_PAGE
+               );
+
+               $glmPage->fetchPage();
+
+        // Export File Form
+        $export = new Toolkit_Members_Leads_ExportFileForm(
+            'file_export',
+            'POST',
+            BASE_URL . 'members-only-area/?rt=Leads&page_id='.MEMBERS_LEADS_PAGE,
+            '',
+            null,
+            true
+        );
+
+        $export->configureForm();
+               $glmPage->toolboxContent .= $export->toHtml($this->registry->dbh);
+
+               $glmPage->topScripts    = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile('template.html');
+               $tEngine->outputObject($glmPage);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/MembersOnly/Navigation/Factory.php b/Toolkit/Members/MembersOnly/Navigation/Factory.php
new file mode 100644 (file)
index 0000000..e5a95dc
--- /dev/null
@@ -0,0 +1,89 @@
+<?php
+/**
+ * Factory.php
+ * 
+ * PHP Version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_Navigation_Factory
+ * 
+ * Description of Toolkit_Members_MembersOnly_Navigation_Factory
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_Navigation_Factory
+       extends Toolkit_NavigationFactoryAbstract
+{
+    /**
+     * Description of $_gateway
+     * @var Toolkit_Toolbox_PageGatewayAbstract
+     * @access private 
+     */
+       private $_gateway;
+
+    /**
+     * Description of setGateway()
+     *
+     * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Toolbox Gateway
+     * 
+     * @return void
+     * @access public
+     */
+       public function setGateway(Toolkit_Toolbox_PageGatewayAbstract $gateway)
+       {
+               $this->_gateway = $gateway;
+       }
+
+    /**
+     * Description of createSideNav()
+     * 
+     * @return \Toolkit_Members_MembersOnly_Navigation_Side 
+     * @access public
+     */
+       public function createSideNav()
+       {
+               $nav = new Toolkit_Members_MembersOnly_Navigation_Side(
+                       new HTML_Menu(),
+                       new HTML_Menu_DirectTreeRenderer()
+               );
+
+               $conf = new Config;
+               $root =& $conf->parseConfig(
+                       BASE . 'Toolkit/Members/config.ini',
+                       'IniFile'
+               );
+               $nav->setConfig($root);
+
+               return $nav;
+       }
+
+    /**
+     * Description for createMainNav()
+     * 
+     * @return \Toolkit_Template_Navigation_MainNavigationStatic 
+     * @access public
+     */
+       public function createMainNav()
+       {
+               return new Toolkit_Template_Navigation_MainNavigationStatic(
+                       new HTML_Menu(),
+                       new Toolkit_Template_Navigation_Renderer_DirectTreeLastLi('lastli')
+               );
+       }
+}
+?>
diff --git a/Toolkit/Members/MembersOnly/Navigation/Side.php b/Toolkit/Members/MembersOnly/Navigation/Side.php
new file mode 100644 (file)
index 0000000..912b657
--- /dev/null
@@ -0,0 +1,289 @@
+<?php
+/**
+ * Side.php
+ *
+ * PHP Version 5.2
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_Navigation_Side
+ *
+ * Description of Toolkit_Members_MembersOnly_Navigation_Side
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_Navigation_Side extends Toolkit_NavigationAbstract
+       implements Toolkit_INavigation
+{
+       //      {{{     properties
+
+    /**
+     * Description for $_config
+     * @var Config_Container
+     * @access private
+     */
+       private $_config = null;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Class constructor
+     *
+     * @param HTML_Menu          $menu    Description for HTML_Menu
+     * @param HTML_Menu_Renderer $rEngine Description for HTML Menu Renderer
+     *
+     * @access public
+     */
+       public function __construct(
+               HTML_Menu $menu,
+               HTML_Menu_Renderer $rEngine
+       ) {
+               $this->menu      = $menu;
+               $this->rEngine   = $rEngine;
+               $this->currIndex = 'home';
+       }
+
+       //      }}}
+
+       //      {{{     setConfig()
+
+    /**
+     * Description for setConfig
+     *
+     * @param Config_Container $config Config container
+     *
+     * @return void
+     * @access public
+     */
+       public function setConfig(Config_Container $config)
+       {
+               $this->_config = $config;
+       }
+
+       //      }}}
+       //      {{{     getNavSructure()
+       //      @codeCoverageIgnoreStart
+
+    /**
+     * Sets up a multi dimensional array used for the nav structure
+        *
+        * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway
+        * @param integer                         $id      id of page we're on
+        *
+     * @return array navigation structure
+     * @access public
+     */
+       public function getNavStructure(
+               Toolkit_Toolbox_GatewayAbstract $gateway,
+               $id
+       ) {
+               $nav = $this->_getToolboxNav($gateway, $id);
+               $nav['travel'] = array(
+                       'title' => 'Travel Reservation System',
+                       'url' => 'http://travel.gaslightmedia.com/members/'
+               );
+               $nav['logout'] = array(
+                       'title' => 'Log out',
+                       'url' => BASE_URL . 'members-only-area/?logout=',
+               );
+
+               $hasTravelSystem
+                       = $this->_config->getItem('section', 'conf')
+                ->getItem('directive', 'glmReservations')
+                ->getContent();
+
+               if (!$hasTravelSystem) {
+                       unset($nav['travel']);
+               }
+
+               $hasCoupons
+                       = $this->_config->getItem('section', 'members only')
+                ->getItem('directive', 'coupons')
+                ->getContent();
+
+               if (!$hasCoupons) {
+                       unset($nav[MEMBER_COUPONS_PAGE]);
+               }
+
+               $hasEvents
+                       = $this->_config->getItem('section', 'members only')
+                ->getItem('directive', 'events')
+                ->getContent();
+
+               if (!$hasEvents) {
+                       unset($nav['events']);
+               }
+
+               return $nav;
+       }
+
+       //      @codeCoverageIgnoreEnd
+       //      }}}
+       //      {{{     _getToolboxNav()
+
+    /**
+     * Description for _getToolboxNav()
+     *
+     * @param Toolkit_Toolbox_GatewayAbstract $gateway  Toolbox gateway
+     * @param integer                         $id       ID of page we're on
+     * @param array                           $tree     Description for $tree
+     * @param unknown                         $appendTo Description for $appendTo
+     *
+     * @return array
+     * @access private
+     */
+       private function _getToolboxNav(
+               Toolkit_Toolbox_GatewayAbstract $gateway,
+               $id,
+               array $tree = null,
+               $appendTo = null
+       ) {
+               $currentPage = $gateway->find($id);
+               $subPages    = $gateway->findAllByParent($currentPage['parent']);
+
+               $nav = array();
+               foreach ($subPages as $subPage) {
+                       if ($subPage['active']) {
+                               if (   defined('MEMBERS_PROFILE_FORM_PAGE')
+                                       && $subPage['id'] == MEMBERS_PROFILE_FORM_PAGE
+                               ) {
+                                       $nav[$subPage['id']] = array(
+                                               'title' => strip_tags($subPage['navigation_name']),
+                                               'url' => BASE_URL . 'members-only-area/?rt=EditProfile&tab=info'
+                                       );
+                               } elseif (   defined('MEMBERS_COUPONS_PAGE')
+                                             && $subPage['id'] == MEMBERS_COUPONS_PAGE
+                               ) {
+                                       $nav[$subPage['id']] = array(
+                                               'title' => strip_tags($subPage['navigation_name']),
+                                               'url' => BASE_URL . 'members-only-area/?rt=Coupons&page_id=' . $subPage['id'],
+                                               'sub' => array(
+                                                       'listCoupons' => array(
+                                                               'title' => 'List Coupons',
+                                                               'url' => BASE_URL . 'members-only-area/?rt=Coupons&page_id=' . $subPage['id'],
+                                                       ),
+                                                       'addCoupon' => array(
+                                                               'title' => 'Add Coupon',
+                                                               'url' => BASE_URL . 'members-only-area/?rt=Coupons&ac=addCoupon&page_id=' . $subPage['id'],
+                                                       )
+                                               )
+                                       );
+                               } elseif (   defined('MEMBERS_EVENTS_PAGE')
+                                             && $subPage['id'] == MEMBERS_EVENTS_PAGE
+                               ) {
+                    $routerCalled
+                        = (defined('COMMON_EVENTS') && COMMON_EVENTS)
+                        ? 'CommonEvents'
+                        : 'Events';
+                                       $nav[$subPage['id']] = array(
+                                               'title' => strip_tags($subPage['navigation_name']),
+                                               'url' => BASE_URL . 'members-only-area/?rt='.$routerCalled.'&page_id=' . $subPage['id'],
+                                               'sub' => array(
+                                                       'listEvents' => array(
+                                                               'title' => 'List Events',
+                                                               'url' => BASE_URL . 'members-only-area/?rt='.$routerCalled.'&page_id=' . $subPage['id'],
+                                                       ),
+                                                       'addEvent' => array(
+                                                               'title' => 'Add Event',
+                                                               'url' => BASE_URL . 'members-only-area/?rt='.$routerCalled.'&ac=addEvent&page_id=' . $subPage['id'],
+                                                       )
+                                               )
+                                       );
+                               } elseif (   defined('MEMBERS_REPORTS_PAGE')
+                                                 && $subPage['id'] == MEMBERS_REPORTS_PAGE
+                               ) {
+                                       $nav[$subPage['id']] = array(
+                                               'title' => strip_tags($subPage['navigation_name']),
+                                               'url' => BASE_URL . 'members-only-area/?rt=Reports&page_id=' . $subPage['id']
+                                       );
+                               } elseif (   defined('MEMBERS_LEADS_PAGE')
+                                                 && $subPage['id'] == MEMBERS_LEADS_PAGE
+                               ) {
+                                       $nav[$subPage['id']] = array(
+                                               'title' => strip_tags($subPage['navigation_name']),
+                                               'url' => BASE_URL . 'members-only-area/?rt=Leads&page_id=' . $subPage['id']
+                                       );
+                               } else {
+                                       $nav[$subPage['id']] = array(
+                                               'title' => strip_tags($subPage['navigation_name']),
+                                               'url' => BASE_URL . 'members-only-area/?page_id=' . $subPage['id']
+                                       );
+                               }
+                       }
+               }
+
+               if (is_array($tree) && array_key_exists($appendTo, $nav)) {
+                       $nav[$appendTo]['sub'] = $tree;
+               }
+
+               if ($currentPage['parent'] != MEMBERS_CATEGORY) {
+                       return $this->_getToolboxNav(
+                               $gateway,
+                               $currentPage['parent'],
+                               $nav,
+                               $id
+                       );
+               } else {
+            //var_dump($id, $nav);die;
+                       return $nav;
+               }
+       }
+
+       //      }}}
+
+       //      {{{     setCurrentIndex()
+
+    /**
+     * Description for setCurrentIndex
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setCurrentIndex()
+       {
+               $this->menu->forceCurrentIndex($_GET['page_id']);
+       }
+
+       //      }}}
+       //      {{{     setNavTemplates()
+
+    /**
+     * Description of setNavTemplates
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setNavTemplates()
+       {
+               $tpl = '<a class="%s" href="%s">{title}</a>';
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_INACTIVE,
+                       sprintf($tpl, '{class}', '{url}', '{desc}', '{title}')
+               );
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVE,
+                       sprintf($tpl, 'active {class}', '{url}', '{desc}', '{title}')
+               );
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVEPATH,
+                       sprintf($tpl, 'active {class}', '{url}', '{desc}', '{title}')
+               );
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/MembersOnly/ReportsController.php b/Toolkit/Members/MembersOnly/ReportsController.php
new file mode 100644 (file)
index 0000000..5261544
--- /dev/null
@@ -0,0 +1,113 @@
+<?php
+/**
+ * ReportsController.php
+ *
+ * PHP Version 5.2
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_MembersOnly_ReportsController
+ *
+ * Description of Toolkit_Members_MembersOnly_ReportsController
+ *
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: $id$
+ * @link      <>
+ */
+class Toolkit_Members_MembersOnly_ReportsController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     indexAction()
+
+    /**
+     * Desciption of indexAction()
+     *
+     * @return void
+     * @access public
+     */
+       public function indexAction()
+       {
+               $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+                       new Toolkit_Toolbox_PageGatewayPublishFactory(
+                               $this->registry->dbh
+                       )
+               );
+               $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+                       new Toolkit_Toolbox_PageGatewayPublish(
+                               $this->registry->dbh
+                       )
+               );
+               $tEngine = new HTML_Template_Flexy($this->registry->flexyOptions);
+               $glmPage = new Toolkit_Page(
+                       new Toolkit_Template_Page(),
+                       $breadCrumbsFactory,
+                       new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_Members_MembersOnly_Navigation_Factory(),
+                       $keywordReplacement,
+                       MEMBERS_REPORTS_PAGE
+               );
+
+               //$glmPage->title = $toolbox->title();
+
+               $glmPage->fetchPage();
+
+               if (   defined('EXPOSURE_REPORTS_LIST')
+                       && EXPOSURE_REPORTS_LIST
+               ) {
+                       $eReports = new Toolkit_Members_ExposureReports(
+                               $this->registry->dbh
+                       );
+                       $eReports->setQuery($_REQUEST['reportMonth']);
+
+                       $out = $eReports->toHtml($rEngine);
+               } else {
+                       $out = "<h1>Exposure Reports</h1>\n";
+                       $out .= "<p>\n";
+                       $out .= "Exposure Reports - Check the statistics being compiled that include:\n";
+                       $out .= "<ul>\n";
+                       $out .= "\t<li>Listed - Number of times your member record was viewed in search result page.</li>\n";
+                       $out .= "\t<li>Details - Number of times your member profile page was visited.</li>\n";
+                       $out .= "\t<li>Clicks - Number of times your web site address was clicks on.</li>\n";
+                       $out .= "</ul\n";
+                       $out .= "</p>\n";
+                       $out .= "<br clear=\"all\"></hr>\n";
+               }
+
+        $dReport = new Toolkit_Members_ExposureDetailReports(
+                       $this->registry->dbh
+               );
+               $dReport->setQuery($this->registry->memberId);
+               $dReport->setDefaultSort(array('month' => 'desc'));
+
+               $rEngine        = new Structures_DataGrid_Renderer_Flexy();
+               $tplOpts        = Toolkit_Members::getFlexyOptions();
+               $tReportsEngine = new HTML_Template_Flexy($tplOpts);
+               $rEngine->setContainer($tReportsEngine);
+
+               $out .= $dReport->toHtml($rEngine);
+
+               $glmPage->toolboxContent .= $out;
+
+               $glmPage->topScripts    = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+               $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+               $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+               $tEngine->compile('template.html');
+               $tEngine->outputObject($glmPage);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/MembersOnly/index.php b/Toolkit/Members/MembersOnly/index.php
new file mode 100644 (file)
index 0000000..4a7efc0
--- /dev/null
@@ -0,0 +1,86 @@
+<?php
+/**
+ * index.php
+ * 
+ * PHP Version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members_MembersOnly
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+require_once '../../../setup.phtml';
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+//  application configuration
+$conf = new Config;
+$root =& $conf->parseConfig(BASE . 'Toolkit/Members/config.ini', 'IniFile');
+
+$authContainer = new Toolkit_Members_AuthContainer(
+       Toolkit_Database::getInstance(),
+       array(
+               'table'       => 'member',
+               'usernamecol' => 'member_login',
+               'passwordcol' => 'member_passwd',
+               'db_fields'   => array('member_id', 'member_name'),
+               'cryptType'   => 'none',
+               'db_where'    => 'new_member <> true AND active = true',
+       )
+);
+
+$memberAuth = new Toolkit_Members_Auth(
+       $root,
+       $authContainer,
+       '',
+       false
+);
+$memberAuth->setIdle();
+$memberAuth->start();
+
+if (isset($_GET['logout'])) {
+       $memberAuth->logout();
+}
+
+if (!$memberAuth->checkAuth()) {
+       //      Manually adjust the authentication status for empty credentials
+       if (empty($_POST['username']) || empty($_POST['password'])) {
+               $status = -3;
+       }
+       $status = $memberAuth->getStatus();
+       header('Location: ' . BASE_URL . 'index.php?catid=' . MEMBERS_CATEGORY . '&status=' . $status);
+} else {
+    if (!Toolkit_Membersonly::checkMemberExists(
+        Toolkit_Database::getInstance(),
+        $memberAuth->getAuthData('member_id')
+    )) {
+        $memberAuth->logout();
+        $status = $memberAuth->getStatus();
+        header('Location: ' . BASE_URL . 'index.php?catid=' . MEMBERS_CATEGORY . '&status=' . $status);
+    }
+       //      Carry over from old code
+       //      @todo: work to remove
+       $_GET['catid'] = ctype_digit($_REQUEST['page_id'])
+               ? $_REQUEST['page_id']
+               : MEMBERS_ONLY_HOME_PAGE;
+
+       //      Create a new registry so we don't pollute the global namespace
+       $registry = new Toolkit_Registry;
+
+       $registry->cacheOptions = $GLOBALS['cacheOptions'];
+       $registry->flexyOptions = $GLOBALS['flexyOptions'];
+       $registry->memberId     = $memberAuth->getAuthData('member_id');
+       $registry->memberName   = $memberAuth->getAuthData('member_name');
+       $registry->logger       = Toolkit_Logger::getLogger();
+       $registry->pageid       = $_GET['catid'];
+       $registry->dbh          = Toolkit_Database::getInstance();
+
+       //      Create a router so we can get where we need to be.
+       $registry->router = new Toolkit_Router($registry);
+       $registry->router->setPath(BASE . 'Toolkit/Members/MembersOnly');
+       $registry->router->setApplication('Members/MembersOnly');
+
+       $registry->router->loader();
+}
diff --git a/Toolkit/Members/PackageList.php b/Toolkit/Members/PackageList.php
new file mode 100644 (file)
index 0000000..fa396a8
--- /dev/null
@@ -0,0 +1,303 @@
+<?php
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @release  CVS: $Id: SearchList.php,v 1.47 2010/07/14 23:31:14 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Datagrid of search results of member db
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee >steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_PackageList
+    extends Toolkit_FlexyDataGridBuilder
+{
+   /**
+     * Description for $tableName
+     * @var    string
+     * @access protected
+     */
+       protected $tableName = 'member_packages';
+
+    /**
+     * Description for $template
+     * @var    string
+     * @access protected
+     */
+       protected $template = 'packageList.tpl';
+    
+    /**
+     * Description for $members
+     * @var array
+     * @access protected
+     */
+    protected $members = array();
+
+       /**
+        * Class constructor
+        *
+        * define where templates for the data grid are at, then call the parent constructor which will handle
+        * finishing the settings for the datagrid.
+        *
+        * After all settings are finished you can call the toHTML() function on this object and the datagrid
+        * will be rendered and returned as a string.  Optionally you could call show() and the datagrid would
+        * be rendered and output immediatley to the screen.
+        *
+     * @param PDO     $pdo           PHP Data Object to use for DB calls
+     * @param string  $limit         The number of records to display per page.
+     * @param int     $page                 The current page viewed.
+     *                               In most cases, this is useless.
+     *                               Note: if you specify this, the "page" GET
+     *                               variable will be ignored.
+     * @param string  $rendererType  The type of renderer to use.
+     *                               You may prefer to use the $type argument
+     *                               of {@link render}, {@link fill} or
+     *                               {@link getOutput}
+     * @param boolean $showSearchBox If we should allow searching for members
+     * @param array   $sections      specific members we should show
+        *
+     * @return void
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null,
+        $showSearchBox = true,
+        array $sections = null
+    ) {
+               $GLOBALS['styleSheets'][] = BASE_URL . 'member.css';
+               parent::__construct($pdo, $limit, $page, $rendererType);
+       }
+
+       /**
+        * Configures the columns that will be used in our datagrid renderer.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureColumns()
+       {
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Member Id',
+                'member_id',
+                'member_id'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Title',
+                'title',
+                'title'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Intro',
+                'intro',
+                'intro',
+                null,
+                null,
+                array($this, 'renderIntro')
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Member Name',
+                'member_name',
+                'member_name'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Street',
+                'street',
+                'street'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'City',
+                'city',
+                'city'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'State',
+                'state',
+                'state'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Zip',
+                'zip',
+                'zip'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Phone',
+                'phone',
+                'phone'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'member_contact_email',
+                'member_contact_email',
+                'member_contact_email'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'website',
+                'website',
+                'website'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Package Id',
+                'package_id',
+                'package_id'
+            )
+        );
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'Image',
+                'image',
+                'image',
+                null,
+                null,
+                array($this, 'setImg')
+            )
+        );
+        
+               $this->addColumn(
+            new Structures_DataGrid_Column(
+                       'Logo',
+                       'logo',
+                       'logo',
+                       null,
+                       null,
+                       array(&$this, 'logo')
+               )
+        );
+    }
+    /**
+        * Returns the logo for a member.
+        *
+     * @param array $data tuple record from db
+     *
+        * @return false when empty, otherwise logo path for member
+        * @access public
+        */
+       public function logo($data)
+       {
+        extract($data['record']);
+               return empty($logo) ? false : MEMBER_PHOTOS . $logo;
+       }
+    
+    /**
+     * Description for renderIntro()
+     * 
+     * @param array $data Data array
+     * 
+     * @return string the altered string 
+     * @access public
+     */
+    public function renderIntro($data)
+    {
+        return nl2br($data['record']['intro']);
+    }
+    
+    /**
+     * Description for setImg()
+     * 
+     * @param array $data data array
+     * 
+     * @return false when empty, otherwise image path for member 
+     * @access public
+     */
+    public function setImg($data)
+    {
+        extract($data['record']);
+        return empty($image) ? false : MEMBER_PHOTOS . $image;
+    }
+    
+    /**
+     * Description for setPackageType()
+     * 
+     * @param string $type Description for $type
+     * 
+     * @throws InvalidArgumentException 
+     * @return void
+     * @access public
+     */
+    public function setPackageType($type)
+    {
+        if (!in_array(
+            $type,
+            array(
+                'golf_package',
+                'ski_package',
+                'lodging_package'
+            )
+        )) {
+            throw new InvalidArgumentException('type not valid');
+        }
+        $sql = "
+    SELECT mp.*,m.*,c.city_name as city,s.state_abb as state,
+           mp.id as package_id,m.url as website,m.logo as logo
+      FROM member_packages mp, member m,state s,city c
+     WHERE mp.{$type} = 't'
+       AND m.active = 't'
+       AND mp.member_id = m.member_id
+       AND s.state_id = m.state_id
+       AND c.city_id = m.city_id
+       AND current_date BETWEEN mp.sdate and mp.edate";
+        parent::setQuery($sql);
+    }
+
+    /**
+     * Description for setControlObject()
+     * 
+     * @return void
+     * @access protected 
+     */
+    protected function setControlObject()
+       {
+               $this->ctrlObj['base_url'] = BASE_URL;
+        $this->ctrlObj['catid']    = $_REQUEST['catid'];
+       }
+}
diff --git a/Toolkit/Members/Packages.php b/Toolkit/Members/Packages.php
new file mode 100644 (file)
index 0000000..a31a93b
--- /dev/null
@@ -0,0 +1,359 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Linked list (LL) implementation of member packages
+ *
+ * File contains the class that gives the ability to create a linked list
+ * of member packages.  You can iterate through manipulate and control every
+ * aspect of the LL.  The best part is, by keeping the LL in order it
+ * automatically maintains the DB for you.
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Packages.php,v 1.9 2010/05/25 14:01:16 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Structures/LinkedList/Double.php
+ *            Toolkit/Members/Packages/Package.php
+ */
+
+/**
+ * Class implementation of a linked list
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Structures/LinkedList/Double.php
+ */
+class Toolkit_Members_Packages extends Structures_LinkedList_Double
+{
+       //      {{{     properties
+
+    /**
+     * Database handler object
+     * @var    pdo
+     * @access public
+     */
+       public $dbh;
+
+    /**
+     * DB id of member whos packages we are manipulating with this linked list
+     * @var    integer
+     * @access protected
+     */
+       protected $mid;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param Structures_LinkedList_DoubleNode $root Linked List node object
+     * @param int                              $mid  DB id of member we want to prepare the list for
+        *
+     * @access public
+     */
+       function __construct(
+        Structures_LinkedList_DoubleNode $root = null,
+        $mid = null
+    ) {
+               parent::__construct($root);
+               $this->setMember($mid);
+       }
+
+       //      }}}
+
+       //      {{{     createMemberList()
+
+    /**
+     * Creates a linked list from all the packages a member has in the db.
+     *
+     * @param string $order The order to make the linked list in
+        *
+     * @return boolean false on error
+     * @access public
+     */
+       public function createMemberList($order = 'pos')
+       {
+               if (!is_numeric($this->mid)) {
+                       return;
+               }
+
+               $safeOrder = array('pos', 'id');
+               if (!in_array($order, $safeOrder)) {
+                       $order = 'pos';
+               }
+               try {
+                       //      Get each package tuple from the member_packages table.
+                       $sql = "
+                               SELECT *
+                                 FROM member_packages
+                                WHERE member_id = :member_id
+                                ORDER BY $order";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $this->mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch()) {
+                               //      Create a new node w/ all the data we just extracted.
+                               $node = $this->createNode($row);
+                $node->setDbh($this->dbh);
+                               //      Sets up any pending data the package might currently have.
+                               $node->setPendingData();
+                               //      Add the package node to the end of the linked list.
+                               $res = $this->appendNode($node);
+                       }
+
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     createNode()
+
+    /**
+     * Creates a new linked list node object
+     *
+     * @param array $data Data to populate the new node with
+        *
+     * @access public
+     * @return object newly created linked list node
+     */
+       public function &createNode(array $data)
+       {
+               $node = new Toolkit_Members_Packages_Package($data);
+        $node->setDbh($this->dbh);
+
+        return $node;
+       }
+
+       //      }}}
+
+       //      {{{     getListSize()
+
+    /**
+     * Get how many nodes are currently in the linked list
+     *
+     * @param boolean $filterPending Include pending packages in the count
+        *
+     * @return integer number of nodes in the linked list
+     * @access public
+     */
+       public function getListSize($filterPending = false)
+       {
+               $size = 0;
+               $cur  = $this->rewind();
+
+               //      If the current node is null, then we have no nodes
+               //      in the linked list.  return the empty size.
+               //      Else we have at least one node in the linked list.
+               if (is_null($cur)) {
+                       return $size;
+               }
+
+               //      Add one to the size of the list for every
+               //      node we encounter.
+               do {
+                       if ($filterPending) {
+                               if (!$cur->getPending()) {
+                                       ++$size;
+                               }
+                       } else {
+                               ++$size;
+                       }
+               } while ($cur = $this->next());
+
+               return $size;
+       }
+
+       //      }}}
+       //      {{{     getMemberId()
+
+    /**
+     * Get which member this linked list is for
+     *
+     * @return integer id of member we are dealing with
+     * @access public
+     */
+       public function getMemberId()
+       {
+               return $this->mid;
+       }
+
+       //      }}}
+
+       //      {{{     findNode()
+
+    /**
+     * find a node from the linked list
+     *
+     * @param integer $target Id of package you are searching for
+        *
+     * @return mixed Toolkit_Members_Packages_Package if present, else false
+     * @access public
+     */
+       public function &findNode($target)
+       {
+               $this->end();
+               $startingId = $this->current->getId();
+
+               if ($target == $startingId) {
+                       return $this->current;
+               }
+
+               while ($curr = $this->previous()) {
+                       if ($target == $curr->getId()) {
+                               return $curr;
+                       }
+               }
+
+               return false;
+       }
+
+       //      }}}
+
+       //      {{{     moveNode()
+
+    /**
+     * Adjust nodes position in the linked list
+     *
+     * @param integer $pid id of package you want to move
+     * @param integer $pos new position you want to move to
+        *
+     * @access public
+     * @return void
+     */
+       public function moveNode($pid, $pos)
+       {
+               $node   = $this->findNode($pid);
+               $oldPos = $node->getPosition();
+
+               if ($this->getListSize()) {
+                       $cur = $this->rewind();
+                       do {
+                               if ($cur->getId() == $pid) {
+                                       $cur->setPosition($pos);
+                               } else {
+                                       $curPos = $cur->getPosition();
+                                       if ($pos > $oldPos) {
+                                               if ($curPos <= $pos && $curPos > $oldPos) {
+                                                       $cur->setPosition($curPos - 1);
+                                               }
+                                       } elseif ($pos < $oldPos) {
+                                               if ($curPos >= $pos && $curPos < $oldPos) {
+                                                       $cur->setPosition($curPos + 1);
+                                               }
+                                       }
+                               }
+                       } while ($cur = $this->next());
+               }
+       }
+
+       //      }}}
+
+       //      {{{     removeNode()
+
+    /**
+     * Removes a node from the linked list
+     *
+     * @param Toolkit_Image_Server $is     Image Server Object
+     * @param integer              $target Id of package you want to remove
+        *
+     * @return boolean false on error
+     * @access public
+     */
+       public function removeNode(Toolkit_Image_Server $is, $target)
+       {
+               $node = $this->findNode($target);
+               if (!$node) {
+                       return false;
+               }
+
+               $node->remove($is);
+               $remNodePos = $node->getPosition();
+
+               //      only try and update positions in the linked list if     there are nodes that
+               //      will still exists after this node is removed ie.  size is greater than 1
+               if ($this->getListSize() > 1) {
+                       $cur = $this->rewind();
+                       do {
+                               if ($cur->getPosition() > $remNodePos) {
+                                       $cur->setPosition($cur->getPosition() - 1);
+                               }
+                       } while ($cur = $this->next());
+               }
+
+               $this->deleteNode($node);
+       }
+
+       //      }}}
+
+    //  {{{ setDbh()
+
+    /**
+     * Set the Database Handler
+     *
+     * @param PDO $pdo PHP Data Object to use
+     *
+     * @return void
+     * @access public
+     */
+    public function setDbh(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+
+    //  }}}
+       //      {{{     setMember()
+
+    /**
+     * Sets which member we are working with
+     *
+     * @param integer $mid id of member
+        *
+     * @access public
+     * @return PEAR error on invalid member id
+     */
+       public function setMember($mid)
+       {
+        if (is_integer($mid)) {
+            $this->mid = $mid;
+        } elseif (is_numeric($mid) && ctype_digit($mid)) {
+                       $this->mid = $mid;
+               } else {
+            return PEAR::raiseError('invalid member id');
+        }
+       }
+
+       //      }}}
+
+       //      {{{     emptyList()
+
+    /**
+     * Deletes all nodes from a list
+     *
+     * @access public
+     * @return void
+     */
+       public function emptyList()
+       {
+               $this->end();
+               while ($cur = $this->current()) {
+                       $this->deleteNode($cur);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Packages/Package.php b/Toolkit/Members/Packages/Package.php
new file mode 100644 (file)
index 0000000..b4a49ae
--- /dev/null
@@ -0,0 +1,377 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Node class for the member packages linked list implementation
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Package.php,v 1.7 2010/05/25 14:01:22 jamie Exp $
+ * @link      <>
+ * @see       Structures/LinkedList/Double.php
+ *                               Toolkit/Image/Server.php
+ */
+
+/**
+ * Linked list node class
+ *
+ * Handles controlling all functionality for a linked list node
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      <>
+ * @see       Structures_LinkedList_DoubleNode
+ */
+class Toolkit_Members_Packages_Package extends Structures_LinkedList_DoubleNode
+{
+       //      {{{     properties
+
+    /**
+     * Database handler object
+     * @var    object
+     * @access public
+     */
+       public $dbh;
+
+    /**
+     * Tuple id of package in db
+     * @var    integer
+     * @access protected
+     */
+       protected $id;
+
+    /**
+     * Image name on image server
+     * @var    string
+     * @access protected
+     */
+       protected $image;
+
+    /**
+     * Packages position in the linked list / db
+     * @var    integer
+     * @access protected
+     */
+       protected $pos;
+
+    /**
+     * If the package is new and is still pending
+     * @var    boolean
+     * @access protected
+     */
+       protected $pending;
+
+    /**
+     * Member id this package belongs to
+     * @var    integer
+     * @access protected
+     */
+       protected $mid;
+
+    /**
+     * DB table name where package data is stored
+     * @var    string
+     * @access protected
+     */
+       protected $tableName = 'member_packages';
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Class Constructor
+     *
+     * @param array $data new node data
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(array $data)
+       {
+               $this->id      = $data['id'];
+               $this->image   = $data['image'];
+               $this->title   = $data['title'];
+               $this->pos     = $data['pos'];
+               $this->pending = $data['pending'];
+               $this->mid     = $data['member_id'];
+       }
+
+       //      }}}
+
+       //      {{{     setFauxPending()
+
+    /**
+     * Make the package pending, but don't set it to pending in the DB
+     *
+        * This is useful in the members only area when only part of a
+        * package is pending but you need to show the entire package in a pending
+        * state.  ie (titles can be pending)
+        *
+     * @param boolean $pending what to set the pending status to
+        *
+     * @return void
+     * @access public
+     */
+       public function setFauxPending($pending)
+       {
+               $this->pending = $pending;
+       }
+
+       //      }}}
+
+       //      {{{     getTitle()
+
+    /**
+     * Get the package title
+     *
+     * @return string packages title
+     * @access public
+     */
+       public function getTitle()
+       {
+               return $this->title;
+       }
+
+       //      }}}
+       //      {{{     getPendingTitle()
+
+    /**
+     * Get the packages pending title (if set)
+     *
+     * @return string packages pending title
+     * @access public
+     */
+       public function getPendingTitle()
+       {
+               return $this->pendingTitle;
+       }
+
+       //      }}}
+       //      {{{     getId()
+
+    /**
+     * Get the package id
+     *
+     * @return integer packages db id
+     * @access public
+     */
+       public function getId()
+       {
+               return $this->id;
+       }
+
+       //      }}}
+       //      {{{     getImage()
+
+    /**
+     * Get the package image name
+     *
+     * @return string file name of image stored on image server
+     * @access public
+     */
+       public function getImage()
+       {
+               return $this->image;
+       }
+
+       //      }}}
+       //      {{{     getPending()
+
+    /**
+     * Get the pending status of the package
+     *
+     * @return boolean if the package is pending or not
+     * @access public
+     */
+       public function getPending()
+       {
+               return $this->pending;
+       }
+
+       //      }}}
+       //      {{{     getPosition()
+
+    /**
+     * Get the position of the package
+     *
+     * @return integer current position in the linked list / db of the package
+     * @access public
+     */
+       public function getPosition()
+       {
+               return $this->pos;
+       }
+
+       //      }}}
+
+       //      {{{     remove()
+
+    /**
+     * Remove a package from the db
+     *
+        * Handles deleting all data from the member_packages table and any
+        * data that might currently be pending for the package as well.
+     *
+     * @param Toolkit_Image_Server $is Image Server object
+     *
+     * @return boolean false on error
+     * @access public
+     */
+       public function remove(Toolkit_Image_Server $is)
+       {
+               try {
+                       $is->imageDelete($this->image);
+                       //      Get rid of the package in the member_packages table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE id = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute(array($this->id));
+
+                       //      Get rid of any updates to the package so we don't have
+                       //      orphaned data lying around.
+                       $sql = "
+                DELETE FROM " . Toolkit_Membersonly::PENDING_TABLE . "
+                 WHERE db_table    = '{$this->tableName}'
+                   AND member_id   = :member_id
+                   AND foreign_key = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':id', $this->id, PDO::PARAM_INT);
+                       $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ setDbh()
+
+    /**
+     * Set the Database handler object
+     *
+     * @param PDO $pdo PHP Data Object
+     *
+     * @return void
+     * @access public
+     */
+    public function setDbh(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+
+    //  }}}
+       //      {{{     setPending()
+
+    /**
+     * Set the pending status for the package
+     *
+     * @param boolean $pending If the package is pending or not
+        *
+     * @return boolean result of db update
+     * @access public
+     */
+       public function setPending($pending)
+       {
+               $this->pending = $pending;
+               try {
+                       $sql = "
+                UPDATE {$this->tableName}
+                   SET pending   = ?
+                 WHERE member_id = ?
+                   AND id        = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       return $stmt->execute(array($pending, $this->mid, $this->id));
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setPendingData()
+
+    /**
+     * Set the content of any data that might be pending
+     *
+     * Currently this only supports pending title
+     *
+     * @return bolean false on error
+     * @access public
+     */
+       public function setPendingData()
+       {
+               try {
+                       //      Get any updates for that package that are still in
+                       //      a pending status.
+                       $sql = "
+                               SELECT *
+                                 FROM " . Toolkit_Membersonly::PENDING_TABLE . "
+                                WHERE id in (
+                                       SELECT max(id)
+                                         FROM " . Toolkit_Membersonly::PENDING_TABLE . "
+                                        WHERE foreign_key = :foreign_key
+                                          AND db_table = 'member_packages'
+                                        GROUP BY field)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute(array($this->id));
+                       $row = $stmt->fetch();
+
+                       if ($row['field'] == 'title') {
+                               $this->pendingCaption = $row['update'];
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setPosition()
+
+    /**
+     * Set a new position for a node
+     *
+     * Handle updating the nodes position in the linked list as well as db.
+     *
+     * @param integer $pos new position number for node
+        *
+     * @return boolean result of position update
+     * @access public
+     */
+       public function setPosition($pos)
+       {
+               //      Not updating anything so just return.
+               if ($pos == $this->pos) {
+                       return true;
+               }
+               try {
+                       $this->pos = $pos;
+
+                       $sql = "
+                UPDATE {$this->tableName}
+                   SET pos       = ?
+                 WHERE member_id = ?
+                   AND id        = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       return $stmt->execute(array($pos, $this->mid, $this->id));
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Photos.php b/Toolkit/Members/Photos.php
new file mode 100644 (file)
index 0000000..c5cfb42
--- /dev/null
@@ -0,0 +1,349 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Linked list (LL) implementation of member photos
+ *
+ * File contains the class that gives the ability to create a linked list
+ * of member photos.  You can iterate through manipulate and control every
+ * aspect of the LL.  The best part is, by keeping the LL in order it
+ * automatically maintains the DB for you.
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Photos.php,v 1.13 2010/05/25 14:01:18 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Structures/LinkedList/Double.php
+ *                       Toolkit/Members/Photos/Photo.php
+ */
+
+/**
+ * Class implementation of a linked list
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Structures/LinkedList/Double.php
+ */
+class Toolkit_Members_Photos extends Structures_LinkedList_Double
+{
+       //      {{{     properties
+
+    /**
+     * DB id of member whos photos we are manipulating with this linked list
+     * @var    integer
+     * @access protected
+     */
+       protected $mid;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param Structures_LinkedList_DoubleNode $root Linked List node object
+     * @param integer                          $mid  id of member we want
+     *                                               to prepare the list for
+        *
+     * @access public
+     * @return void
+     */
+       function __construct(
+        Structures_LinkedList_DoubleNode $root = null,
+        $mid = null
+    ) {
+               parent::__construct($root);
+               $this->setMember($mid);
+        /*
+               if (is_numeric($mid)) {
+                       $this->createMemberList($mid);
+               }
+        */
+       }
+
+       //      }}}
+
+       //      {{{     createMemberList()
+
+    /**
+     * Creates a linked list from all the photos a member has in the db.
+     *
+     * @param PDO              $dbh   PHP Data Object
+     * @param Config_Container $c     Member configuration
+     * @param string           $order The order to make the linked list in
+        *
+     * @return boolean false on error
+     * @access public
+     */
+       public function createMemberList(
+        PDO $dbh,
+        Config_Container $c,
+        $order = 'pos'
+    ) {
+               if (!ctype_digit((string) $this->mid)) {
+                       return;
+               }
+
+        //  Make sure the list is actually empty before you recreate it
+        //  otherwise you can end up w/ duplicate values in the LL
+        $this->emptyList();
+
+               $safeOrder = array('pos', 'id');
+               if (!in_array($order, $safeOrder)) {
+                       $order = 'pos';
+               }
+               try {
+                       //      Get each photo tuple from the member_photos table.
+                       $sql = "
+                               SELECT *
+                                 FROM member_photos
+                                WHERE member_id = :member_id
+                                ORDER BY $order";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $this->mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch()) {
+                               //      Create a new node w/ all the data we just extracted.
+                               $node = $this->createNode($row);
+                $node->setDbh($dbh);
+                               //      Sets up any pending data the photo might currently have.
+                               $node->setPendingData($c);
+                               //      Add the photo node to the end of the linked list.
+                               $res = $this->appendNode($node);
+                       }
+
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     createNode()
+
+    /**
+     * Creates a new linked list node object
+     *
+     * @param array $data Data to populate the new node with
+        *
+     * @return Toolkit_Members_Photos_Photo linked list node
+     * @access public
+     */
+       public function &createNode(array $data)
+       {
+               return new Toolkit_Members_Photos_Photo($data);
+       }
+
+       //      }}}
+
+       //      {{{     getListSize()
+
+    /**
+     * Get how many nodes are currently in the linked list
+     *
+     * @param boolean $filterPending Include pending photos in the count
+        *
+     * @return integer number of nodes in the linked list
+     * @access public
+     */
+       public function getListSize($filterPending = false)
+       {
+               $size = 0;
+               $cur  = $this->rewind();
+
+               //      If the current node is null, then we have no nodes
+               //      in the linked list.  return the empty size.
+               //      Else we have at least one node in the linked list.
+               if (is_null($cur)) {
+                       return $size;
+               }
+
+               //      Add one to the size of the list for every
+               //      node we encounter.
+               do {
+                       if ($filterPending) {
+                               if (!$cur->getPending()) {
+                                       ++$size;
+                               }
+                       } else {
+                               ++$size;
+                       }
+               } while ($cur = $this->next());
+
+               return $size;
+       }
+
+       //      }}}
+       //      {{{     getMemberId()
+
+    /**
+     * Get which member this linked list is for
+     *
+     * @return integer id of member we are dealing with
+     * @access public
+     */
+       public function getMemberId()
+       {
+               return $this->mid;
+       }
+
+       //      }}}
+
+       //      {{{     findNode()
+
+    /**
+     * find a node from the linked list
+     *
+     * @param integer $target Id of photo you are searching for
+        *
+     * @return mixed Toolkit_Members_Photos_Photo object if present, else false
+     * @access public
+     */
+       public function &findNode($target)
+       {
+               $this->end();
+               $startingId = $this->current->getId();
+
+               if ($target == $startingId) {
+                       return $this->current;
+               }
+
+               while ($curr = $this->previous()) {
+                       if ($target == $curr->getId()) {
+                               return $curr;
+                       }
+               }
+
+               return false;
+       }
+
+       //      }}}
+
+       //      {{{     moveNode()
+
+    /**
+     * Adjust nodes position in the linked list
+     *
+     * @param integer $pid id of photo you want to move
+     * @param integer $pos new position you want to move to
+        *
+     * @return void
+     * @access public
+     */
+       public function moveNode($pid, $pos)
+       {
+               $node   = $this->findNode($pid);
+               $oldPos = $node->getPosition();
+
+               if ($this->getListSize()) {
+                       $cur = $this->rewind();
+                       do {
+                               if ($cur->getId() == $pid) {
+                                       $cur->setPosition($pos);
+                               } else {
+                                       $curPos = $cur->getPosition();
+                                       if ($pos > $oldPos) {
+                                               if ($curPos <= $pos && $curPos > $oldPos) {
+                                                       $cur->setPosition($curPos - 1);
+                                               }
+                                       } elseif ($pos < $oldPos) {
+                                               if ($curPos >= $pos && $curPos < $oldPos) {
+                                                       $cur->setPosition($curPos + 1);
+                                               }
+                                       }
+                               }
+                       } while ($cur = $this->next());
+               }
+       }
+
+       //      }}}
+
+       //      {{{     removeNode()
+
+    /**
+     * Removes a node from the linked list
+     *
+     * @param Toolkit_Image_Server $is     Image Server Object
+     * @param Config_Container     $c      Member configuration
+     * @param integer              $target Id of photo you want to remove
+        *
+     * @return boolean false on error
+     * @access public
+     */
+       public function removeNode(
+        Toolkit_Image_Server $is,
+        Config_Container $c,
+        $target
+    ) {
+               $node = $this->findNode($target);
+               if (!$node) {
+                       return false;
+               }
+
+               $node->remove($is, $c);
+               $remNodePos = $node->getPosition();
+
+               //      only try and update positions in the linked list if     there are nodes that
+               //      will still exists after this node is removed ie.  size is greater than 1
+               if ($this->getListSize() > 1) {
+                       $cur = $this->rewind();
+                       do {
+                               if ($cur->getPosition() > $remNodePos) {
+                                       $cur->setPosition($cur->getPosition() - 1);
+                               }
+                       } while ($cur = $this->next());
+               }
+
+               $this->deleteNode($node);
+       }
+
+       //      }}}
+
+       //      {{{     setMember()
+
+    /**
+     * Sets which member we are working with
+     *
+     * @param integer $mid id of member
+        *
+     * @access public
+     * @return void
+     */
+       public function setMember($mid)
+       {
+               if (ctype_digit((string) $mid)) {
+                       $this->mid = $mid;
+               }
+       }
+
+       //      }}}
+
+       //      {{{     emptyList()
+
+    /**
+     * Deletes all nodes from a list
+     *
+     * @access public
+     * @return void
+     */
+       public function emptyList()
+       {
+               $this->end();
+               while ($cur = $this->current()) {
+                       $this->deleteNode($cur);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Photos/Photo.php b/Toolkit/Members/Photos/Photo.php
new file mode 100644 (file)
index 0000000..cdf46a6
--- /dev/null
@@ -0,0 +1,440 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Node class for the member photos linked list implementation
+ * 
+ * PHP version 5
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: Photo.php,v 1.9 2009/09/16 10:48:10 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Structures/LinkedList/Double.php
+ *                       Toolkit/Image/Server.php
+ */
+
+/**
+ * PEAR linked list library
+ */
+require_once 'Structures/LinkedList/Double.php';
+
+/**
+ * Class to handle uploading and processing of images on the image server
+ */
+require_once BASE . 'Toolkit/Image/Server.php';
+
+/**
+ * Linked list node class
+ * 
+ * Handles controlling all functionality for a linked list node
+ * 
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Structures_LinkedList_DoubleNode
+ */
+class Toolkit_Members_Photos_Photo extends Structures_LinkedList_DoubleNode
+{
+       //      {{{     properties
+
+    /**
+     * Database handler object
+     * @var    object
+     * @access public
+     */
+       public $dbh;
+
+    /**
+     * Tuple id of photo in db
+     * @var    integer
+     * @access protected
+     */
+       protected $id;
+
+    /**
+     * Image name on image server
+     * @var    string
+     * @access protected
+     */
+       protected $image;
+
+    /**
+     * Photo caption
+     * @var    string
+     * @access protected
+     */
+       protected $caption;
+
+    /**
+     * Photo pending caption (if set)
+     * @var    string
+     * @access protected
+     */
+       protected $pendingCaption;
+
+    /**
+     * Photos position in the linked list / db
+     * @var    integer
+     * @access protected
+     */
+       protected $pos;
+
+    /**
+     * If the photo is new and is still pending
+     * @var    boolean
+     * @access protected
+     */
+       protected $pending;
+
+    /**
+     * Member id this photo belongs to
+     * @var    integer
+     * @access protected
+     */
+       protected $mid;
+
+    /**
+     * DB table name where photo data is stored
+     * @var    string   
+     * @access protected
+     */
+       protected $tableName = 'member_photos';
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Class Constructor
+     * 
+     * @param array $data new node data
+        *
+     * @return void  
+     * @access public
+     */
+       public function __construct(array $data)
+       {
+               $this->id      = $data['id'];
+               $this->image   = $data['image'];
+               $this->caption = $data['caption'];
+               $this->pos     = $data['pos'];
+               $this->pending = $data['pending'];
+               $this->mid     = $data['member_id'];
+       }
+
+       //      }}}
+
+       //      {{{     setFauxPending()
+
+    /**
+     * Make the photo pending, but don't set it to pending in the DB
+     * 
+        * This is useful in the members only area when only part of a
+        * photo is pending but you need to show the entire photo in a pending
+        * state.  ie (captions can be pending)
+        *
+     * @param boolean $pending what to set the pending status to
+        *
+     * @return void   
+     * @access public 
+     */
+       public function setFauxPending($pending)
+       {
+               $this->pending = $pending;
+       }
+
+       //      }}}
+
+       //      {{{     getCaption()
+
+    /**
+     * Get the photo caption
+     * 
+     * @return string photos caption
+     * @access public 
+     */
+       public function getCaption()
+       {
+               return $this->caption;
+       }
+       
+       //      }}}
+       //      {{{     getPendingCaption()
+
+    /**
+     * Get the photos pending caption (if set)
+     * 
+     * @return string photos pending caption
+     * @access public 
+     */
+       public function getPendingCaption()
+       {
+               return $this->pendingCaption;
+       }
+       
+       //      }}}
+       //      {{{     getId()
+
+    /**
+     * Get the photo id
+     * 
+     * @return integer photos db id
+     * @access public 
+     */
+       public function getId()
+       {
+               return $this->id;
+       }
+
+       //      }}}
+       //      {{{     getImage()
+
+    /**
+     * Get the photo image name
+     * 
+     * @return string file name of image stored on image server
+     * @access public 
+     */
+       public function getImage()
+       {
+               return $this->image;
+       }
+
+       //      }}}
+       //      {{{     getPending()
+
+    /**
+     * Get the pending status of the photo
+     * 
+     * @return boolean if the photo is pending or not
+     * @access public 
+     */
+       public function getPending()
+       {
+               return $this->pending;
+       }
+
+       //      }}}
+       //      {{{     getPosition()
+
+    /**
+     * Get the position of the photo
+     * 
+     * @return integer current position in the linked list / db of the photo
+     * @access public 
+     */
+       public function getPosition()
+       {
+               return $this->pos;
+       }
+
+       //      }}}
+
+       //      {{{     remove()
+
+    /**
+     * Remove a photo from the db
+     * 
+        * Handles deleting all data from the member_photos table and any
+        * data that might currently be pending for the photo as well.
+     * 
+     * @param Toolkit_Image_Server $is Image Server object
+     * @param Config_Container     $c  Member Configuration
+     *
+     * @return boolean false on error
+     * @access public 
+     */
+       public function remove(Toolkit_Image_Server $is, Config_Container $c)
+       {
+               try {
+                       $is->imageDelete($this->image);
+                       //      Get rid of the photo in the member_photos table.
+                       $sql = "
+                DELETE FROM {$this->tableName}
+                 WHERE id = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute(array($this->id));
+
+            $config = $c->getItem('section', 'tables');
+            $pendingTable = $config->getItem('directive', 'pendingTable');
+
+                       //      Get rid of any updates to the photo so we don't have
+                       //      orphaned data lying around.
+                       $sql = "
+                DELETE FROM {$pendingTable->getContent()}
+                 WHERE db_table    = '{$this->tableName}'
+                   AND member_id   = :member_id
+                   AND foreign_key = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                       $stmt->bindParam(':id', $this->id, PDO::PARAM_INT);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     setCaption()
+
+    /**
+     * Set the caption for the photo
+     * 
+     * @param string $caption new caption text
+        *
+     * @return boolean result of db update
+     * @access public 
+     */
+       public function setCaption($caption)
+       {
+               $this->caption = $caption;
+               try {
+                       $sql = "
+                UPDATE {$this->tableName}
+                   SET caption   = ?
+                 WHERE member_id = ?
+                   AND id        = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       return $stmt->execute(array($caption, $this->mid, $this->id));
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+    //  {{{ setDbh()
+
+    /**
+     * sets the database handler object
+     *
+     * using dependecy injection to help testing this application
+     *
+     * @param PDO $pdo PHP Data Object used for DB calls.
+     *
+     * @return void
+     * @access public
+     */
+    public function setDbh(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+
+    //  }}}
+       //      {{{     setPending()
+
+    /**
+     * Set the pending status for the photo
+     * 
+     * @param boolean $pending If the photo is pending or not
+        *
+     * @return boolean result of db update
+     * @access public 
+     */
+       public function setPending($pending)
+       {
+               $this->pending = $pending;
+               try {
+                       $sql = "
+                UPDATE {$this->tableName}
+                   SET pending   = ?
+                 WHERE member_id = ?
+                   AND id        = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       return $stmt->execute(array($pending, $this->mid, $this->id));
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setPendingData()
+
+    /**
+     * Set the content of any data that might be pending
+     * 
+     * Currently this only supports pending caption
+     *
+     * @param Config_Container $c Member configuration
+     * 
+     * @return bolean false on error
+     * @access public 
+     */
+       public function setPendingData(Config_Container $c)
+       {
+        $config = $c->getItem('section', 'tables');
+        $pendingTable = $config->getItem('directive', 'pendingTable');
+
+               try {
+                       //      Get any updates for that photo that are still in 
+                       //      a pending status.
+                       $sql = "
+                               SELECT *
+                                 FROM {$pendingTable->getContent()}
+                                WHERE id in (
+                                       SELECT max(id)
+                                         FROM {$pendingTable->getContent()}
+                                        WHERE foreign_key = :foreign_key
+                                          AND db_table = 'member_photos'
+                                        GROUP BY field)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute(array($this->id));
+                       $row = $stmt->fetch();
+
+                       if ($row['field'] == 'caption') {
+                               $this->pendingCaption = $row['update'];
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setPosition()
+
+    /**
+     * Set a new position for a node
+     * 
+     * Handle updating the nodes position in the linked list as well as db.
+     * 
+     * @param integer $pos new position number for node
+        *
+     * @return boolean result of position update
+     * @access public 
+     */
+       public function setPosition($pos)
+       {
+               //      Not updating anything so just return.
+               if ($pos == $this->pos) {
+                       return true;
+               }
+               try {
+                       $this->pos = $pos;
+
+                       $sql = "
+                UPDATE {$this->tableName}
+                   SET pos       = ?
+                 WHERE member_id = ?
+                   AND id        = ?";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       return $stmt->execute(array($pos, $this->mid, $this->id));
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/ProfilePage.php b/Toolkit/Members/ProfilePage.php
new file mode 100644 (file)
index 0000000..b666875
--- /dev/null
@@ -0,0 +1,859 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Member Profile Page
+ *
+ * PHP version 5
+ *
+ * @category  MemberDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: ProfilePage.php,v 1.17 2010/08/15 19:34:33 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Generates Member profile pages
+ *
+ * @category  MemberDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_ProfilePage
+{
+    //  {{{ properties
+
+    /**
+     * Database handler
+     * @var    object
+     * @access protected
+     */
+    protected $dbh;
+
+    /**
+     * Page catid
+     * @var    integer
+     * @access private
+     */
+    private $_catid;
+
+    /**
+     * Member Id to get profile for
+     * @var    integer
+     * @access private
+     */
+    private $_mid;
+
+    /**
+     * Toolbox page gateway
+     * @var    integer
+     * @access private
+     */
+    private $_pageGateway;
+
+    //  }}}
+    //  {{{ __construct()
+
+    /**
+     * constructor
+     *
+     * @param PDO                                 $pdo         Database handler
+     * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway DB page gateway
+     * @param integer                             $mid         Member to get profile for
+     *
+     * @return void
+     * @access public
+     */
+    public function __construct(
+               PDO $pdo,
+               Toolkit_Toolbox_PageGatewayAbstract $pageGateway,
+               $mid
+       ) {
+        $this->dbh          = $pdo;
+        $this->_pageGateway = $pageGateway;
+        $this->setMemberId($mid);
+    }
+
+    //  }}}
+
+       //      {{{     _isNewMember()
+
+       /**
+        * Determines if we are dealing w/ a new member from the addyourbusiness form
+        *
+        * @return boolean
+        * @access private
+        */
+       private function _isNewMember()
+       {
+               try {
+                       $sql = "
+                SELECT new_member
+                  FROM member
+                 WHERE member_id = :mid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('new_member', $isNew);
+                       $stmt->fetch();
+
+                       return (bool) $isNew;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     getMemberId()
+
+    /**
+     * Description for getMemberId()
+     *
+     * @return integer
+     */
+       public function getMemberId()
+       {
+               return $this->_mid;
+       }
+
+       //      }}}
+       //      {{{     memberActive()
+
+       /**
+        * Check to make sure the member is active in the DB.
+        *
+        * @return boolean true or false if the member is active
+        * @access private
+        */
+       private function _memberActive()
+    {
+               if (!filter_var($this->_mid, FILTER_VALIDATE_INT)) {
+            return false;
+        }
+
+               try {
+                       $sql = "
+                SELECT CASE
+                       WHEN active THEN 1
+                       ELSE 0
+                       END AS active
+                  FROM member
+                 WHERE member_id = :member_id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('active', $active);
+                       $stmt->fetch();
+
+                       return (bool) $active;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     memberExists()
+
+       /**
+        * Check to make sure the member exists in the database
+        *
+        * @return boolean true or false if the member exists
+        * @access private
+        */
+       private function _memberExists()
+    {
+               if (!filter_var($this->_mid, FILTER_VALIDATE_INT)) {
+            return false;
+        }
+
+               try {
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM member
+                                WHERE member_id = :member_id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('total', $total);
+                       $stmt->fetch();
+
+                       return (bool) $total;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ setCatId()
+
+    /**
+     * Set the catid for the page
+     *
+     * @param integer $catid page id from db
+     *
+     * @return void
+     * @access public
+     * @throws InvalidArgumentException on invalid member id
+     */
+    public function setCatId($catid)
+    {
+               if (filter_var($catid, FILTER_VALIDATE_INT)) {
+            $this->_catid = $catid;
+        } else {
+            $this->_catid = null;
+            throw new InvalidArgumentException("Invalid catid `$catid`");
+        }
+    }
+
+    //  }}}
+    //  {{{ setConfig()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function setConfig(Config_Container $c)
+    {
+        $this->config = $c;
+    }
+
+    //  }}}
+    //  {{{ setImagePath()
+
+    /**
+     * Sets the path to use for images
+     *
+     * @param string $imagePath File server image path url
+     *
+     * @return void
+     * @access public
+     */
+    public function setImagePath($imagePath)
+    {
+        $this->imagePath = $imagePath;
+    }
+
+    //  }}}
+       //      {{{     setMemberAccommodations()
+
+    /**
+     * Get all the member accommodation info
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberAccommodations(&$page)
+       {
+               try {
+                       //      Check to see if there are any rows in the
+            //  member_accommodations table that are linked to this
+            //  member. If there are, then we know this member
+                       //      needs the hotel section
+                       $sql = "
+                SELECT reservation_url, reservation_id, num_rooms, year_round
+                  FROM member_accommodations
+                 WHERE member_id = :mid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $accommodations = array_filter($row);
+            }
+
+            $page->has_accommodations    = !empty($accommodations);
+            $page->does_online_reservations
+                               = (   !is_null($accommodations['reservation_id'])
+                                  || !is_null($accommodations['reservation_url'])
+                                 );
+            $page->reservation_id        = $accommodations['reservation_id'];
+            $page->reservation_url       = $accommodations['reservation_url'];
+            $page->lists_number_of_rooms = !is_null($accommodations['num_rooms']);
+            $page->num_rooms             = $accommodations['num_rooms'];
+            $page->year_round            = $accommodations['year_round'];
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberAmenities()
+
+    /**
+     * Get all the member amenity info
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberAmenities(&$page)
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM amenity
+                                WHERE amenity_id in (
+                                               SELECT amenity_id
+                                                 FROM member_amenity
+                                                WHERE member_id = :mid)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch()) {
+                               $page->amenities[] = $row['amenity_name'];
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberCCards()
+
+    /**
+     * Get all the member Credit Card info
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberCCards(&$page)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM ccard_type
+                 WHERE ccard_type_id in (
+                                               SELECT ccard_type_id
+                                                 FROM member_ccard_type
+                                                WHERE member_id = :mid)";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       while ($row = $stmt->fetch()) {
+                               $page->ccards[] = $row['ccard_type_name'];
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberDetail()
+
+    /**
+     * Get the member profile page
+     *
+     * @param stdClass $page controller object used with the template
+        *
+     * @return string html string of member profile page
+     * @access public
+     */
+       public function setMemberDetail(stdClass $page)
+       {
+        if (!$this->_validMember()) {
+            return false;
+        }
+
+               $this->profile =& $page;
+
+               $page->image_path   = $this->imagePath;
+               $page->base_url     = BASE_URL;
+        $page->glm_base_url = GLM_APP_BASE_URL;
+
+               $this->setMemberInfo($page);
+               $this->setMemberPhotos($page);
+               $this->setMemberAccommodations($page);
+               $this->setMemberAmenities($page);
+               $this->setMemberCCards($page);
+               $this->setMemberSocialMedia($page);
+               $this->setMemberFiles($page);
+               $this->setMemberPackages($page);
+               $this->setMemberGolf($page);
+               $this->setMemberRestaurant($page);
+
+        $page->show_attributes = (   $page->has_accommodations
+                                                                 || $page->has_social_media
+                                                                 || is_array($page->ccards));
+       }
+
+       //      }}}
+       //      {{{     setMemberFiles()
+
+    /**
+     * Get all the file data for the the member profile being looked at
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberFiles(&$page)
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM member_files
+                                WHERE member_id = :mid
+                                  AND NOT pending";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $count = 0;
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $page->files[$count]['href']
+                                       = BASE_URL . "member-file/{$this->_mid}/{$row['id']}/";
+                               $page->files[$count]['name']
+                                       = empty($row['file_name']) ?
+                                       $row['original_name'] :
+                                       $row['file_name'];
+                               ++$count;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberGolf()
+
+    /**
+     * Get all the golf data for the the member profile being looked at
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberGolf(&$page)
+       {
+               try {
+                       $sql = "
+                               SELECT column_name, data_type
+                                 FROM information_schema.columns
+                                WHERE table_name = 'member_golf'";
+
+                       $tableData = $this->dbh->query($sql)->fetchAll();
+
+                       $sql = "
+                               SELECT *
+                                 FROM member_golf
+                                WHERE member_id = :mid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       if ($row = $stmt->fetch()) {
+                               $show = false;
+                               foreach ($tableData as $td) {
+                                       switch ($td['data_type']) {
+                                       case 'radio' :
+                                       case 'boolean' :
+                                               $golf[$td['column_name']] = ($row[$td['column_name']] == 't') ? 'Yes': 'No';
+                                               break;
+
+                                       case 'integer' :
+                                               break;
+
+                                       case 'text' :
+                                       default :
+                                               $golf[$td['column_name']] = $row[$td['column_name']];
+                                               if (!empty($row[$td['column_name']])) {
+                                                       $show = true;
+                                               }
+                                               break;
+                                       }
+                               }
+
+                $page->golf_info      = $show;
+                $page->par            = $golf['par'];
+                $page->yardage        = $golf['yardage'];
+                $page->course_rating  = $golf['course_rating'];
+                $page->slope_rating   = $golf['slope_rating'];
+                $page->walking_course = $golf['walking_course'];
+                $page->holes18        = $golf['holes18'];
+                $page->holes9         = $golf['holes9'];
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+    //  {{{ setMemberId()
+
+    /**
+     * Set a new member id
+     *
+     * @param integer $mid member id to set
+     *
+     * @return void
+     * @access public
+     * @throws PEAR_Exception Error on invalid member id
+     */
+    public function setMemberId($mid)
+    {
+               if ($mid = filter_var($mid, FILTER_VALIDATE_INT)) {
+            $this->_mid = $mid;
+        } else {
+            $this->_mid = null;
+            throw new PEAR_Exception('Invalid Member Id');
+        }
+    }
+
+    //  }}}
+       //      {{{     setMemberInfo()
+
+    /**
+     * Set the record data stored in the database for the template
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberInfo(&$page)
+       {
+               try {
+                       $sql = "
+                SELECT m.*, c.city_name, s.state_name,
+                       s.state_abb AS state_abbr
+                  FROM member m JOIN city c USING (city_id), state s
+                 WHERE m.member_id = :mid
+                   AND m.state_id  = s.state_id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+
+            if (!empty($row['logo'])) {
+                $page->logo = $row['logo'];
+            }
+
+            $page->member_name = $row['member_name'];
+            $page->street      = $row['street'];
+            //  get reference to [listing type] section of config file
+            $config =& $this->config->getItem('section', 'conf');
+            $ctrlCtyD =& $config->getItem('directive', 'controlledCities');
+            if ($ctrlCtyD->getContent()) {
+                $page->city = $row['city_name'];
+            } else {
+                $page->city = $row['city'];
+            }
+            $page->state_name  = $row['state_name'];
+            $page->state_abbr  = $row['state_abbr'];
+            $page->zip         = $row['zip'];
+            $page->phone       = $row['phone'];
+            $page->toll_free   = $row['toll_free'];
+            $page->fax         = $row['fax'];
+            $page->email       = $row['member_contact_email'];
+            if (strpos($row['url'], 'http://') === false) {
+                $row['url'] = 'http://' . $row['url'];
+            }
+            $page->url         = $row['url'];
+
+                       //      handle if we should be showing mailing addresses
+                       //      on the member profile or not.
+                       $mailingAddyD
+                               =& $config->getItem('directive', 'showMailingAddress');
+                       if ($mailingAddyD->getContent()) {
+                               $sql = "
+                                       SELECT c.city_name AS mailing_city_name, s.state_name AS
+                                              mailing_state_name, s.state_abb AS mailing_state_abbr
+                      FROM member m, city c, state s
+                     WHERE m.member_id        = :mid
+                       AND m.mailing_state_id = s.state_id
+                       AND m.mailing_city_id  = c.city_id";
+
+                               $stmt = $this->dbh->prepare($sql);
+                               $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                               $stmt->execute();
+                               $mailingAddyRow = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                               if ($mailingAddyRow) {
+                                       $page->hasMailingAddy = true;
+                                       $page->mailing_address
+                                               = $row['mailing_address'];
+                                       $page->mailing_city
+                                               = $mailingAddyRow['mailing_city_name'];
+                                       $page->mailing_state
+                                               = $mailingAddyRow['mailing_state_name'];
+                                       $page->mailing_state_abbr
+                                               = $mailingAddyRow['mailing_state_abbr'];
+                                       $page->mailing_zip = $row['mailing_zip'];
+                               }
+                       }
+
+            if (!empty($row['lat']) && !empty($row['lon'])) {
+                $fromAddress  = trim(urlencode(str_replace("\n", "", strip_tags($row['member_name']))));
+                $fromAddress .= "@{$row['lat']},{$row['lon']}";
+            } else {
+                $fromAddress = trim(urlencode(str_replace("\n", "", strip_tags($row['street']))))
+                .','.trim(urlencode(str_replace("\n", "", strip_tags($row['city']))))
+                .','.trim(urlencode(str_replace("\n", "", strip_tags($row['state_name']))));
+            }
+
+            $page->daddr = $fromAddress;
+            $page->description = $row['description'];
+
+            $page->member_id = $row['member_id'];
+            if (defined("MEMBER_SESSION_LIST") && MEMBER_SESSION_LIST) {
+                $page->catid           = $_GET['catid'];
+                $page->trip_planner_id = MEMBER_SESSION_PAGE;
+                if ($_SESSION['wish_list'][$this->_mid]) {
+                    $page->addToLink = false;
+                    $page->plink     = Toolkit_Template_Page::getSeoUrl(
+                                               $this->_pageGateway,
+                                               MEMBER_SESSION_PAGE
+                                       );
+                } else {
+                    $page->addToLink = true;
+                    $page->plink = BASE_URL . "Toolkit/Members/TripPlanner/"
+                    . "wish-list.php?catid={$this->_catid}"
+                    . "&amp;member_id={$row['member_id']}&amp;detail=1";
+                }
+            } else {
+                $page->plink = null;
+            }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberPackages()
+
+    /**
+     * Get all the file data for the the member profile being looked at
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberPackages(&$page)
+       {
+               try {
+                       $sql = "
+                               SELECT title, description, image
+                                 FROM member_packages
+                                WHERE member_id = :mid
+                                  AND NOT pending
+                   AND CURRENT_DATE BETWEEN sdate AND edate
+                 ORDER BY id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $count = 0;
+                       while ($row = $stmt->fetch()) {
+                               $page->packages[$count]['title'] = $row['title'];
+                               if (!empty($row['image'])) {
+                    $img = $page->image_path . $row['image'];
+                                       $page->packages[$count]['image'] = $img;
+                               }
+                               if (!empty($row['description'])) {
+                                       $page->packages[$count]['description'] = $row['description'];
+                               }
+                               ++$count;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberPhotos()
+
+    /**
+     * set all the non-pending photos that a member has
+     *
+     * @param object &$page The object you want to use with the flexy template
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberPhotos(&$page)
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM member_photos
+                                WHERE member_id = :mid
+                                  AND (NOT pending OR pending IS NULL)
+                                ORDER BY pos";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $count = 0;
+                       while ($row = $stmt->fetch()) {
+                               $images[$count]['alt'] = $row['caption'];
+                               $images[$count]['id']  = PHOTO_LARGE_URL . $row['image'];
+                               $images[$count]['src'] = PHOTO_SMALL_URL . $row['image'];
+                               $images[$count]['img'] = $row['image'];
+                               ++$count;
+                       }
+
+            $page->photos = !empty($images) ? $images : false;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberRestaurant()
+
+    /**
+     * Get all the restaurant data for the the member profile being looked at
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setMemberRestaurant(&$page)
+       {
+               try {
+                       $sql = "
+                               SELECT column_name, data_type
+                                 FROM information_schema.columns
+                                WHERE table_name = 'member_restaurants'";
+
+                       $tableData = $this->dbh->query($sql)->fetchAll();
+
+                       $sql = "
+                               SELECT *
+                                 FROM member_restaurants
+                                WHERE member_id = :mid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       if ($row = $stmt->fetch()) {
+                               $show = false;
+                               foreach ($tableData as $td) {
+                                       switch ($td['data_type']) {
+                                       case 'radio' :
+                                       case 'boolean' :
+                                               $restaurant[$td['column_name']]
+                            = ($row[$td['column_name']] == 't') ? 'Yes': 'No';
+                                               if ($row[$td['column_name']] == 't') {
+                                                       $show = true;
+                                               }
+                                               break;
+
+                                       default :
+                                               $restaurant[$td['column_name']] = $row[$td['column_name']];
+                                               break;
+                                       }
+                               }
+
+                $page->restaurant_info = $show;
+                $page->breakfast       = $restaurant['breakfast'];
+                $page->brunch          = $restaurant['brunch'];
+                $page->lunch           = $restaurant['lunch'];
+                $page->dinner          = $restaurant['dinner'];
+                $page->alcohol         = $restaurant['alcohol'];
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     setMemberSocialMedia()
+
+    /**
+     * Gets all the members social media links
+     *
+     * @param object &$page The object you want to use with the flexy template
+        *
+     * @return mixed array if the member has any links otherwise false
+     * @access protected
+     */
+       protected function setMemberSocialMedia(&$page)
+       {
+               try {
+                       $sql = "
+                SELECT facebook, twitter, myspace, linkedin, blog,
+                       youtube, pinterest
+                  FROM member
+                 WHERE member_id = :mid";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT);
+                       $stmt->execute();
+
+            $row = $stmt->fetch(PDO::FETCH_ASSOC);
+            $media = array_filter($row);
+
+            if (!empty($media)) {
+                $page->has_social_media = true;
+                foreach ($media as $k => $v) {
+                    $page->$k = $v;
+                }
+            }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ _validMember()
+
+    /**
+     * Verify the member if valid
+     *
+     * check that the member exists in the DB and that they are active
+     *
+     * @return boolean true if valid, false if not
+     * @access private
+     */
+    private function _validMember()
+    {
+        if (   !$this->_memberExists()
+            || !$this->_memberActive()
+            || $this->_isNewMember()
+        ) {
+            return false;
+        }
+
+        return true;
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/Members/ProfileWriter.php b/Toolkit/Members/ProfileWriter.php
new file mode 100644 (file)
index 0000000..32d84ca
--- /dev/null
@@ -0,0 +1,240 @@
+<?php
+
+/**
+ * Member profile writer
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id:$
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Writes a profile to HTML
+ *
+ * Uses server side caching to increase page return speed.  If a cache exists
+ * for a member - the cache will be returned.  If the member profile template
+ * has been changed after the cache file was written, all the cached
+ * profiles will be cleaned so they can be rewritten on the next pull
+ * using the new template.
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_ProfileWriter implements SplSubject
+{
+       //      {{{     properties
+
+       /**
+        * Observers for the observer pattern
+        * @var    SplSubject
+        * @access private
+        */
+       private $_observers = array();
+
+    /**
+     * Cache
+     * @var    Cache_Lite
+     * @access private
+     */
+       private $_cache;
+
+    /**
+     * Template Engine
+     * @var    HTML_Template_Flexy
+     * @access private
+     */
+       private $_tEngine;
+
+       //      }}}
+       //      {{{     __construct()
+
+
+    /**
+     * Constructor
+     *
+     * @param Cache_Lite          $cache   Caching object
+     * @param HTML_Template_Flexy $tEngine Template engine
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+               Cache_Lite $cache,
+               HTML_Template_Flexy $tEngine
+       ) {
+               $this->_cache   = $cache;
+               $this->_tEngine = $tEngine;
+       }
+
+       //      }}}
+
+       //  {{{ attach()
+
+
+    /**
+     * Attach observer to the subject
+     *
+     * @param SplObserver $observer Observer to attach
+        *
+     * @return void
+     * @access public
+     */
+       public function attach(SplObserver $observer)
+       {
+               $this->_observers[] = $observer;
+       }
+
+       //  }}}
+       //  {{{ detach()
+
+
+    /**
+     * Detach observer form subject
+     *
+     * @param SplObserver $observer Observer to detach
+        *
+     * @return void
+     * @access public
+     */
+       public function detach(SplObserver $observer)
+       {
+               if ($idx = array_search($observer, $this->_observers, true)) {
+                       unset($this->_observers[$idx]);
+               }
+       }
+
+       //  }}}
+       //  {{{ notify()
+
+
+    /**
+     * Notify observers of action
+     *
+     * @return void
+     * @access public
+     */
+       public function notify()
+       {
+               foreach ($this->_observers as $observer) {
+                       $observer->update($this);
+               }
+       }
+
+       //  }}}
+
+       //      {{{     setTemplate()
+
+       /**
+        * Set the template to use with the template engine
+        *
+        * @param string Path to template file
+        *
+        * @return void
+        * @access public
+        */
+       public function setTemplate($template)
+       {
+               $this->_template = $template;
+       }
+
+       //      }}}
+       //      {{{     _isTemplateNewer()
+
+       /**
+        * Check to see if a template has been updated after a cache was written
+        *
+        * @param string $tplFile   Path to template file
+        * @param string $cacheFile Path to cache file
+        *
+        * @return boolean If template mod time is LTE cache mod time
+        * @access private
+        */
+       private function _isTemplateNewer($tplFile, $cacheFile)
+       {
+               $tplPath = $this->_tEngine->options['templateDir'][0];
+               $strlen = strlen($tplPath);
+               if ($tplPath[$strlen - 1] !== DIRECTORY_SEPARATOR) {
+                       $tplPath .= DIRECTORY_SEPARATOR;
+               }
+
+               if (file_exists($cacheFile)) {
+                       //      If the template was modified after the cache was
+                       //      written the mod time will be greater
+                       return (filemtime($cacheFile) <= filemtime($tplPath . $tplFile));
+               }
+       }
+
+       //      }}}
+       //      {{{     toHtml()
+
+
+    /**
+     * Gets an HTML respresentation of the profile
+     *
+        * If profile cache is available - fetch cache to bypass compile time.
+        * If template has been updated after cache was written - clean cache files
+        * and re-create cache to include updates.
+        *
+        * send out notification to observers.
+     *
+     * @param Toolkit_Members_ProfilePage $profile Profile Page Object
+        *
+     * @return boolean Return description (if any) ...
+     * @access public
+     */
+       public function toHtml(Toolkit_Members_ProfilePage $profile)
+       {
+               $GLOBALS['bottomScripts'][]
+                       = GLM_APP_BASE_URL . 'gallery/thickbox-3.1.1.js';
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/business-detail.js';
+
+               $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Members/css/member.css';
+               $GLOBALS['styleSheets'][] = GLM_APP_BASE_URL . 'gallery/gallery.css';
+               $GLOBALS['styleSheets'][] = GLM_APP_BASE_URL . 'gallery/thickbox.css';
+
+               $profileCache = "Member-{$profile->getMemberId()}";
+               $out = $this->_cache->get($profileCache, 'Profile');
+               $cacheFile = $this->_cache->_cacheDir . "cache_Profile_$profileCache";
+
+               if ($this->_isTemplateNewer($this->_template, $cacheFile)) {
+                       $this->_cache->clean('Profile');
+                       $out = false;
+               }
+
+               if (!$out) {
+                       $this->_tEngine->compile($this->_template);
+                       $profile->setMemberDetail(new stdClass());
+                       $out = $this->_tEngine->bufferedOutputObject($profile->profile);
+
+                       if ($out === false) {
+                               include BASE . '404.html';
+                               exit();
+                       } elseif (PEAR::isError($this->_cache->save($out))) {
+                               $logger =& Toolkit_Logger::getLogger();
+                               $logger->emerg($res->getMessage());
+                       }
+               }
+
+               $this->notify();
+
+               return $out;
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/RecordNavigation.php b/Toolkit/Members/RecordNavigation.php
new file mode 100644 (file)
index 0000000..f6b5426
--- /dev/null
@@ -0,0 +1,317 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Navigation class for editing member records
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: RecordNavigation.php,v 1.7 2010/07/14 23:31:14 jamie Exp $
+ * @link     http://demo.gaslightmedia.com
+ */
+
+/**
+ * Base class for the memberdb
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_RecordNavigation
+{
+    //  {{{ __construct()
+
+    /**
+     * Constructor
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function __construct(Config_Container $c)
+    {
+        $this->config = $c;
+    }
+
+    //  }}}
+       //      {{{     getPageNav()
+
+    /**
+     * Render the page navigation that is defined in the navStructure
+     *
+     * @return string Page navigation structure
+     * @access public
+     */
+       public function getPageNav()
+       {
+               $menu = new HTML_Menu($this->navStructure, 'rows');
+        $menu->forceCurrentIndex($_GET['tab']);
+
+               $renderer = new HTML_Menu_DirectRenderer($tpl);
+               $renderer->setEntryTemplate(
+                       HTML_MENU_ENTRY_INACTIVE,
+                       '<li><a href="{url}" title="{desc}">{title}</a></li>'
+               );
+               $renderer->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVE,
+                       '<li><a class="current" href="{url}" title="{desc}">{title}</a></li>'
+               );
+               $renderer->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVEPATH,
+                       '<li><a class="current" href="{url}" title="{desc}">{title}</a></li>'
+               );
+               $renderer->setMenuTemplate('', '');
+               $renderer->setRowTemplate('<ul>', '</ul>');
+
+               $menu->render($renderer);
+               return $renderer->toHtml();
+       }
+
+       //      }}}
+
+       //      {{{     setupAdminNavStructure()
+
+    /**
+     * Sets up a multi dimensional array used for the subnav structure
+     *
+     * @return mixed false on sql error. otherwise void
+     * @access public
+     */
+       public function setupAdminNavStructure()
+       {
+        $singularType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+               $pluralType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+
+        //  Default URI parameters that will get us back to the
+        //  page were we can edit member data.
+               $params = "rt=Members&amp;ac=editMember";
+
+        //  If we are editing an existing member, then we need to
+        //  add their id into the URI so we know who we are editing
+        if (is_numeric($_GET['id'])) {
+            $params .= "&amp;id={$_GET['id']}";
+        }
+
+        //  We always show the member info tab.
+        //  whether we are adding a member or editing a member
+               $nav = array(
+                       'info' => array(
+                               'title' => "$singularType Info",
+                               'url' => "/members.php?$params",
+                               'desc' => "View and edit $singularType in the database",
+                       )
+        );
+        if (is_numeric($_GET['id'])) {
+            $nav['photos'] = array(
+                               'title' => 'Photos',
+                               'url' => "/members.php?$params",
+                               'desc' => "View and edit $pluralType in the database",
+                       );
+            $nav['packages'] = array(
+                               'title' => 'Packages',
+                               'url' => "/members.php?$params",
+                               'desc' => "View and edit $singularType categories",
+                       );
+                       $nav['amenities'] = array(
+                               'title' => 'Amenities',
+                               'url' => "/members.php?$params",
+                               'desc' => "View and edit $singularType amenities",
+                       );
+                       $nav['files'] = array(
+                               'title' => 'Files',
+                               'url' => "/members.php?$params",
+                               'desc' => "View and edit $singularType regions",
+                       );
+                       $nav['contacts'] = array(
+                               'title' => 'Contacts',
+                               'url' => "/members.php?$params",
+                               'desc' => "View and edit $singularType cities",
+                       );
+            $billingModule = $this->config->getItem('section', 'admin')
+                ->getItem('directive', 'billing')
+                ->getContent();
+
+
+            if ($billingModule) {
+                $billingNav = new Toolkit_Members_Billing_RecordNavigation();
+                $nav = $billingNav->getNavigationArray($params, $nav);
+            }
+        }
+
+               $hasPhotos = $this->config
+                       ->getItem('section', 'admin')
+                       ->getItem('directive', 'photos')
+                       ->getContent();
+
+               if (!$hasPhotos) {
+                       unset($nav['photos']);
+               }
+
+               $hasPackages = $this->config
+                       ->getItem('section', 'admin')
+                       ->getItem('directive', 'packages')
+                       ->getContent();
+
+               if (!$hasPackages) {
+                       unset($nav['packages']);
+               }
+
+               $hasAmenities = $this->config
+                       ->getItem('section', 'admin')
+                       ->getItem('directive', 'amenities')
+                       ->getContent();
+
+               if (!$hasAmenities) {
+                       unset($nav['amenities']);
+               }
+
+               $hasFiles = $this->config
+                       ->getItem('section', 'admin')
+                       ->getItem('directive', 'files')
+                       ->getContent();
+
+               if (!$hasFiles) {
+                       unset($nav['files']);
+               }
+
+               $hasContacts = $this->config
+                       ->getItem('section', 'admin')
+                       ->getItem('directive', 'contacts')
+                       ->getContent();
+
+               if (!$hasContacts) {
+                       unset($nav['contacts']);
+               }
+
+        //  make full URI's and attach which tab we are working with
+        foreach ($nav as $i => &$j) {
+            $j['url'] =  BASE_URL . 'admin' . $j['url'] . "&amp;tab=$i";
+        }
+
+               $this->navStructure = $nav;
+       }
+
+       //      }}}
+       //      {{{     setupUserNavSructure()
+
+    /**
+     * Sets up a multi dimensional array used for the subnav structure
+     *
+     * @return mixed  false on sql error. otherwise void
+     * @access public
+     */
+       public function setupUserNavStructure()
+       {
+        $singularType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+               $pluralType = $this->config
+                       ->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+
+               $params = "rt=EditProfile";
+               $nav = array(
+                       'info' => array(
+                               'title' => "$singularType Info",
+                               'url' => "/?$params",
+                               'desc' => "View and edit $singularType in the database",
+                       ),
+                       'photos' => array(
+                               'title' => 'Photos',
+                               'url' => "/?$params",
+                               'desc' => "View and edit $pluralType in the database",
+                       ),
+                       'packages' => array(
+                               'title' => 'Packages',
+                               'url' => "/?$params",
+                               'desc' => "View and edit $singularType categories",
+                       ),
+                       'amenities' => array(
+                               'title' => 'Amenities',
+                               'url' => "/?$params",
+                               'desc' => "View and edit $singularType amenities",
+                       ),
+                       'files' => array(
+                               'title' => 'Files',
+                               'url' => "/?$params",
+                               'desc' => "View and edit $singularType regions",
+                       ),
+                       'contacts' => array(
+                               'title' => 'Contacts',
+                               'url' => "/?$params",
+                               'desc' => "View and edit $singularType cities",
+                       ),
+               );
+
+               $hasPhotos = $this->config
+                       ->getItem('section', 'members only')
+                       ->getItem('directive', 'photos')
+                       ->getContent();
+
+               if (!$hasPhotos) {
+                       unset($nav['photos']);
+               }
+
+               $hasPackages = $this->config
+                       ->getItem('section', 'members only')
+                       ->getItem('directive', 'packages')
+                       ->getContent();
+
+               if (!$hasPackages) {
+                       unset($nav['packages']);
+               }
+
+               $hasAmenities = $this->config
+                       ->getItem('section', 'members only')
+                       ->getItem('directive', 'amenities')
+                       ->getContent();
+
+               if (!$hasAmenities) {
+                       unset($nav['amenities']);
+               }
+
+               $hasFiles = $this->config
+                       ->getItem('section', 'members only')
+                       ->getItem('directive', 'files')
+                       ->getContent();
+
+               if (!$hasFiles) {
+                       unset($nav['files']);
+               }
+
+               $hasContacts = $this->config
+                       ->getItem('section', 'members only')
+                       ->getItem('directive', 'contacts')
+                       ->getContent();
+
+               if (!$hasContacts) {
+                       unset($nav['contacts']);
+               }
+
+        //  make full URI's and attach which tab we are working with
+        foreach ($nav as $i => &$j) {
+            $j['url'] =  BASE_URL . 'members-only-area' . $j['url'] . "&amp;tab=$i";
+        }
+
+               $this->navStructure = $nav;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/Rules/DuplicateMember.php b/Toolkit/Members/Rules/DuplicateMember.php
new file mode 100644 (file)
index 0000000..ba030ee
--- /dev/null
@@ -0,0 +1,99 @@
+<?php
+
+/**
+ * validate if a member name is being duplicated or not
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id: DuplicateMember.php,v 1.2 2010/05/15 15:14:54 jamie Exp $
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Validate if a member name is being duplicated or not
+ *
+ * Check to see if the member name exists already in the database.
+ * If it does not, then it is a valid name. Else it is invalid.
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Rules_DuplicateMember extends HTML_QuickForm_Rule
+{
+       //      {{{     validate()
+
+       /**
+        * Validate if a member already exists
+        *
+        * @param string $value the date array to validate
+        * @param PDO    $dbh   Database handler used to check the DB
+
+        * @return bool if the string could correctly be validated as a date.
+        * @access      public
+        * @see         Validate::date()
+        */
+       function validate($value, PDO $dbh)
+       {
+               try {
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM member
+                                WHERE member_name = :name";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':name', $value, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $stmt->bindColumn('total', $isValid);
+                       $stmt->fetch();
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               'Error checking for duplicate member names'
+                       );
+               }
+
+               return (bool) !$isValid;
+       }
+
+       //      }}}
+       //      {{{ getValidationScript()
+
+    /**
+     * Cannot be validated via JS
+     *
+        * Could set up an AJAX call to perform this.  but haven't done it yet
+     *
+     * @param  unknown $options Parameter description (if any) ...
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       function getValidationScript($options = null)
+       {
+               return array('', false);
+       }
+
+       //      }}}
+}
+
+HTML_QuickForm::registerRule(
+       'DuplicateMember',
+       'rule',
+       'Toolkit_Members_Rules_DuplicateMember',
+       BASE . 'Toolkit/Members/Rules/DuplicateMember.php'
+);
+?>
diff --git a/Toolkit/Members/Rules/MemberFile.php b/Toolkit/Members/Rules/MemberFile.php
new file mode 100644 (file)
index 0000000..c093416
--- /dev/null
@@ -0,0 +1,159 @@
+<?php
+/**
+ * MemberFile.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit
+ * @package  Members_Rules
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_Rules_MemberFile
+ *
+ * Description for Toolkit_Members_Rules_MemberFile
+ *
+ * @category Toolkit
+ * @package  Members_Rules
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_Rules_MemberFile extends HTML_QuickForm_Rule
+{
+       //      {{{     fileUpload()
+
+       /**
+        * Upload a file into its proper spot
+        *
+        * Uploads a file with a unique filename to a target dir by:
+        * 1. Remove illegal characters from the filename.
+        * 2. Check if a file in the target dir exists with that name
+        * 3. If a file does exist, append a unix timestamp to the name to make it
+        *              a unique filename.
+        * 4. Copy the file in the tmp dir to its target dir under its new name.
+        * 5. Verify the new file exists.
+        * 6. If it does make it readable.
+        *
+        * @param string $tmpFile   The name of the file in the tmp dir
+        *                                                  As given by the $_FILES array.
+        * @param string $fileName  The name of the new file, as given by the
+        *                                                  $_FILES array.
+        * @param string $targetDir     The path of the dir where the file should go.
+     * 
+        * @author Jamie Kahgee <steve@gaslightmedia.com
+        *
+        * @return mixed True if successfull, otherwise PEAR error.
+        * @access protected
+        */
+       protected function fileUpload($tmpFile, $fileName, $targetDir)
+       {
+               $fileName = preg_replace('/[!@#$%^&()+={};:\'\"\/ ]/', '-', $fileName);
+               $nameInUse = (file_exists($targetDir . $fileName));
+               if ($nameInUse) {
+                       $fileName = mktime() . $fileName;
+               }
+               $newLocation = $targetDir . $fileName;
+               //      Copy the tmp file into its new spot under its new name.
+               if (!copy($tmpFile, $newLocation)) {
+                       return PEAR::raiseError(
+                               'Unable to copy uploaded file into its target destination.'
+                       );
+               }
+               //      Make sure the file exists
+               if (!is_file($newLocation)) {
+                       return PEAR::raiseError('New file does not exist!');
+               }
+
+               //      Make sure the file is readable.
+               chmod($newLocation, 0666);
+
+               return $fileName;
+       }
+
+       //      }}}
+       //      {{{     getValidationScript()
+
+    /**
+     * Description of getValidationScript
+     * 
+     * @param array $options Options
+     * 
+     * @return void
+     * @access public
+     */
+       function getValidationScript($options = null)
+       {
+       }
+
+       //      }}}
+       //      {{{     validate()
+
+    /**
+     * Description of validate()
+     * 
+     * @param array $value    Value array
+     * @param array &$options Options array
+     * 
+     * @global unknown $form description of $form
+     * 
+     * @return boolean 
+     * @access public
+     */
+       function validate($value, &$options = null)
+       {
+               if ($value['error'] != UPLOAD_ERR_OK) {
+                       return false;
+               }
+               //      Ewwwwww GLOBALS....I know they suck, but unavoidable in this case.
+               if (is_null($options)) {
+                       global $form;
+               } elseif (is_array($options)) {
+                   //  an array of info is passed along the options.
+                       $form =& $options[0];
+                       $required = $options[1];
+               } else {
+                   //  No array is passed along. just the form object.
+            // image upload is then required.
+                       $form =& $options;
+                       $required = true;
+               }
+
+               //      A file was uploaded from the file element.
+               //      process the file
+               //      insert it into the forms submit values
+               if (!empty($value['size'])) {
+                       $fileName = $this->fileUpload(
+                               $value['tmp_name'],
+                               $value['name'],
+                               MEMBER_UPLOADED_FILES
+                       );
+                       if (PEAR::isError($fileName)) {
+                               echo 'File Upload Error: ' . $fileName->getMessage();
+                               return false;
+                       }
+
+                       $element = array_keys(
+                               Toolkit_Common::multiDimArrayLocate($_FILES, $value['name'])
+                       );
+
+                       $origName    = $element[0];
+                       $elementName = "uploaded_{$element[0]}";
+
+                       $form->_submitValues[$elementName] = $fileName;
+               }
+               return true;
+       }
+
+       //      }}}
+}
+
+HTML_QuickForm::registerRule(
+       'MemberFile',
+       'rule',
+       'Toolkit_Members_Rules_MemberFile',
+       BASE . 'Toolkit/Members/Rules/MemberFile.php'
+);
+?>
diff --git a/Toolkit/Members/Rules/MemberLogin.php b/Toolkit/Members/Rules/MemberLogin.php
new file mode 100644 (file)
index 0000000..f4be360
--- /dev/null
@@ -0,0 +1,99 @@
+<?php
+
+/**
+ * validate if a member login is being duplicated or not
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id: MemberLogin.php,v 1.1 2010/05/16 01:51:13 jamie Exp $
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+
+/**
+ * Validate if a member login is being duplicated or not
+ *
+ * Check to see if the member login exists already in the database.
+ * If it does not, then it is a valid login . Else it is invalid.
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_Rules_MemberLogin extends HTML_QuickForm_Rule
+{
+       //      {{{     validate()
+
+       /**
+        * Validate if a member already exists
+        *
+        * @param string $value the date array to validate
+        * @param PDO    $dbh   Database handler used to check the DB
+
+        * @return bool if the string could correctly be validated as a date.
+        * @access      public
+        * @see         Validate::date()
+        */
+       function validate($value, PDO $dbh)
+       {
+               try {
+                       $sql = "
+                               SELECT count(*) AS total
+                                 FROM member
+                                WHERE member_login = :name";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':name', $value, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $stmt->bindColumn('total', $isValid);
+                       $stmt->fetch();
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               'Error checking for duplicate member names'
+                       );
+               }
+
+               return (bool) !$isValid;
+       }
+
+       //      }}}
+       //      {{{ getValidationScript()
+
+    /**
+     * Cannot be validated via JS
+     *
+        * Could set up an AJAX call to perform this.  but haven't done it yet
+     *
+     * @param  unknown $options Parameter description (if any) ...
+     * @return mixed   Return description (if any) ...
+     * @access public
+     */
+       function getValidationScript($options = null)
+       {
+               return array('', false);
+       }
+
+       //      }}}
+}
+
+HTML_QuickForm::registerRule(
+       'MemberLogin',
+       'rule',
+       'Toolkit_Members_Rules_MemberLogin',
+       BASE . 'Toolkit/Members/Rules/MemberLogin.php'
+);
+?>
diff --git a/Toolkit/Members/SearchList.php b/Toolkit/Members/SearchList.php
new file mode 100644 (file)
index 0000000..70724a5
--- /dev/null
@@ -0,0 +1,774 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabsstop=4 foldmethod=marker syntax=php:
+
+/**
+ * SearchList.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @release  CVS: $Id: SearchList.php,v 1.47 2010/07/14 23:31:14 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Datagrid of search results of member db
+ *
+ * @category  Toolkit
+ * @package   Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_SearchList extends Toolkit_FlexyDataGridBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+       protected $tableName = 'member';
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $queryParams = array();
+
+    /**
+     * Description for protected
+     * @var    unknown
+     * @access protected
+     */
+       protected $showSearchBox;
+
+    /**
+     * Description for protected
+     * @var    string
+     * @access protected
+     */
+       protected $template = 'membersList.tpl';
+
+       /**
+        * Whether subcats should be included in the search results
+        *
+        * If this is turned on, the subcategories beneath all categories assigned
+        * to the page will be included in the search results.
+        *
+        * Example Category Tree:
+        *
+        * Parent
+        *   |_ Child
+        *   |    |_ GrandChild
+        *   |
+        *   |_ Sibling
+        *
+        * If set to true and only "Parent" is assigned to a page from the toolbox,
+        * then members with all categories (parent, child, grandchild, sibling) will
+        * be included in the search results.
+        *
+        * If set to false and only Child is assigned to a page, then only members
+        * that have the category "Child" assigned to them will be included in the
+        * search Results.
+        *
+        * @var boolean
+        * @access protected
+        */
+       protected $includeSubCats = true;
+
+    /**
+     * map icon numbers only get displayed if the map is there
+     *
+     * @var boolean
+     * @access protected
+     */
+    protected $memberMap = false;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Class constructor
+        *
+        * define where templates for the data grid are at, then call the parent constructor which will handle
+        * finishing the settings for the datagrid.
+        *
+        * After all settings are finished you can call the toHTML() function on this object and the datagrid
+        * will be rendered and returned as a string.  Optionally you could call show() and the datagrid would
+        * be rendered and output immediatley to the screen.
+        *
+     * @param PDO     $pdo           PHP Data Object to use for DB calls
+     * @param string  $limit         The number of records to display per page.
+     * @param int     $page                 The current page viewed.
+     *                               In most cases, this is useless.
+     *                               Note: if you specify this, the "page" GET
+     *                               variable will be ignored.
+     * @param string  $rendererType  The type of renderer to use.
+     *                               You may prefer to use the $type argument
+     *                               of {@link render}, {@link fill} or
+     *                               {@link getOutput}
+     * @param boolean $showSearchBox If we should allow searching for members
+     * @param array   $sections      specific members we should show
+        *
+     * @return void
+        * @access public
+        */
+       public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null,
+        $showSearchBox = true,
+        array $sections = null
+    ) {
+               $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Members/css/member.css';
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/business-search.js';
+        if (defined("MEMBER_SESSION_LIST") && MEMBER_SESSION_LIST) {
+            $GLOBALS['bottomScripts'][]
+                = BASE_URL . 'Toolkit/Members/libjs/travel-list.js';
+        }
+
+               $this->showSearchBox = $showSearchBox;
+               $this->pagerOptions['containerClass'] = 'pages';
+               parent::__construct($pdo, $limit, $page, $rendererType);
+       }
+
+       //      }}}
+
+       //      {{{ city()
+
+       /**
+        * Returns the city for a member.
+        *
+     * If this memberdb is using controlled cities then we need to extract
+     * the city name via the city_id
+        *
+     * @param array $data tuple record from db
+        *
+        * @return string City name for the record
+        * @access public
+        */
+       public function city($data)
+       {
+        //  get reference to [conf] section of config file
+        $ctrlCtyD =& $this->config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'controlledCities');
+
+        if ($ctrlCtyD->getContent()) {
+            return $data['record']['city_name'];
+        } else {
+            return $data['record']['city'];
+        }
+       }
+
+       //      }}}
+       //      {{{ configureColumns()
+
+       /**
+        * Configures the columns that will be used in our datagrid renderer.
+        *
+        * @return void
+        * @access protected
+        */
+       protected function configureColumns()
+       {
+               $logo = new Structures_DataGrid_Column(
+                       'Logo',
+                       'logo',
+                       'logo',
+                       null,
+                       null,
+                       array(&$this, 'logo')
+               );
+               $this->addColumn($logo);
+
+               $name = new Structures_DataGrid_Column(
+                       'Member Name',
+            'member_name',
+            'member_name'
+               );
+               $this->addColumn($name);
+
+               $memberContactEmail = new Structures_DataGrid_Column(
+                       'Email',
+            'member_contact_email',
+            'member_contact_email'
+               );
+               $this->addColumn($memberContactEmail);
+
+               $drivingDirections = new Structures_DataGrid_Column(
+                       'Address',
+            'address',
+            'address',
+            null,
+            null,
+            array(&$this, 'drivingDirections')
+               );
+               $this->addColumn($drivingDirections);
+
+               $street = new Structures_DataGrid_Column(
+                       'Street',
+            'street',
+            'street'
+               );
+               $this->addColumn($street);
+
+               $city = new Structures_DataGrid_Column(
+                       'City',
+            'city',
+            'city',
+            null,
+            null,
+            array(&$this, 'city')
+               );
+               $this->addColumn($city);
+
+               $state = new Structures_DataGrid_Column(
+                       'State',
+            'state',
+            'state'
+               );
+               $this->addColumn($state);
+
+               $stateAbbr = new Structures_DataGrid_Column(
+                       'State Abbr',
+            'state_abbr',
+            'state_abbr'
+               );
+               $this->addColumn($stateAbbr);
+
+               $zip = new Structures_DataGrid_Column(
+                       'Zip',
+            'zip',
+            'zip'
+               );
+               $this->addColumn($zip);
+
+               $phone = new Structures_DataGrid_Column(
+                       'Phone',
+            'phone',
+            'phone',
+            null,
+            null,
+            array(&$this, 'phone')
+               );
+               $this->addColumn($phone);
+
+               $url = new Structures_DataGrid_Column(
+                       'URL',
+            'url',
+            'url',
+            null,
+            null,
+            array(&$this, 'url')
+               );
+               $this->addColumn($url);
+
+               $reservationId = new Structures_DataGrid_Column(
+                       'Reservation Id',
+                       'reservation_id',
+            'reservation_id'
+               );
+               $this->addColumn($reservationId);
+
+               $numRooms = new Structures_DataGrid_Column(
+                       'Number of Rooms',
+                       'num_rooms',
+            'num_rooms'
+               );
+               $this->addColumn($numRooms);
+
+               $yearRound = new Structures_DataGrid_Column(
+                       'Year Round',
+                       'year_round',
+            'year_round',
+            null,
+            null,
+            array(&$this, 'yearRound')
+               );
+               $this->addColumn($yearRound);
+
+               $hasHotelInfo = new Structures_DataGrid_Column(
+                       null,
+            'has_hotel_info',
+                       'has_hotel_info',
+            null,
+            null,
+            array(&$this, 'hasHotelInfo')
+               );
+        $this->addColumn($hasHotelInfo);
+
+        if (defined("MEMBER_SESSION_LIST") && MEMBER_SESSION_LIST) {
+            $this->addColumn(
+                new Structures_DataGrid_Column(
+                    'plink',
+                    'plink',
+                    'plink',
+                    null,
+                    null,
+                    array(&$this, 'listUrl')
+                )
+            );
+        }
+
+        $this->addColumn(
+            new Structures_DataGrid_Column(
+                'addToLink',
+                'addToLink',
+                'addToLink',
+                null,
+                null,
+                array(&$this, 'inList')
+            )
+        );
+
+        $member_id = new Structures_DataGrid_Column(
+                       'member_id',
+            'member_id',
+            'member_id'
+               );
+        $this->addColumn($member_id);
+
+               $website = new Structures_DataGrid_Column(
+                       'Website',
+                       'website',
+                       'website',
+                       null,
+                       null,
+                       array(&$this, 'website')
+               );
+        $this->addColumn($website);
+
+               $mapIcon = new Structures_DataGrid_Column(
+                       'map_icon',
+                       'map_icon',
+                       'map_icon',
+                       null,
+                       null,
+                       array(&$this, 'mapIcon')
+               );
+        $this->addColumn($mapIcon);
+
+    }
+
+    //    }}}
+
+       //      {{{     drivingDirections()
+
+       /**
+        * Get the html link for driving directions to google
+        *
+        * @param array $data tuple record from db
+        *
+        * @return string html string for link to google maps for driving directions
+        * @access public
+        */
+       public function drivingDirections($data)
+       {
+               extract($data['record']);
+               $format = 'http://maps.google.com/maps?daddr=%s@%s,%s';
+               return sprintf(
+                       $format,
+                       urlencode($member_name),
+                       $lat,
+                       $lon
+               );
+       }
+
+       //      }}}
+
+    //  {{{ getAlphaList()
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return array     Return description (if any) ...
+     *
+     * @access protected
+     */
+       protected function getAlphaList()
+       {
+               $pattern = "/ (\s*?AND\s*?)?upper\(substr\(m.member_name, 1, 1\)\) = upper\('.'\)/i";
+               $replacement = '';
+               $sql = preg_replace($pattern, $replacement, $this->sql);
+               try {
+                       $letters = array();
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->execute();
+
+                       $stmt->bindColumn('member_name', $name);
+
+                       while ($row = $stmt->fetch()) {
+                               $letters[] = strtoupper($name{0});
+                       }
+
+                       $letters = array_unique($letters);
+                       sort($letters);
+
+                       $addNumeric = false;
+                       while ($i = current($letters)) {
+                               if (is_numeric($i)) {
+                                       $addNumeric = true;
+                                       unset($letters[key($letters)]);
+                               } else {
+                                       break;
+                               }
+                       }
+
+                       if ($addNumeric) {
+                               array_unshift($letters, '0-9');
+                       }
+
+                       //      We only need to show the links of alphabet if we have more than
+                       //      one letter to display.
+                       if (count($letters) > 1) {
+                               foreach ($_GET as $k => $v) {
+                                       if ($k != 'alpha') {
+                                               if (is_array($v)) {
+                                                       foreach ($v as $i => $j) {
+                                                               $queryString .= $k . '[' . $i . ']=' . $j . '&';
+                                                       }
+                                               } else {
+                                                       $queryString .= "$k=$v&";
+                                               }
+                                       }
+                               }
+                               $links['All']['url'] = BASE_URL . "index.php?{$queryString}";
+                               $links['All']['class'] = empty($_GET['alpha']) ? 'curr' : null;
+                               foreach ($letters as $v) {
+                                       $links[$v]['url'] = BASE_URL . "index.php?{$queryString}alpha=$v";
+                                       if ($_GET['alpha'] == $v) {
+                                               $links[$v]['class'] = 'curr';
+                                       }
+                               }
+                               return $links;
+                       }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ hasHotelInfo()
+
+    /**
+     * Determines if the record has any available hotel info to display
+     *
+     * @param array $data record data
+     *
+     * @return boolean true if any data to display, otherwise false
+     * @access public
+     */
+       public function hasHotelInfo($data)
+       {
+        extract($data['record']);
+        return !(empty($reservation_id) && empty($num_rooms) && empty($year_round));
+       }
+
+       //      }}}
+
+    // {{{ inList()
+
+       /**
+     * Returns the bool for a member in session (list)
+        *
+        * Used when configuring the columns for the data grid. This
+     * function returns true or false if the member is in not session
+     * then true
+     *
+     * @param array $data tuple record from db
+        *
+     * @return boolean true if member is not in $_SESSION['wish_list']
+        * @access public
+        */
+    public function inList($data)
+    {
+        return !($_SESSION['wish_list'][$data['record']['member_id']]);
+    }
+
+    // }}}
+
+       //      {{{ listUrl()
+
+       /**
+        * Returns the url for a member.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the url to get to the member detail page
+        *
+     * @param array $data tuple record from db
+        *
+        * @access      Public
+        * @version     Release: @package_version@
+        * @return      url for the add to or remove from $_SESSION['wish_list']
+        */
+       public function listUrl($data)
+       {
+        if (defined("MEMBER_SESSION_LIST") && MEMBER_SESSION_LIST) {
+            if ($_SESSION['wish_list'][$data['record']['member_id']]) {
+                               $url = Toolkit_Template_Page::getSeoUrl($this->_pageGateway, MEMBER_SESSION_PAGE);
+            } else {
+                $url = BASE_URL . "Toolkit/Members/TripPlanner/"
+                . "wish-list.php?catid={$_REQUEST['catid']}"
+                . "&amp;member_id={$data['record']['member_id']}";
+            }
+        } else {
+            $url = false;
+        }
+        return $url;
+       }
+
+       //      }}}
+       //      {{{ logo()
+
+       /**
+        * Returns the logo for a member.
+        *
+     * @param array $data tuple record from db
+     *
+        * @return false when empty, otherwise logo path for member
+        * @access
+        */
+       public function logo($data)
+       {
+        extract($data['record']);
+               return empty($logo) ? false : MEMBER_PHOTOS . $logo;
+       }
+
+       //      }}}
+
+       //      {{{ phone()
+
+       /**
+        * Returns the phone # for a member.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the phone for the member
+        *
+     * @param array $data tuple record from db
+     *
+        * @return mixed false when empty, member phone number if not empty
+        * @access public
+        */
+       public function phone($data)
+       {
+        extract($data['record']);
+               return empty($phone) ? false : $phone;
+       }
+
+       //      }}}
+
+    //  {{{ setConfig()
+
+    /**
+     * Sets the query to use to fetch the datagrid results
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function setConfig(Config_Container $c)
+    {
+        $this->config = $c;
+    }
+
+    //  }}}
+    //  {{{ setMemberMap()
+
+    /**
+     * Sets the memberMap on if there's a map displayed on page
+     *
+     * @param unknown $memberMap Description for $memberMap
+     *
+     * @return void
+     * @access public
+     */
+    public function setMemberMap($memberMap)
+    {
+        $this->memberMap = $memberMap;
+    }
+
+    //  }}}
+    //  {{{ setPageGateway()
+
+    /**
+     * Sets the page gateway
+     *
+     * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway gateway obj
+     *
+     * @return void
+     * @access public
+     */
+    public function setPageGateway(
+               Toolkit_Toolbox_PageGatewayAbstract $pageGateway
+       ) {
+        $this->_pageGateway= $pageGateway;
+    }
+
+    //  }}}
+       //      {{{     setControlObject()
+
+    /**
+     * These are the objects that will be inserted into the template.
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setControlObject()
+       {
+        $searchMapIconActive =& $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'searchMapIconActive')
+            ->getContent();
+               $this->ctrlObj['base_url']            = BASE_URL;
+               $this->ctrlObj['catid']               = $_REQUEST['catid'];
+               $this->ctrlObj['trip_planner_id']     = MEMBER_SESSION_PAGE;
+               $this->ctrlObj['letters']             = $this->getAlphaList();
+        $this->ctrlObj['searchMapIconActive'] = $searchMapIconActive;
+
+               if (isset($_GET['search']) && $this->showSearchBox) {
+                       $action = BASE_URL . "index.php?{$_SERVER['QUERY_STRING']}";
+            $form = new Toolkit_Members_UserSearchForm(
+                'SearchForm',
+                'get',
+                $action,
+                null,
+                null,
+                true
+                       );
+            $res = $form->setCatId($_GET['catid']);
+
+            if (PEAR::isError($res)) {
+                return Toolkit_Common::handleError($res);
+            } else {
+                $form->setPageMemberCategories($this->_pageGateway);
+                $form->setPageMemberRegions($this->_pageGateway);
+                $form->configureForm($this->dbh, $this->config);
+                $this->ctrlObj['member_search_form'] = $form->toHtml(
+                                       Toolkit_Members::getFlexyOptions(),
+                                       $this->_pageGateway
+                               );
+            }
+               }
+       }
+
+       //      }}}
+
+       //      {{{ url()
+
+       /**
+        * Returns the url for a member.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the url to get to the member detail page
+        *
+     * @param array $data tuple record from db
+        *
+        * @return string uri for exposure record
+        * @access public
+        */
+       public function url($data)
+       {
+               extract($data['record']);
+        $exposure = new Toolkit_Members_Exposure($member_id, 'list');
+               $exposure->runUpdate();
+               return BASE_URL . "member-profile/{$_GET['catid']}/$member_id/";
+       }
+
+       //      }}}
+
+       //      {{{     website()
+
+       /**
+        * Returns html link to members website w/ clickthru tracking
+        *
+        * @param array $data tuple record from db
+        *
+        * @return string html string for member website w/ clickthru tracking
+        * @access public
+        */
+       public function website($data)
+       {
+               extract($data['record']);
+        if (!$url) {
+            return false;
+        }
+        // make sure the url has http://
+        if (strpos($url, 'http://') === false) {
+            $url = 'http://' . $url;
+        }
+        return $url;
+       }
+
+       //      }}}
+
+       //      {{{     mapIcon()
+
+       /**
+        * Returns html link to members website w/ clickthru tracking
+        *
+        * @param array $data tuple record from db
+        *
+        * @return string html string for member website w/ clickthru tracking
+        * @access public
+        */
+       public function mapIcon($data)
+       {
+        $searchResultNumbered =& $this->config
+            ->getItem('section', 'conf')
+            ->getItem('directive', 'searchResultNumbered')
+            ->getContent();
+               extract($data['record']);
+        if ($searchResultNumbered && $this->memberMap) {
+            $format = BASE_URL . 'map/5680FC/%s.png';
+        }
+
+               if (empty($format)) {
+                       return false;
+               }
+        $currentRecordNumber
+            = $data['currRow'] + $this->getCurrentRecordNumberStart();
+               return array(
+            'id' => $currentRecordNumber - 1,
+            'icon'   => sprintf(
+                $format,
+                $currentRecordNumber
+            )
+               );
+       }
+
+       //      }}}
+
+       //      {{{ yearRound()
+
+       /**
+        * Returns the year round for a member w/ accommodations.
+        *
+        * Used when configuring the columns for the data grid. This
+        * function generates the year round for the member detail page
+     *
+     * @param array $data tuple record from db
+        *
+     * @return string if the accommodations is offered year round
+        * @access public
+        */
+       public function yearRound($data)
+       {
+               return ($data['record']['year_round'] == 't') ? 'Yes' : 'No';
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Members/SearchQueryGenerator.php b/Toolkit/Members/SearchQueryGenerator.php
new file mode 100644 (file)
index 0000000..d28f965
--- /dev/null
@@ -0,0 +1,407 @@
+<?php
+/**
+ * SearchQueryGenerator.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+/**
+ * Toolkit_Members_SearchQueryGenerator
+ *
+ * Description for Toolkit_Members_SearchQueryGenerator
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Steve Sutton <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_SearchQueryGenerator
+{
+       //      {{{     properties
+
+    /**
+     * Description of $_includeSubCats
+     * @var unknown
+     * @access private
+     */
+       private $_includeSubCats;
+
+    /**
+     * Description of $_config
+     * @var Config_Container
+     * @access private
+     */
+       private $_config;
+
+       //      }}}
+
+       //      {{{ __construct()
+
+    /**
+     * Class constructor
+     *
+     * @param unknown          $includeSubCats Include sub categories
+     * @param Config_Container $root           Config container
+     *
+     * @access public
+     */
+       public function __construct($includeSubCats, Config_Container $root)
+       {
+               $this->_includeSubCats = $includeSubCats;
+               $this->_config = $root;
+       }
+
+       //      }}}
+
+       //      {{{     _getMemberCategoriesForPage()
+
+    /**
+     * Gets the member categories that are assigned to the page
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return mixed false if not categories, else array of cats
+     * @access private
+     */
+       private function _getMemberCategoriesForPage(PDO $dbh)
+       {
+               try {
+                       $memberCategories = array();
+                       $sql =  "
+                SELECT category
+                  FROM member_categories2toolbox_pages
+                 WHERE page = :catid";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':catid', $_GET['catid'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('category', $category);
+
+                       while ($row = $stmt->fetch()) {
+                               $memberCategories[] = $category;
+                       }
+
+                       //      If we should include all the sub categories beneath a category.
+                       if ($this->_includeSubCats) {
+                               //      For each of the categories assigned to the page,
+                               //      we need to get all sub-categories.  This way the user
+                               //      can assign a top level category as a balloon to cover all the
+                               //      subcategories w/out individually assigning them as well.
+                               foreach ($memberCategories as $v) {
+                                       $catTree = Toolkit_Common::getHierarchicalTreeStructure(
+                        $dbh,
+                        'category',
+                        'category_id',
+                        'parent_id',
+                        'pos',
+                        $v
+                    );
+
+                                       foreach ($catTree as $i => $j) {
+                                               $memberCategories[] = $i;
+                                       }
+                               }
+                       }
+
+                       return empty($memberCategories) ? false : $memberCategories;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     _getMemberRegionsForPage()
+
+    /**
+     * Gets the member regions that are assigned to the page
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return mixed false if not regions, else array of regions
+     * @access private
+     */
+       private function _getMemberRegionsForPage(PDO $dbh)
+       {
+               try {
+                       $memberRegions = array();
+                       $sql =  "
+                SELECT region
+                  FROM member_regions2toolbox_pages
+                 WHERE page = :catid";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':catid', $_GET['catid'], PDO::PARAM_INT);
+                       $stmt->execute();
+                       $stmt->bindColumn('region', $region);
+
+                       while ($row = $stmt->fetch()) {
+                               $memberRegions[] = $region;
+                       }
+
+                       return empty($memberRegions) ? false : $memberRegions;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+    //  {{{ getQuery()
+
+    /**
+     * Gets the query to use to fetch the datagrid results
+     *
+        * @param PDO   $dbh      Database handler
+     * @param array $sections Sections array
+        *
+     * @return void
+     * @access public
+     */
+    public function getQuery(PDO $dbh, array $sections = null)
+    {
+               $sql = "
+        SELECT distinct m.*, c.city_name, s.state_name AS state, s.state_abb
+               AS state_abbr, ma.reservation_id, ma.num_rooms,
+               ma.year_round
+          FROM member m
+        NATURAL LEFT JOIN member_accommodations ma
+          JOIN state s ON m.state_id = s.state_id
+          JOIN city c ON m.city_id  = c.city_id,
+          exploded_members_name emn";
+
+        $params = array(
+                       "new_member <> '1'",
+                       "active = '1'",
+                       'emn.mid = m.member_id');
+        if (defined('EVENT_MANAGEMENT') && EVENT_MANAGEMENT) {
+            $params[] = "(events_only IS NULL OR events_only = false)";
+        }
+        //  Limit to members whose first letter starts with the letter
+        //  a user clicked in the narrow alphabetically list.
+               if (isset($_GET['alpha']) && $_GET['alpha'] == '0-9') {
+                       $params[] = "substr(m.member_name, 1, 1) ~ '[0-9]'";
+        } elseif (isset($_GET['alpha']) && ctype_alpha($_GET['alpha'])) {
+                       $letter = $_GET['alpha'][0];
+            $params[] = "upper(substr(m.member_name, 1, 1)) = upper(" .
+                               $dbh->quote($letter) . ')';
+               }
+        $memberName = filter_var($_REQUEST['member_name'], FILTER_SANITIZE_STRING);
+        //  Limit to members whose name contains the string a user
+        //  entered into the member name box. + Phonetics search matches.
+        if (isset($memberName) && !empty($memberName)) {
+                       $noSpaceName = preg_replace(
+                               '/\W/',
+                               '',
+                               urldecode($memberName)
+                       );
+                       $spaceName = urldecode($memberName);
+                       $sanitizedNoSpaceName = $dbh->quote($noSpaceName);
+                       $sanitizedSpaceName = $dbh->quote($spaceName);
+                       $params[] = "
+                       (
+                               (   regexp_replace(member_name, '[^[:alnum:]]', '', 'g') ~* $sanitizedNoSpaceName
+                                OR metaphone(member_name, 4) = metaphone($sanitizedSpaceName, 4)
+                               )
+                        OR (
+                                    m.member_id = emn.mid
+                                AND (
+                                                $sanitizedNoSpaceName ~* regexp_replace(emn.part, '[^[:alnum:]]', '', 'g')
+                                         OR (metaphone($sanitizedSpaceName, 4) = metaphone(emn.part, 4))
+                                        )
+                                AND char_length(emn.part) > 1
+                               )
+                       )";
+        }
+
+        //  Using controlled cities and a search was performed on a city
+        //  get reference to [conf] section of config file
+        $ctrlCtyD =& $this->_config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'controlledCities');
+        $hasRegions =& $this->_config
+                       ->getItem('section', 'conf')
+                       ->getItem('directive', 'regions')
+                       ->getContent();
+        $regionId = filter_var($_REQUEST['region'], FILTER_VALIDATE_INT);
+        if ($regionId) {
+            $params[] = " (m.region = " . $dbh->quote($regionId) .")";
+        } elseif ($hasRegions
+            && $regions = $this->_getMemberRegionsForPage($dbh)
+        ) {
+            $params[] = '
+             (m.region in ('.implode(', ', $regions).') OR m.region IS NULL)';
+        }
+        $postedArrays = filter_var_array(
+            $_REQUEST,
+            array(
+                'activity' => array(
+                    'filter' => FILTER_VALIDATE_INT,
+                    'flags'  => FILTER_FORCE_ARRAY
+                ),
+                'park' => array(
+                    'filter' => FILTER_VALIDATE_INT,
+                    'flags'  => FILTER_FORCE_ARRAY
+                )
+            )
+        );
+        if (!empty($postedArrays['activity'])) {
+            $params[] = "m.member_id IN (
+                SELECT member_id
+                  FROM member_category
+                 WHERE category_id IN ("
+                .implode(',', $postedArrays['activity'])."))";
+        }
+        if ($postedArrays['park']) {
+             $params[] = "m.member_id IN (
+                SELECT member_id
+                  FROM member_category
+                 WHERE category_id IN ("
+                .implode(',', $postedArrays['park'])."))";
+        }
+
+        //  Limit to members who have the category assigned to them
+        //  that a user selected from the member type box.
+        if (   isset($_GET['sub_category_id'])
+                       && ctype_digit($_GET['sub_category_id'])
+               ) {
+            $subCategoryId = filter_input(
+                INPUT_GET,
+                'sub_category_id',
+                FILTER_SANITIZE_NUMBER_INT
+            );
+            $params[] = "
+                m.member_id IN (
+                    SELECT member_id
+                      FROM member_category
+                     WHERE category_id = " .
+                                       $dbh->quote($subCategoryId) . ')';
+        } elseif (   isset($_GET['category_id'])
+                                 && ctype_digit($_GET['category_id'])
+               ) {
+            unset($subCats);
+            if ($this->_includeSubCats) {
+                //  Members who are assigned specifically to this category
+                //  OR
+                //  Members who have a category assigned to them that is a child
+                //  of the parent category.
+                $catTree = Toolkit_Common::getHierarchicalTreeStructure(
+                    $dbh,
+                    'category',
+                    'category_id',
+                    'parent_id',
+                    'pos',
+                    $_GET['category_id']
+                );
+                $categories = $this->_getMemberCategoriesForPage($dbh);
+
+                // need to find out if the categories returned here are actually
+                // included on the page first before including to the search params
+
+
+                if (!empty($categories) && !empty($catTree)) {
+                    foreach ($catTree as $ctId => $testCat) {
+                        if (!in_array($ctId, $categories)) {
+                            unset($catTree[$ctId]);
+                        }
+                    }
+                    if (!empty($catTree)) {
+                        $subCats = "
+                        OR category_id IN (".implode(', ', array_keys($catTree)).")";
+                    }
+                }
+            }
+            if (   (   isset($_GET['category_id'])
+                && ctype_digit($_GET['category']))
+                || isset($subCats)
+            ) {
+                $params[] = "
+                    m.member_id IN (
+                        SELECT member_id
+                        FROM member_category
+                        WHERE category_id = {$_GET['category_id']}
+                            $subCats)";
+            }
+        } elseif ($categories = $this->_getMemberCategoriesForPage($dbh)) {
+            $params[] = '
+                 m.member_id in (
+                    SELECT member_id
+                      FROM member_category
+                     WHERE category_id in ('.implode(', ', $categories).'))';
+        }
+
+               //      Limit to members who have the amenities that a user
+               //      checked off.
+               if (isset($_GET['amenities']) && !empty($_GET['amenities'])) {
+                       if (   isset($_GET['search_all_amenity'])
+                               && isset($_GET['amenities'])
+                               && is_array($_GET['amenities'])
+                               && !empty($_GET['amenities'])
+                       ) {
+                               //      Member must have ALL of the selected amenities.
+                               $innerSql = array();
+                               foreach ($_GET['amenities'] as $k => $v) {
+                                       if (ctype_digit((string)$k)) {
+                                               $innerSql[] = "
+                                                       SELECT member_id
+                                                         FROM member_amenity
+                                                        WHERE amenity_id = $k";
+                                       }
+                               }
+
+                               $innerSql = implode(' INTERSECT ', $innerSql);
+                               $innerSql = "m.member_id in ($innerSql)";
+
+                               $params[] = $innerSql;
+                       } elseif (is_array($_GET['amenities'])) {
+                               $addParam = true;
+                               foreach ($_GET['amenities'] as $key => $value) {
+                                       if (!filter_var($key, FILTER_VALIDATE_INT)) {
+                                               $addParam = false;
+                                       }
+                               }
+                               if ($addParam) {
+                                       //      Member can have ANY of the selected amenities
+                                       $params[] = "
+                                               member_id in (
+                                                       SELECT member_id
+                                                         FROM member_amenity
+                                                        WHERE amenity_id in(".implode(', ', array_keys($_GET['amenities']))."))";
+                               }
+                       }
+               }
+
+               if (!is_null($sections)) {
+                       foreach ($sections as $v) {
+                               switch ($v) {
+                               case 'packages' :
+                                       $params[] = "
+                                               member_id IN (
+                                                       SELECT member_id
+                                                         FROM member_packages
+                                                        WHERE NOT pending
+                                                          AND CURRENT_DATE BETWEEN sdate AND edate)";
+                                       break;
+
+                               default :
+                                       break;
+                               }
+                       }
+               }
+
+               if (!empty($params)) {
+                       $sql .= ' WHERE ' . implode(' AND ', $params);
+               }
+//var_dump($params);
+//var_dump($sql);
+//exit;
+        return $sql;
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/Members/StreamSend.php b/Toolkit/Members/StreamSend.php
new file mode 100644 (file)
index 0000000..af9ad33
--- /dev/null
@@ -0,0 +1,526 @@
+<?php
+/**
+ * StreamSend.php
+ *
+ * PHP Version 5
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+
+/**
+ * Default parameters for contact create operations.
+ * Note that these are strings for use in XML data not true/false values.
+ * If false, the person will be created with a status of pending
+ */
+define('STREAMSEND_DEFAULT_ACTIVATE', 'true');
+/**
+  * If activate is false, setting this to true will trigger the sending of the built-in
+  * activation notification; if activate is true, this setting has no effect
+  */
+define('STREAMSEND_DEFAULT_DELIVER_ACTIVATION', 'false');
+/**
+  * If activate is true, setting this to true will trigger the sending of the built-in
+  * welcome notification; if activate is false, this setting has no effect
+  */
+define('STREAMSEND_DEFAULT_DELIVER_WELCOME', 'false');
+
+require_once GLM_APP_BASE . 'StreamSend/Member.php';
+
+/**
+ * Toolkit_Members_StreamSend
+ *
+ * Description for Toolkit_Members_StreamSend
+ *
+ * @category Toolkit
+ * @package  Members
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  Gaslight Media
+ * @link     <>
+ */
+class Toolkit_Members_StreamSend
+{
+    /**
+     * Database handler
+     * @var PDO
+     * @access protected
+     */
+    protected $dbh;
+
+    /**
+     * Description of $streamSendMember
+     * @var StreamSend_Member()
+     * @access protected
+     */
+    protected $streamSendMember;
+
+    /**
+     * Class constructor
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @access public
+     */
+    public function __construct(PDO $dbh)
+    {
+        $this->dbh = $dbh;
+        $this->streamSendMember = new StreamSend_Member();
+    }
+
+    /**
+     * Description of addAllMembers
+     *
+     * @return void
+     * @access protected
+     */
+    protected function addAllMembers()
+    {
+        $this->streamSendMember->setStreamSend();
+        $this->streamSendMember->setMemberCategories($this->dbh);
+
+        $members = $this->getAllMembers();
+        var_dump($members);
+        $ret = $this->streamSendMember->importMembers($members);
+        var_dump($ret);
+    }
+
+    /**
+     * Description of firstRun()
+     *
+     * @return void
+     * @access public
+     */
+    public function firstRun()
+    {
+        $this->streamSendMember->initializeMemberStreamSend(
+            Toolkit_Database::getInstance()
+        );
+        // now everything is setup import all members and member contacts
+        $this->addAllMembers();
+    }
+
+    /**
+     * Description of getAllMembers()
+     *
+     * @return array $members
+     * @access protected
+     */
+    protected function getAllMembers()
+    {
+        $memberMapper = new StreamSend_DB_MemberMapper();
+        $memberMapper->setMemberCategories(
+            $this->streamSendMember->memberCategories
+        );
+        // for the import we need to translate the &amp; back to &
+        $memberMapper->setMemberCategoriesForImport();
+        try {
+            $members = array();
+            $sql = "
+            SELECT member_id
+              FROM member
+             WHERE process_email != ''
+               AND process_email IS NOT NULL";
+            $stmt = $this->dbh->query($sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $members[] = $memberMapper->findById($this->dbh, $row['member_id']);
+                $memberContacts
+                    = $this->getAllMemberContacts($row['member_id']);
+                if ($memberContacts) {
+                    foreach ($memberContacts as $contact) {
+                        $members[] = $contact;
+                    }
+                }
+            }
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $members;
+    }
+
+    /**
+     * Description of getAllMemberContacts()
+     *
+     * @param integer $memberId memberId
+     *
+     * @return unknown
+     * @access protected
+     */
+    protected function getAllMemberContacts($memberId)
+    {
+        $memberContactMapper = new StreamSend_DB_MemberContactMapper();
+        $memberContactMapper->setMemberCategories(
+            $this->streamSendMember->memberCategories
+        );
+        return $memberContactMapper->findById(
+            $this->dbh,
+            $memberId
+        );
+    }
+
+    /**
+     * Description for SendMemberById
+     *
+     * @param integer $memberId Member ID
+     *
+     * @return void
+     * @access public
+     */
+    public function sendMemberById($memberId)
+    {
+        $this->streamSendMember->setStreamSend();
+        $this->streamSendMember->setMemberCategories($this->dbh);
+
+        $memberMapper = new StreamSend_DB_MemberMapper();
+        $memberMapper->setMemberCategories(
+            $this->streamSendMember->memberCategories
+        );
+
+        $member = $memberMapper->findById($this->dbh, $memberId);
+        if ($member->getEmail_address()) {
+               $this->streamSendMember->addContactToStreamSend($member);
+        }
+    }
+
+    /**
+     * Description for SendMemberContactsByMemberId
+     *
+     * @param int $memberId Member ID
+     *
+     * @return void
+     * @access public
+     */
+    public function sendMemberContactsByMemberId($memberId)
+    {
+        $this->streamSendMember->debug = true;
+        $this->streamSendMember->setStreamSend();
+        $this->streamSendMember->setMemberCategories($this->dbh);
+
+        $memberContactMapper = new StreamSend_DB_MemberContactMapper();
+        $memberContactMapper->setMemberCategories(
+            $this->streamSendMember->memberCategories
+        );
+        $memberContacts = $memberContactMapper->findById(
+            $this->dbh,
+            $memberId
+        );
+        foreach ($memberContacts as $contact) {
+            $this->streamSendMember->addContactToStreamSend($contact);
+        }
+    }
+
+    /**
+     * Given a Member Category id and name update the streamsend option
+     * for the field 'Member Category'
+     * This also update the streamsend table with correct data
+     * if the category parent is 0 or the category is deleted streamsend table
+     * is updated and the field option is destroyed
+     *
+     * @param integer $categoryId category_id field table category
+     *
+     * @return void
+     */
+    public function updateOptionByCategoryId($categoryId)
+    {
+        $this->streamSendMember->setStreamSend();
+        $this->streamSendMember->setMemberCategories($this->dbh);
+        if (!is_numeric($categoryId)) {
+            throw new InvalidArgumentException(
+                'CategoryId supplied must be numeric'
+            );
+        }
+        try {
+            // for getting the categories parent name (needed for option name)
+            $sql = "
+            SELECT name
+              FROM category
+             WHERE category_id = :parent_id";
+            $getParentId = $this->dbh->prepare($sql);
+            // get data from our cache table of member category options
+            $sql = "
+            SELECT *
+              FROM streamsend
+             WHERE category_id = :category_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':category_id',
+                $categoryId,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            // $currentFieldData is from the streamsend table
+            $currentFieldData = $stmt->fetch(PDO::FETCH_ASSOC);
+            $sql = "
+            SELECT *
+              FROM category
+             WHERE category_id = :category_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':category_id',
+                $categoryId,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            // $data will be the array from category table
+            $data = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($data['parent_id']) {
+                $getParentId->bindParam(
+                    ':parent_id',
+                    $data['parent_id'],
+                    PDO::PARAM_INT
+                );
+                $getParentId->execute();
+                $parentName = $getParentId->fetchColumn();
+                $newOptionName = $parentName . '/' . $data['name'];
+                $newOptionName = $this->streamSendMember->cleanName(
+                    $newOptionName
+                );
+            }
+            if ($currentFieldData) {
+                if (!$data['parent_id'] || $_REQUEST['delete']) {
+                    $this->streamSendFieldOptionDelete(
+                        $currentFieldData,
+                        $categoryId
+                    );
+                    return true;
+                }
+                if ($newOptionName != $currentFieldData['option_name']) {
+                    // we'll need to see if the category is going to parent 0
+                    // if it is then it'll need to be deleted
+                    // if not then it'll be updated
+                    if ($data['parent_id']) {
+                        $this->streamSendFieldOptionUpdate(
+                            $currentFieldData['field_id'],
+                            $currentFieldData['option_id'],
+                            $newOptionName,
+                            $categoryId
+                        );
+                    }
+                }
+            } else {
+                if (!$_REQUEST['delete'] && $data['parent_id']) {
+                    $this->streamSendFieldOptionCreate(
+                        $data,
+                        $newOptionName
+                    );
+                }
+            }
+            return true;
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Create a new stream send field option
+     * gets the fieldId from feild_id in 'Member Category' (streamsend table)
+     * function must setup the dabase entry for field option and submit to
+     * streamsend the new field option
+     *
+     * @param array  $data          Array from the category table
+     * @param string $newOptionName option name 'parent/subcategory'
+     *
+     * @return boolean|void
+     * @throws InvalidArgumentException
+     * @access protected
+     */
+    protected function streamSendFieldOptionCreate($data, $newOptionName)
+    {
+        if (!is_numeric($data['category_id'])) {
+            throw new InvalidArgumentException(
+                '$data["category_id"] must be numeric'
+            );
+        }
+        if (!is_numeric($data['parent_id'])) {
+            throw new InvalidArgumentException(
+                '$data["parent_id"] must be numeric'
+            );
+        }
+        if (!isset($newOptionName) || !strstr($newOptionName, '/')) {
+            throw new InvalidArgumentException(
+                'Must have option name with a slash in it'
+            );
+        }
+        $sql = "
+        SELECT field_id
+          FROM streamsend
+         WHERE field_name = 'Member Category'
+         LIMIT 1
+        OFFSET 0";
+        $fieldId = $this->dbh->query($sql)->fetchColumn();
+        $fieldName = 'Member Category';
+        // for a new field option create a record in cache table
+        $sql = "
+        INSERT INTO streamsend
+        (field_id, field_name, option_id, option_name, category_id, parent)
+        VALUES
+        (:field_id, :field_name, :option_id, :option_name, :category_id, :parent)";
+        $stmt = $this->dbh->prepare($sql);
+        $optionId = $this->streamSendMember->createFieldOption(
+            $fieldId,
+            $newOptionName
+        );
+        if (!$optionId) {
+            // if we can't find it here then look into the member category array
+            if (is_array($this->streamSendMember->memberCategories)) {
+                foreach ($this->streamSendMember->memberCategories as $optId => $name) {
+                    if ($newOptionName == $name) {
+                        $optionId = $optId;
+                        continue;
+                    }
+                }
+            }
+        }
+        if (!$optionId) {
+            return true;
+        }
+        // now insert into the streamsend table
+        $stmt->bindParam(
+            ':field_id',
+            $fieldId,
+            PDO::PARAM_INT
+        );
+        $stmt->bindParam(
+            ':field_name',
+            $fieldName,
+            PDO::PARAM_STR
+        );
+        $stmt->bindParam(
+            ':option_id',
+            $optionId,
+            PDO::PARAM_INT
+        );
+        $stmt->bindParam(
+            ':category_id',
+            $data['category_id'],
+            PDO::PARAM_INT
+        );
+        $stmt->bindParam(
+            ':option_name',
+            $newOptionName,
+            PDO::PARAM_STR
+        );
+        $stmt->bindParam(
+            ':parent',
+            $data['parent_id'],
+            PDO::PARAM_INT
+        );
+        $stmt->execute();
+    }
+
+    /**
+     * delete the field option from streamsend
+     * and delete the streamsend record for it
+     * This has to be done before the actual delete of the category
+     * or it won't find the field_id and option_id so it can be deleted
+     * from streamsend
+     *
+     * reamsend the new field option
+     *
+     * @param array  $data       Array from the category table
+     * @param string $categoryId Category ID
+     *
+     * @return void
+     * @throws InvalidArgumentException
+     * @access protected
+     */
+    protected function streamSendFieldOptionDelete($data, $categoryId)
+    {
+        if (!is_numeric($data['field_id'])) {
+            throw new InvalidArgumentException(
+                '$data["field_id"] must be numeric'
+            );
+        }
+        if (!is_numeric($data['option_id'])) {
+            throw new InvalidArgumentException(
+                '$data["option_id"] must be numeric'
+            );
+        }
+        if (!is_numeric($categoryId)) {
+            throw new InvalidArgumentException(
+                '$categoryId must be numeric'
+            );
+        }
+        $this->streamSendMember->deleteFieldOption(
+            $data['field_id'],
+            $data['option_id']
+        );
+        try {
+            $sql = "
+            DELETE FROM streamsend
+             WHERE category_id = :category_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':category_id',
+                $categoryId,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * update the streamsend account with new name for an option
+     * and update our streamsend table with new name
+     *
+     * @param integer $fieldId       field_id of streamsend field
+     * @param integer $optionId      option_id of streamsend field
+     * @param string  $newOptionName new name
+     * @param integer $categoryId    category_id for streamsend table
+     *
+     * @return void
+     * @access protected
+     * @throws InvalidArgumentException
+     */
+    protected function streamSendFieldOptionUpdate(
+        $fieldId,
+        $optionId,
+        $newOptionName,
+        $categoryId
+    ) {
+        if (!is_numeric($fieldId)) {
+            throw new InvalidArgumentException(
+                '$fieldId must be numeric'
+            );
+        }
+        if (!is_numeric($optionId)) {
+            throw new InvalidArgumentException(
+                '$optionId must be numeric'
+            );
+        }
+        if (!isset($newOptionName) || !strstr($newOptionName, '/')) {
+            throw new InvalidArgumentException(
+                'Must have option name with a slash in it'
+            );
+        }
+        $this->streamSendMember->updateFieldOption(
+            $fieldId,
+            $optionId,
+            $newOptionName
+        );
+        try {
+            $sql = "
+            UPDATE streamsend
+               SET option_name = :option_name
+             WHERE category_id = :category_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':category_id',
+                $categoryId,
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':option_name',
+                $newOptionName,
+                PDO::PARAM_STR
+            );
+            $stmt->execute();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/Members/TripPlanner/AuthContainer.php b/Toolkit/Members/TripPlanner/AuthContainer.php
new file mode 100644 (file)
index 0000000..cc7c55b
--- /dev/null
@@ -0,0 +1,196 @@
+<?php
+
+/**
+ * Authentication container for members trip planner
+ *
+ * Custom container which allows us to utilize our PDO Singleton which
+ * takes advantage of schema based partitioning of our tables
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id: AuthContainer.php,v 1.1 2010/06/22 11:45:34 jamie Exp $
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Authentication container for members trip planner
+ *
+ * Custom container which allows us to utilize our PDO Singleton which
+ * takes advantage of schema based partitioning of our tables
+ *
+ * @category  Members
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_Members_TripPlanner_AuthContainer extends Auth_Container
+{
+       //      {{{     properties
+
+    /**
+     * Database handler
+     * @var    PDO
+     * @access private
+     */
+       private $_dbh;
+
+       /**
+        * Addition options for the storage container
+        * @var array
+        * @access private
+        */
+       private $_options = array();
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param PDO   $dbh     Database handler
+     * @param array $options Options array
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(PDO $dbh, array $options = null)
+       {
+               $this->_dbh = $dbh;
+               $this->_setDefaults();
+               if (is_array($options)) {
+                       $this->_parseOptions($options);
+               }
+       }
+
+       //      }}}
+       //      {{{     _setDefaults()
+
+       /**
+        * Set some default options
+        *
+        * @access private
+        * @return void
+        */
+       private function _setDefaults()
+       {
+               $this->_options['table']       = 'contact';
+               $this->_options['usernamecol'] = 'email';
+               $this->_options['passwordcol'] = 'password';
+               $this->_options['db_fields']   = array('id', 'fname', 'lname');
+               $this->_options['cryptType']   = 'md5';
+               $this->_options['db_where']    = '';
+       }
+
+       //      }}}
+       //      {{{     _parseOptions()
+
+       /**
+        * Parse options passed to the container class
+        *
+        * @param array $array options for class
+        *
+        * @access private
+        * @return void
+        */
+       private function _parseOptions($array)
+       {
+               foreach ($array as $key => $value) {
+                       if (isset($this->_options[$key])) {
+                               $this->_options[$key] = $value;
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     fetchData()
+
+    /**
+     * Get the user information from the database
+     *
+     * @param string $username username to authenticate
+     * @param string $password password to authenticate against username
+        *
+     * @return boolean If the user was authenticated or not
+     * @access public
+     * @throws Toolkit_Members_Exception upon error querying DB for user
+     */
+       public function fetchData($username, $password)
+       {
+               if (   is_string($this->_options['db_fields'])
+                       && strstr($this->_options['db_fields'], '*')
+               ) {
+                       $sqlFrom = '*';
+               } else {
+                       $sqlFrom  = $this->_options['usernamecol'];
+                       $sqlFrom .= ', ' . $this->_options['passwordcol'];
+
+                       if (strlen($fields = $this->_getDBFields()) > 0) {
+                               $sqlFrom .= ", $fields";
+                       }
+
+               }
+
+               $pword = ($this->_options['cryptType'] == 'md5') ? 'MD5(:pword)' : ':pword';
+
+               $sql = "
+            SELECT $sqlFrom
+              FROM {$this->_options['table']}
+             WHERE {$this->_options['usernamecol']} = :uname
+               AND {$this->_options['passwordcol']} = $pword";
+
+               try {
+                       $stmt = $this->_dbh->prepare($sql);
+                       $stmt->bindParam(':uname', $username, PDO::PARAM_STR);
+                       $stmt->bindParam(':pword', $password, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       if ($row !== false) {
+                               foreach ($row as $key => $value) {
+                                       $this->_auth_obj->setAuthData($key, $value);
+                               }
+                               return true;
+                       }
+
+                       return false;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               "Error validating user `$username` - `$password`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     _getDBFields()
+
+       /**
+        * Get extra db fields to fetch and set in the auth data
+        *
+        * @return array comma separated string of extra db fields for a SQL query
+        * @access private
+        */
+       private function _getDBFields()
+       {
+               if (isset($this->_options['db_fields'])) {
+                       if (is_array($this->_options['db_fields'])) {
+                               return implode(', ', $this->_options['db_fields']);
+                       }
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/TripPlanner/Forgot.php b/Toolkit/Members/TripPlanner/Forgot.php
new file mode 100644 (file)
index 0000000..8b4cb05
--- /dev/null
@@ -0,0 +1,358 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Forgot.php
+ *
+ * for contacts that forget their password sends out an email to if they're found.
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Forgot.php,v 1.4 2010/05/20 15:30:36 matrix Exp $
+ * @link      <>
+ */
+
+/**
+ * Handles rendering and validating the password reminder form
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      <>
+ * @see       Toolkit_FormBuilder
+ */
+class Toolkit_Members_TripPlanner_Forgot extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Table to query when gathering information
+        *
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'contact';
+
+    /**
+     * Custom defined rules to validate against when the form is submitted
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Where to perform validation
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $validationType = 'client';
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param PDO     $pdo         PDO object
+     * @param string  $formName    Form's name
+     * @param string  $method      (optional)Form's method defaults to 'POST'
+     * @param string  $action      (optional)Form's action
+     * @param string  $target      (optional)Form's target
+     * @param mixed   $attributes  (optional)Extra attributes for the <form> tag
+     * @param boolean $trackSubmit (optional)Whether to track if the form
+        *                                                         was submitted by adding a special hidden field
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+               $this->template = BASE . 'Toolkit/Members/templates/currentTables/';
+       }
+
+       //      }}}
+
+       //      {{{     checkAddressExists()
+
+    /**
+     * Checks to see if the email address exists before allowing an email to go out
+     *
+     * @param string $value submitted email address
+        *
+     * @return boolean If the email address exists or not
+     * @access public
+     */
+       public function checkAddressExists($value)
+       {
+               try {
+                       $sql = "
+                SELECT count(*) AS total
+                  FROM {$this->tableName}
+                 WHERE email = :email
+                   AND verify_password IS NOT NULL
+                   AND verify_password != ''
+                   AND password IS NOT NULL
+                   AND password != ''";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':email', $value, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $stmt->bindColumn('total', $exists);
+                       $stmt->fetch();
+
+                       return (bool) $exists;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     configureElements()
+
+    /**
+     * Sets up the elements to be configured for use with the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureElements()
+       {
+        $e = array();
+
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'formHdr',
+            'display' => 'Email Reminder'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'email',
+            'display' => 'Your Email Address'
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Send'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Sets up the filters to be used with the form when submitted
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper method to setup form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{     configureRules()
+
+    /**
+     * Sets up required rules and extra defined rules for the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureRules()
+       {
+        $r = array();
+
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Invalid Email Format!',
+            'type' => 'email',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Cannot locate email address!',
+            'type' => 'callback',
+            'format' => array(&$this,
+            'checkAddressExists'),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+       //      {{{     setupRenderers()
+
+    /**
+     * Inject custom renderers into the forms elements for custom display
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="form-warning-inside">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate('<tr><td colspan="2" align="center">{element}</td></tr>', 'submit');
+       }
+
+       //      }}}
+
+       //      {{{     processData()
+
+    /**
+     * Processes the data submitted by the form
+     *
+        * Gets the login credentials for the matching email address and mails
+        * them to that email address
+     *
+     * @param array $values submitted form values
+        *
+     * @return boolean   Result of mail
+     * @access protected
+     */
+       protected function processData($values)
+       {
+               try {
+                       $sql = "
+                SELECT email, verify_password as password
+                  FROM {$this->tableName}
+                 WHERE email = :email";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':email', $values['email'], PDO::PARAM_STR);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+
+                       $htmlMsg
+                = "Here is your " . SITENAME . " password:<br><br>" .
+                                 "Email: {$values['email']}<br>" .
+                                 "Password: {$row['password']}<br><br>";
+
+                       $msg
+                = "Here is your " . SITENAME . " password:\n\n" .
+                                 "Email: {$values['email']}\n" .
+                                 "Password: {$row['password']}";
+
+                       $crlf     = "\n";
+                       $mimeMail = new Mail_mime($crlf);
+                       $mimeMail->setFrom(SITENAME . ' <' . OWNER_EMAIL . '>');
+                       $mimeMail->setSubject('Your ' . SITENAME . ' Password');
+                       $mimeMail->setHTMLBody($htmlMsg);
+                       $mimeMail->setTXTBody($msg);
+
+                       $mail    =& Mail::factory('mail');
+                       $body    = $mimeMail->get();
+                       $headers = $mimeMail->headers($hdrs);
+
+                       $res = $mail->send($values['email'], $headers, $body);
+
+                       return PEAR::isError($res) ?
+                                       Toolkit_Common::handleError($res) :
+                                       $res;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handlError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Returns an HTML version of the form
+     *
+     * @return string HTML version of the form
+     * @access public
+     */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       if ($this->process(array(&$this, 'processData'))) {
+                               $url    = BASE_URL . 'index.php?catid=' . MEMBER_SESSION_PAGE;
+                               $e      =& $this->getElement('email');
+                               $email  = $e->getValue();
+                               $output
+                    = "<p>Your Login Information has been sent to $email</p>" .
+                                         "<p>Continue to <a href=\"$url\">Login</a></p>";
+                       } else {
+                               $output = '<p>Email address not found.</p>';
+                       }
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHtml();
+               } else {
+                       $output .= parent::toHtml();
+               }
+
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/TripPlanner/Sessions.php b/Toolkit/Members/TripPlanner/Sessions.php
new file mode 100644 (file)
index 0000000..9373402
--- /dev/null
@@ -0,0 +1,291 @@
+<?php
+
+/**
+ * Sessions.php
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Sessions.php,v 1.3 2010/05/28 12:54:14 matrix Exp $
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Members_TripPlanner_Sessions
+ *
+ * Trying to place all the code for the storing of the member list to session
+ * into one place
+ * Takes the $_SESSION['wish_list'] used for the trip planner and
+ * add or removes members and their page id to the session
+ * if they're logged in with trip planner then they'll get everything saved to the
+ * database table member_session
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      <>
+ */
+class Toolkit_Members_TripPlanner_Sessions
+{
+    // {{{ Properties
+    /**
+     * Global PDO
+     * @var    object
+     * @access protected
+     */
+    public $dbh;
+
+    /**
+     * Auth object
+     * @var    object
+     * @access protected
+     */
+    protected $auth;
+
+    /**
+     * $_SESSION['wish_list']
+     * @var    array
+     * @access protected
+     */
+    protected $session;
+
+    // }}}
+    // {{{ __construct()
+
+    /**
+     * Set the Auth object ad Global PDO
+     *
+     * @param integer $pdo  Global pdo
+     * @param Auth    $Auth current Auth object used for valid session
+     *
+     * @return void
+     * @access public
+     */
+    function __construct($pdo, Auth $Auth)
+    {
+        $this->dbh     =& $pdo;
+        $this->auth    =& $Auth;
+        $this->session =& $_SESSION['wish_list'];
+    }
+
+    // }}}
+    // {{{ addRecord()
+
+    /**
+     * Add the record into session storing the page it was added on.
+     * page shold always have the catid.
+     * If the user is logged in then store it in database with contact_id
+     *
+     * @param unknown $memberId member_id of record
+     * @param unknown $catId    page catid
+     *
+     * @return void
+     * @access public
+     */
+    function addRecord($memberId, $catId)
+    {
+        if (ctype_digit($memberId) && $memberId) {
+            // add to the session the member record
+            $this->session[$memberId] = array(
+                'catid' => $catId
+            );
+            if ($this->isLoggedIn()) {
+                $cData = $this->auth->getAuthData();
+                try {
+                    $sql = "
+                    INSERT INTO member_session
+                    (contact_id, member_id, catid)
+                    VALUES
+                    (:contact_id, :member_id, :catid)";
+                    $stmt = $this->dbh->prepare($sql);
+                    $stmt->bindParam(":member_id", $memberId, PDO::PARAM_INT);
+                    $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT);
+                    $stmt->bindParam(":catid", $catId, PDO::PARAM_INT);
+                    $stmt->execute();
+                } catch(PDOException $e) {
+                    Toolkit_Common::handleError($e);
+                }
+            }
+        }
+    }
+
+    // }}}
+    // {{{ dumpList()
+
+    /**
+     * Dump the session for the list and
+     * if they are logged in then remove their list in the
+     * database.
+     *
+     * @return void
+     * @access public
+     */
+    function dumpList()
+    {
+        if ($this->isLoggedIn()) {
+            $cData = $this->auth->getAuthData();
+            $sql = "
+            DELETE
+              FROM member_session
+             WHERE contact_id = :contact_id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT);
+            $stmt->execute();
+        }
+        unset($this->session);
+        unset($_SESSION['wish_list']);
+    }
+
+    // }}}
+    // {{{ isLoggedIn()
+
+    /**
+     * Check the Auth object function checkAuth to see if the user has a valid
+     * login session.  If so then return true. If not then return false.
+     *
+     * @return boolean true valid login false invalid login
+     * @access public
+     */
+    function isLoggedIn()
+    {
+        if ($this->auth->checkAuth()) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    // }}}
+    // {{{ removeRecord()
+
+    /**
+     * Remove the record from the session.  If the user is logged in then
+     * also remove the data from the database.
+     *
+     * @param unknown $memberId member id for record
+     *
+     * @return void
+     * @access public
+     */
+    function removeRecord($memberId)
+    {
+        unset($this->session[$memberId]);
+        if ($this->isLoggedIn()) {
+            $cData = $this->auth->getAuthData();
+            //die('<p>'.print_r($cData, true).'</p>');
+            try {
+                $sql = "
+                DELETE FROM member_session
+                      WHERE member_id = :member_id
+                        AND contact_id = :contact_id";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(":member_id", $memberId, PDO::PARAM_INT);
+                $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT);
+                $stmt->execute();
+            } catch(PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+        }
+    }
+
+    // }}}
+    // {{{ retrieveList()
+
+    /**
+     * Retreive the list form the database storage and repopulate the accounts data
+     * to the session var $this->session = $_SESSION['wish_list']
+     *
+     * @return void
+     * @access public
+     */
+    function retrieveList()
+    {
+        if ($this->isLoggedIn()) {
+            $cData = $this->auth->getAuthData();
+            try {
+                $sql = "
+                SELECT *
+                  FROM member_session
+                 WHERE contact_id = :contact_id";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT);
+                $stmt->execute();
+                while ($row = $stmt->fetch()) {
+                    // don't dupe the list
+                    if (!$this->session[$row['member_id']]) {
+                        $this->session[$row['member_id']] = array(
+                            'catid' => $row['catid']
+                        );
+                    }
+                }
+            } catch(PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+        }
+    }
+
+    // }}}
+    // {{{ saveList()
+
+    /**
+     * Save the list for the user.  This is called on the login page after the
+     * session is repopulated out from database.  No worries about dupes here.
+     * this function checks for existing records then won't reinsert.
+     *
+     * @param int $contactId the id from contact table for lookup
+     *
+     * @return void
+     * @access public
+     */
+    function saveList($contactId = null)
+    {
+        if ($this->isLoggedIn() && is_array($this->session)) {
+            if (isset($contactId) && is_numeric($contactId)) {
+                $cData['id'] = $contactId;
+            } else {
+                $cData = $this->auth->getAuthData();
+            }
+            $sql = "
+            SELECT member_id
+              FROM member_session
+             WHERE contact_id = :contact_id";
+            try {
+                $getDat = $this->dbh->prepare($sql);
+                $getDat->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT);
+                $getDat->execute();
+                while ($row = $getDat->fetch()) {
+                    $mStoreSess[$row['member_id']] = $row['member_id'];
+                }
+            } catch(PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+            foreach ($this->session as $memberId => $sData) {
+                if (!$mStoreSess[$memberId]) {
+                    try {
+                        $sql = "
+                        INSERT INTO member_session
+                        (contact_id, member_id, catid)
+                        VALUES
+                        (:contact_id, :member_id, :catid)";
+                        $stmt = $this->dbh->prepare($sql);
+                        $stmt->bindParam(":member_id", $memberId, PDO::PARAM_INT);
+                        $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT);
+                        $stmt->bindParam(":catid", $sData['catid'], PDO::PARAM_INT);
+                        $stmt->execute();
+                    } catch(PDOException $e) {
+                        Toolkit_Common::handleError($e);
+                    }
+                }
+            }
+        }
+    }
+    // }}}
+}
+?>
diff --git a/Toolkit/Members/TripPlanner/TripAuth.php b/Toolkit/Members/TripPlanner/TripAuth.php
new file mode 100644 (file)
index 0000000..91d2e9b
--- /dev/null
@@ -0,0 +1,766 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Member Authentication
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: TripAuth.php,v 1.6 2010/06/22 11:45:34 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm
+ */
+
+require_once 'Auth.php';
+
+/**
+ * Methods for the memberdb authentication system
+ *
+ * Handles Cookie and session generation, id challenges and security for
+ * the memberdb application
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm
+ */
+class Toolkit_Members_TripPlanner_TripAuth extends Auth
+{
+       //      {{{     properties
+
+    /**
+     * Maximum idle time
+        *
+        * If more seconds pass before a new page request, then the user
+        * will have to re-authenticate back into the application.
+        * 1800 = 30 min
+        * 3600 = 1 hr
+        *
+     * @var    integer
+     * @access protected
+     */
+       protected $idleTime = 1800;
+
+    /**
+     * Authentication options for storage driver
+        *
+        * This is setup here, so it can be overridden in subclasses and merged
+        * into existing authentication options.
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $classOptions = array();
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * Sets up the storage driver
+     *
+     * @param Toolkit_Members_TripPlanner_AuthContainer $storageDriver storage driver
+     * @param string                                    $loginFunction (optional)Name of the function that
+        *                                                                                                 creates the login form
+     * @param boolean                                   $showLogin     (optional)Should the login form be
+        *                                                                                                 displayed if neccessary?
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+        Toolkit_Members_TripPlanner_AuthContainer $storageDriver,
+        $loginFunction = '',
+        $showLogin = true
+    ) {
+
+               parent::Auth($storageDriver, '', $loginFunction, $showLogin);
+        $this->setSessionName('TripPlanner');
+       }
+
+       //      }}}
+
+       //      {{{     loginForm()
+
+    /**
+     * Function to set up the regular login form
+     *
+     * @param unknown $uname  Last attempted username
+     * @param unknown $status The authorization status
+     * @param unknown &$auth  The authentication object
+        *
+     * @return void
+     * @access public
+     */
+       protected function loginForm($uname = null, $status = null, &$auth = null)
+       {
+               $login = new TripPlannerLoginForm('member_login',
+                                'post',
+                                BASE_URL . 'memberdb/index.php');
+        $login->setDbh(Toolkit_Database::getInstance());
+        $login->configureForm();
+        echo $login->toHtml();
+       }
+
+       //      }}}
+
+       //      {{{     passwordForm()
+
+    /**
+     * Function to set up the forgot password form
+     *
+     * @return void
+     * @access public
+     */
+       protected function passwordForm()
+       {
+               $pword = new TripPlannerPasswordForm('member_password');
+        $pword->setDbh(Toolkit_Database::getInstance());
+        $pword->configureForm();
+               echo $pword->toHtml();
+       }
+
+       //      }}}
+
+       //      {{{     setIdle()
+
+    /**
+     * Set the maximum idle time
+     *
+     * @param integer $time time in seconds
+     * @param boolean $add  (optional)add time to current maximum idle time or not
+        *
+     * @return void
+     * @access public
+     */
+       public function setIdle($time = null, $add = false)
+       {
+               $time = is_null($time) ? $this->idleTime : $time;
+               parent::setIdle($time, $add);
+       }
+
+       //      }}}
+}
+
+/**
+ * Handles rendering and validating the member login form
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_FormBuilder
+ */
+class TripPlannerLoginForm extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Custom rules to check for when validating the form
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Where to perform validation
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $validationType = 'client';
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param string  $formName    Form's name
+     * @param string  $method      (optional)Form's method defaults to 'POST'
+     * @param string  $action      (optional)Form's action
+     * @param string  $target      (optional)Form's target
+     * @param mixed   $attributes  (optional)Extra attributes for the <form> tag
+     * @param boolean $trackSubmit (optional)Whether to track if the form
+        *                                                         was submitted by adding a special hidden field
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               $this->template = dirname(__FILE__) . '/templates/currentTables/';
+       }
+
+       //      }}}
+
+       //      {{{     configureElements()
+
+    /**
+     * Sets up the elements to be configured for use with the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureElements()
+       {
+        $e = array();
+
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'formHdr',
+            'display' => Toolkit_Members_Admin_Controller::$listingType['singular'] . ' Login'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'username',
+            'display' => 'Username'
+        );
+               $e[] = array(
+            'type' => 'password',
+            'req' => true,
+            'name' => 'password',
+            'display' => 'Password'
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'doLogin',
+            'display' => 'Login now',
+            'opts' => array('id' => 'doLogin')
+        );
+               $e[] = array(
+            'type' => 'link',
+            'req' => false,
+            'name' => 'forgot',
+            'display' => 'Forgot your password? Click',
+            'opts' => BASE_URL . 'index.php?catid='.MEMBERS_CATEGORY.'&forgot=',
+            'att' => 'here'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Sets up the filters to be used with the form when submitted
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper method to setup form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{     configureRules()
+
+    /**
+     * Sets up required rules and extra defined rules for the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureRules()
+       {
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+    //  {{{ setDbh()
+
+    /**
+     * set the pdo to use for db calls
+     *
+     * @param PDO $pdo PHP Data Object to use
+     *
+     * @return void
+     * @access public
+     */
+    public function setDbh(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+
+    //  }}}
+       //      {{{     setupRenderers()
+
+    /**
+     * Inject custom renderers into the forms elements for custom display
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="form-warning-inside">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate('<tr><td colspan="2" class="member-login-forgot">{label} {element}</td></tr>', 'forgot');
+               $renderer->setElementTemplate('<tr><td colspan="2" align="center">{element}</td></tr>', 'doLogin');
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Returns an HTML version of the form
+     *
+     * @return string HTML version of the form
+     * @access public
+     */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       header('Location: ' . BASE_URL . 'memberdb/index.php');
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHtml();
+               } else {
+                       if ($_GET['status']) {
+                               switch ($_GET['status']) {
+                               case -1 :
+                                       $error = 'Your session has exceeded the maximum idle time';
+                                       break;
+
+                               case -2 :
+                                       $error = 'Your session has expired.';
+                                       break;
+
+                               case -3 :
+                                       $error = 'Invalid username or password.';
+                                       break;
+
+                               case -4 :
+                                       //      This is primarily used for Development.
+                                       //      Users should never be presented with this error.
+                                       $error = 'Invalid Container';
+                                       break;
+
+                               case -5 :
+                                       //      This is only thrown if the advanced security system
+                                       //      has detected a breach into the system.
+                                       $error = 'The system has encountered an error. Reference code: -5';
+                                       break;
+                               }
+                               $output = "<div id=\"form-warning-top\">$error</div>";
+                       }
+                       $output .= parent::toHtml();
+               }
+
+               return $output;
+       }
+
+       //      }}}
+}
+
+/**
+ * Handles rendering and validating the member password form
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ * @see       Toolkit_FormBuilder
+ */
+class TripPlannerPasswordForm extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+    /**
+     * Table to query when gathering information
+        *
+     * @var    string
+     * @access public
+     */
+       public $tableName = 'member';
+
+    /**
+     * Custom defined rules to validate against when the form is submitted
+        *
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    /**
+     * Where to perform validation
+        *
+     * @var    string
+     * @access protected
+     */
+       protected $validationType = 'client';
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Constructor
+     *
+     * @param string  $formName    Form's name
+     * @param string  $method      (optional)Form's method defaults to 'POST'
+     * @param string  $action      (optional)Form's action
+     * @param string  $target      (optional)Form's target
+     * @param mixed   $attributes  (optional)Extra attributes for the <form> tag
+     * @param boolean $trackSubmit (optional)Whether to track if the form
+        *                                                         was submitted by adding a special hidden field
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+               parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+               $this->template = dirname(__FILE__) . '/templates/currentTables/';
+       }
+
+       //      }}}
+
+       //      {{{     checkAddressExists()
+
+    /**
+     * Checks to see if the email address exists before allowing an email to go out
+     *
+     * @param string $value submitted email address
+        *
+     * @return boolean If the email address exists or not
+     * @access public
+     */
+       public function checkAddressExists($value)
+       {
+               try {
+                       $sql = "
+                SELECT count(*) AS total
+                  FROM {$this->tableName}
+                 WHERE member_contact_email = :mce";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mce', $value, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $stmt->bindColumn('total', $exists);
+                       $stmt->fetch();
+
+                       return (bool) $exists;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     configureElements()
+
+    /**
+     * Sets up the elements to be configured for use with the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureElements()
+       {
+        $e = array();
+
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'formHdr',
+            'display' => 'Email Reminder'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => true,
+            'name' => 'email',
+            'display' => 'Your Member Contact Email Address'
+        );
+               $e[] = array(
+            'type' => 'submit',
+            'req' => false,
+            'name' => 'submit',
+            'display' => 'Send'
+        );
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Sets up the filters to be used with the form when submitted
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Helper method to setup form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    //  }}}
+       //      {{{     configureRules()
+
+    /**
+     * Sets up required rules and extra defined rules for the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureRules()
+       {
+        $r = array();
+
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Invalid Email Format!',
+            'type' => 'email',
+            'format' => null,
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+               $r[] = array(
+            'element' => 'email',
+            'message' => 'ERROR: Cannot locate email address!',
+            'type' => 'callback',
+            'format' => array(&$this,
+            'checkAddressExists'),
+            'validation' => $this->validationType,
+            'reset' => true,
+            'force' => false
+        );
+
+               $this->setupRules($r);
+       }
+
+       //      }}}
+
+    //  {{{ setDbh()
+
+    /**
+     * set the pdo to use for db calls
+     *
+     * @param PDO $pdo PHP Data Object to use
+     *
+     * @return void
+     * @access public
+     */
+    public function setDbh(PDO $pdo)
+    {
+        $this->dbh = $pdo;
+    }
+
+    //  }}}
+       //      {{{     setupRenderers()
+
+    /**
+     * Inject custom renderers into the forms elements for custom display
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="form-warning-inside">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate('<tr><td colspan="2" align="center">{element}</td></tr>', 'submit');
+       }
+
+       //      }}}
+
+       //      {{{     processData()
+
+    /**
+     * Processes the data submitted by the form
+     *
+        * Gets the login credentials for the matching email address and mails
+        * them to that email address
+     *
+     * @param array $values submitted form values
+        *
+     * @return boolean Result of mail
+     * @access protected
+     */
+       protected function processData($values)
+       {
+               try {
+                       $sql = "
+                SELECT member_login, member_passwd
+                  FROM {$this->tableName}
+                 WHERE member_contact_email = :mce";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':mce', $values['email'], PDO::PARAM_STR);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+
+                       $htmlMsg
+                = "Here is your " . SITENAME . " password:<br><br>" .
+                                 "Login: {$row['member_login']}<br>" .
+                                 "Email: {$values['email']}<br>" .
+                                 "Password: {$row['member_passwd']}<br><br>";
+
+                       $msg
+                = "Here is your " . SITENAME . " password:\n\n" .
+                                 "Login: {$row['member_login']}\n" .
+                                 "Email: {$values['email']}\n" .
+                                 "Password: {$row['member_passwd']}";
+
+                       $crlf     = "\n";
+                       $mimeMail = new Mail_mime($crlf);
+                       $mimeMail->setFrom(SITENAME . ' <' . OWNER_EMAIL . '>');
+                       $mimeMail->setSubject('Your ' . SITENAME . ' Password');
+                       $mimeMail->setHTMLBody($htmlMsg);
+                       $mimeMail->setTXTBody($msg);
+
+                       $mail    =& Mail::factory('mail');
+                       $body    = $mimeMail->get();
+                       $headers = $mimeMail->headers($hdrs);
+
+                       $res = $mail->send($values['email'], $headers, $body);
+
+                       return PEAR::isError($res) ?
+                                       Toolkit_Common::handleError($res) :
+                                       $res;
+               } catch (PDOException $e) {
+                       Toolkit_Common::handlError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Returns an HTML version of the form
+     *
+     * @return string HTML version of the form
+     * @access public
+     */
+       public function toHtml()
+       {
+               $this->setupRenderers();
+               if ($this->validate()) {
+                       if ($this->process(array(&$this, 'processData'))) {
+                               $url    = BASE_URL . 'index.php?catid=' . MEMBERS_CATEGORY;
+                               $e      =& $this->getElement('email');
+                               $email  = $e->getValue();
+                               $output
+                    = "<p>Your Login Information has been sent to $email</p>" .
+                                         "<p>Continue to <a href=\"$url\">Member Login</a></p>";
+                       } else {
+                               $output = '<p>Email address not found.</p>';
+                       }
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHtml();
+               } else {
+                       $output .= parent::toHtml();
+               }
+
+               return $output;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/TripPlanner/googleMapData.php b/Toolkit/Members/TripPlanner/googleMapData.php
new file mode 100644 (file)
index 0000000..7de4944
--- /dev/null
@@ -0,0 +1,82 @@
+<?php
+/**
+ * googleMapData.php
+ *
+ * for contacts that forget their password sends out an email to if they're found.
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  Toolkit
+ * @package   Members_TripPlanner
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Forgot.php,v 1.4 2010/05/20 15:30:36 matrix Exp $
+ * @link      <>
+ */
+header('Content-type: text/xml');
+require_once '../../../setup.phtml';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+if (!is_array($_SESSION['wish_list'])) {
+    return false;
+}
+$xmlEncoder = new Toolkit_Members_Map();
+$is = new Toolkit_Image_Server();
+
+$members = implode(', ', array_keys($_SESSION['wish_list']));
+
+$sql = "
+    SELECT m.*, s.state_abb, c.city_name
+      FROM member m
+      FULL JOIN state s
+     USING (state_id)
+      FULL JOIN city c
+     USING (city_id)
+     WHERE member_id IN ($members)";
+
+$dbh = Toolkit_Database::getInstance();
+try {
+       $membersArray = array();
+       $urlFormat = BASE_URL . 'Toolkit/Members/memberClickThru.php?member_id=%s&href=%s';
+       $moreInfoFormat = BASE_URL . 'member-profile/%s/%s/';
+       foreach ($dbh->query($sql, PDO::FETCH_ASSOC) as $row) {
+               $url = sprintf(
+                       $format,
+                       $row['member_id'],
+                       urlencode(str_replace('http://', '', $row['url']))
+               );
+               $moreInfoUrl = sprintf(
+                       $moreInfoFormat,
+                       MEMBER_SESSION_PAGE,
+                       $row['member_id']
+               );
+//             list($imgWidth, $imgHeight,) = $is->getImageSize(TRIP_PLANNER_MAP_IMG . $row['logo']);
+               $membersArray[] = array(
+                       'member_id' => $row['member_id'],
+                       'member_name' => $row['member_name'],
+                       'url_member_name' => urlencode($row['member_name']),
+                       'lat' => $row['lat'],
+                       'lng' => $row['lon'],
+                       'street' => $row['street'],
+                       'state_abb' => $row['state_abb'],
+                       'city_name' => $row['city_name'],
+                       'zip' => $row['zip'],
+                       'phone' => $row['phone'],
+                       'url' => $url,
+                       'website' => $row['url'],
+                       'logoPath' => TRIP_PLANNER_MAP_IMG,
+                       'logo' => $row['logo'],
+                       'logoWidth' => $imgWidth,
+                       'logoHeight' => $imgHeight,
+                       'moreInfoUrl' => $moreInfoUrl,
+               );
+       }
+} catch (PDOException $e) {
+       Toolkit_Common::handleError($e);
+}
+
+echo $xmlEncoder->getMemberXML($membersArray);
+?>
diff --git a/Toolkit/Members/TripPlanner/helpme.html b/Toolkit/Members/TripPlanner/helpme.html
new file mode 100644 (file)
index 0000000..218289f
--- /dev/null
@@ -0,0 +1,48 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+<html>
+  <head>
+       <title>Help Me</title>
+<style type="text/css">
+<!-- 
+body {
+       padding: 10px;
+       font-family: arial, sans-serif;
+       font-size: 0.8em;
+} 
+li {
+       margin-top: 1em;
+}
+-->
+</style> 
+</head>
+  <body>
+<div id="wrapper">
+<p>
+This section lets you create your own online itinerary. As you find items on this website that may be of interest to you, simply click the "Add to 
+Travel Planner" icon. Each item will then get added to your list. Once you have 
+completed adding items to your planner list, you may take the following actions:</p>
+
+<ol>
+       <li>Request Info<br>
+This will send an email directly to each individual business using our "Send Me More Information" 
+form. For the items you have added to your list that do not have an 
+email, we will give you their phone number. </li>
+
+<li>Print This List<br>
+Prints the list to your printer, if you have one.</li>
+
+<li>View Map<br>
+This will display your itinerary on a Map, also allowing you to retrieve driving directions.
+</li>
+
+<li>
+Save your Trip Planner<br>
+Creates an account with this website so you can access your itinerary later.
+</li>
+
+</ol>
+
+</div>
+  </body>
+</html>
diff --git a/Toolkit/Members/TripPlanner/login.php b/Toolkit/Members/TripPlanner/login.php
new file mode 100644 (file)
index 0000000..35d4c6f
--- /dev/null
@@ -0,0 +1,67 @@
+<?php
+
+/**
+ * login.php
+ *
+ * To login the front end user using the contact table
+ * with email as username and the password field using
+ * a extended class from Auth in the PEAR library.
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: login.php,v 1.6 2010/06/22 11:45:34 jamie Exp $
+ * @link      <>
+ */
+$includeFunctions = false;
+
+/**
+ * Description for require_once
+ */
+require_once '../../../setup.phtml';
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$authContainer = new Toolkit_Members_TripPlanner_AuthContainer(
+       Toolkit_Database::getInstance(),
+       array(
+               'table'                 => 'contact',
+               'usernamecol'   => 'email',
+               'passwordcol'   => 'password',
+               'db_fields'             => array('id', 'fname', 'lname'),
+               'cryptType'             => 'md5',
+       )
+);
+$tripPlannerAuth = new Toolkit_Members_TripPlanner_TripAuth(
+       $authContainer,
+       '',
+       false
+);
+$tripPlannerAuth->setIdle();
+$tripPlannerAuth->start();
+
+if (isset($_GET['logout'])) {
+       $tripPlannerAuth->logout();
+}
+
+if (!$tripPlannerAuth->checkAuth()) {
+       //      Manually adjust the authentication status for empty credentials
+       if (empty($_POST['username']) || empty($_POST['password'])) {
+               $status = -3;
+       }
+       $status = $tripPlannerAuth->getStatus();
+       header('Location: ' . BASE_URL . 'index.php?catid=' . MEMBER_SESSION_PAGE . '&status=' . $status);
+} else {
+    $sessionList = new Toolkit_Members_TripPlanner_Sessions(
+               Toolkit_Database::getInstance(),
+        $tripPlannerAuth
+       );
+    $sessionList->retrieveList();
+    $sessionList->saveList();
+       header('Location: ' . BASE_URL . 'index.php?catid=' . MEMBER_SESSION_PAGE);
+}
+?>
diff --git a/Toolkit/Members/TripPlanner/memberList.php b/Toolkit/Members/TripPlanner/memberList.php
new file mode 100755 (executable)
index 0000000..7419b88
--- /dev/null
@@ -0,0 +1,56 @@
+<?php
+
+/**
+ * wish-list.php
+ *
+ * for adding and removing members/businesses to a session
+ * storing their email addresses and names
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: memberList.php,v 1.2 2010/05/15 16:35:33 jamie Exp $
+ * @link      <>
+ */
+$includeFunctions = false;
+/**
+ * requires setup.phtml
+ */
+require_once '../../../setup.phtml';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$authContainer = new Toolkit_Members_TripPlanner_AuthContainer(
+       Toolkit_Database::getInstance(),
+       array(
+               'table'                 => 'contact',
+               'usernamecol'   => 'email',
+               'passwordcol'   => 'password',
+               'db_fields'             => array('id', 'fname', 'lname'),
+               'cryptType'             => 'md5',
+       )
+);
+
+$tripPlannerAuth = new Toolkit_Members_TripPlanner_TripAuth(
+       $authContainer,
+       '',
+       false
+);
+$tripPlannerAuth->setIdle();
+$tripPlannerAuth->start();
+$sessionList = new Toolkit_Members_TripPlanner_Sessions(
+       Toolkit_Database::getInstance(),
+       $tripPlannerAuth
+);
+if ($_SESSION['wish_list'][$_REQUEST['member_id']]) {
+    $sessionList->removeRecord($_REQUEST['member_id']);
+} else {
+    $sessionList->addRecord($_REQUEST['member_id'], $_REQUEST['catid']);
+}
+echo count($_SESSION['wish_list']);
+?>
diff --git a/Toolkit/Members/TripPlanner/tripPlannerMap.php b/Toolkit/Members/TripPlanner/tripPlannerMap.php
new file mode 100644 (file)
index 0000000..e0ad769
--- /dev/null
@@ -0,0 +1,33 @@
+<?php
+/**
+ * tripPlannerMap.php
+ *
+ * for contacts that forget their password sends out an email to if they're found.
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  Toolkit
+ * @package   Members_TripPlanner
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: Forgot.php,v 1.4 2010/05/20 15:30:36 matrix Exp $
+ * @link      <>
+ */
+
+require_once '../../../setup.phtml';
+?>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<title>The Official Travel Website for Michigan's Upper Peninsula</title>
+<meta http-equiv="content-type" content="text/html;charset=utf-8">
+<meta http-equiv="imagetoolbar" content="no">
+<meta http-equiv="imagetoolbar" content="false">
+<script type="text/javascript" src="<?php echo GLM_APP_BASE_URL;?>libjs/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
+<script type="text/javascript" src="<?php echo BASE_URL;?>trip-planner-map.js" type="text/javascript"></script>
+<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
+</head>
+<body>
+       <div id="map-canvas" style="width: 800px; height: 550px"></div>
+</body>
diff --git a/Toolkit/Members/TripPlanner/wish-list.php b/Toolkit/Members/TripPlanner/wish-list.php
new file mode 100755 (executable)
index 0000000..2c7ea1f
--- /dev/null
@@ -0,0 +1,72 @@
+<?php
+
+/**
+ * wish-list.php
+ *
+ * for adding and removing members/businesses to a session
+ * storing their email addresses and names
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: wish-list.php,v 1.6 2010/06/22 12:00:10 jamie Exp $
+ * @link      <>
+ */
+//die('<pre>'.print_r($_REQUEST, true).'</pre>');
+$includeFunctions = false;
+/**
+ * requires setup.phtml
+ */
+require_once '../../../setup.phtml';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$authContainer = new Toolkit_Members_TripPlanner_AuthContainer(
+       Toolkit_Database::getInstance(),
+       array(
+               'table'                 => 'contact',
+               'usernamecol'   => 'email',
+               'passwordcol'   => 'password',
+               'db_fields'             => array('id', 'fname', 'lname'),
+               'cryptType'             => 'md5',
+       )
+);
+
+$tripPlannerAuth = new Toolkit_Members_TripPlanner_TripAuth(
+       $authContainer,
+       '',
+       false
+);
+$tripPlannerAuth->setIdle();
+$tripPlannerAuth->start();
+$sessionList = new Toolkit_Members_TripPlanner_Sessions(
+       Toolkit_Database::getInstance(),
+       &$tripPlannerAuth
+);
+if ($_SESSION['wish_list'][$_REQUEST['member_id']]) {
+    $sessionList->removeRecord($_REQUEST['member_id']);
+    $add = false;
+} else {
+    $sessionList->addRecord($_REQUEST['member_id'], $_REQUEST['catid']);
+    $add = true;
+}
+
+//remove the email from GET array and goback to member detail page
+unset($_REQUEST['member_email']);
+if (is_array($_REQUEST)) {
+       foreach ($_REQUEST as $pname => $pval) {
+               if ($pval) {
+                       $param_part[] = $pname.'='.urlencode($pval);
+               }
+       }
+}
+if (is_array($param_part)) {
+       $params = implode("&", $param_part);
+}
+
+header("location: " . $_SERVER['HTTP_REFERER']);
diff --git a/Toolkit/Members/TripPlannerList.php b/Toolkit/Members/TripPlannerList.php
new file mode 100644 (file)
index 0000000..5f05914
--- /dev/null
@@ -0,0 +1,485 @@
+<?php
+
+/**
+ * TripPlannerList.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id$
+ * @link      <>
+ */
+
+/**
+ * Short description for class
+ *
+ * Long description (if any) ...
+ *
+ * @category  Toolkit
+ * @package   Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      <>
+ */
+class Toolkit_Members_TripPlannerList
+{
+    //  {{{ properties
+
+    /**
+     * Database handler
+     * @var    string
+     * @access protected
+     */
+    public $dbh;
+
+    /**
+     * Description for $plannerListPageId
+     * @var integer
+     * @access protected
+     */
+    protected $plannerListPageId;
+
+    /**
+     * Description for $plannerFormPageId
+     * @var integer
+     * @access protected
+     */
+    protected $plannerFormPageId;
+
+    /**
+     * Description for $pageGateway
+     * @var Toolkit_Toolbox_PageGatewayAbstract
+     * @access protected
+     */
+       protected $pageGateway;
+
+    //  }}}
+    //  {{{  __construct()
+
+    /**
+     * class constructor
+     *
+     * Only setup values need be done here
+     * any work need to be done within methods
+     *
+     * @param Toolkit_Toolbox_PageGatewayAbstract $gateway gateway
+     * @param PDO                                 $pdo     PDO reference
+     *
+     * @return void
+     * @access public
+     */
+    function __construct(
+               Toolkit_Toolbox_PageGatewayAbstract $gateway,
+               PDO $pdo
+       ) {
+               $this->pageGateway = $gateway;
+        $this->dbh = $pdo;
+        // These settings are used to override flexyOptions.
+        $this->flexyConfig = Toolkit_Members::getFlexyOptions();
+        $this->pagerOptions['containerClass'] = 'pages';
+        $this->plannerListPageId = MEMBER_SESSION_PAGE;
+        $this->plannerFormPageId = MEMBER_SESSION_FORM;
+    }
+
+    //  }}}
+
+       //      {{{ getAncestors()
+
+       /**
+        * getAncestors:get the ancestors for this category
+        *
+        * @param integer $catid catid
+        * @param integer $count starting counter
+        *
+        * @return array
+        * @access  public
+        */
+       function getAncestors($catid, $count = 0)
+       {
+        static $ancestors;
+        if (!$ancestors || $count == 0) {
+            $ancestors = array();
+        }
+               if ($catid) {
+                       $page = $this->pageGateway->find($catid);
+                       $ancestors[$count]['id']    = $catid;
+                       $ancestors[$count]['label'] = $page['navigation_name'];
+                       $ancestors[$count]['link'] 
+                = Toolkit_Template_Page::getSeoUrl($this->pageGateway, $catid);
+                       $this->getAncestors($page['parent'], ++$count);
+                       $ancestors[$count]['link'] 
+                = Toolkit_Template_Page::getSeoUrl($this->pageGateway, $res['id']);
+                       $this->getAncestors($res['parent'], ++$count);
+
+                       return array_reverse($ancestors);
+               }
+       }
+
+       //      }}}
+    // {{{ getSessionList()
+
+
+    /**
+     * get list from session
+     *
+     * @return void
+     * @access public
+     */
+    function getSessionList()
+    {
+        // for the session list need to sort by categories then
+        // we'll have to go through the session first and organize to what category they're in
+        // then run query
+        // have to order by the page name we'll need to find there names first then
+        $sql = "
+            SELECT member_name
+              FROM member
+             WHERE member_id = :member_id";
+        $getMemberName = $this->dbh->prepare($sql);
+        if (is_array($_SESSION['wish_list']) && !empty($_SESSION['wish_list'])) {
+            foreach ($_SESSION['wish_list'] as $member_id => $mData) {
+                               $page = $this->pageGateway->find($mData['catid']);
+                try {
+                    $getMemberName->bindParam(":member_id", $member_id, PDO::PARAM_INT);
+                    $getMemberName->execute();
+                    $memberName = $getMemberName->fetchColumn();
+                    $members[$page['navigation_name']][$memberName] = $member_id;
+                } catch(PDOException $e) {
+                    Toolkit_Common::handleError($e);
+                }
+            }
+            // for sorting members by the page they're added from
+            natSort($members);
+            try {
+                $sql = "
+                SELECT m.*, c.city_name AS city, s.state_name AS state,
+                       s.state_abb AS state_abbr,
+                       m.street||', '||c.city_name||', '||s.state_name||', '||m.zip AS address
+                  FROM member m
+                       JOIN state s USING (state_id)
+                       JOIN city c USING (city_id)
+                 WHERE member_id = :member_id";
+                $stmt = $this->dbh->prepare($sql);
+                if (is_array($members)) {
+                    $count = 0;
+                    foreach ($members as $toolbboxPageName => $memberList) {
+                        // for sorting members under each page
+                        natSort($memberList);
+                        foreach ($memberList as $memberName => $member_id) {
+                            $stmt->bindParam(":member_id", $member_id, PDO::PARAM_INT);
+                            $stmt->execute();
+                            // set record data
+                            $catid             = $_SESSION['wish_list'][$member_id]['catid'];
+                            $recordSet[$count] = $stmt->fetch();
+                            // setup the breadCrumbs
+                            $recordSet[$count]['breadCrumbs'] = $this->printAncestors($catid);
+                            // setup delete link
+                            $recordSet[$count]['deleteUrl'] = BASE_URL .
+                                'Toolkit/Members/TripPlanner/' .
+                                'wish-list.php?catid=' . $_REQUEST['catid'] .
+                                '&member_id=' . $member_id;
+                            // setup the url
+                            $recordSet[$count]['urlText'] = $recordSet[$count]['url'];
+                            if ($recordSet[$count]['url']) {
+                                $recordSet[$count]['url']     = BASE_URL .
+                                    'Toolkit/Members/memberClickThru.php' .
+                                    '?member_id=' . $member_id .
+                                    '&href=' . urlencode($recordSet[$count]['url']);
+                            }
+                            ++$count;
+                        }
+                    }
+                    if (is_array($recordSet)) {
+                        $temp = new HTML_Template_Flexy($this->flexyConfig);
+                        $page = new stdClass;
+                        $page->accountUrl  = Toolkit_Template_Page::getSeoUrl($this->pageGateway, $this->plannerFormPageId);
+                                               $page->forgotUrl   = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=forgot';
+                        $page->loginUrl    = BASE_URL . 'Toolkit/Members/TripPlanner/login.php';
+                           $page->logoutUrl   = BASE_URL . 'Toolkit/Members/TripPlanner/login.php?logout=1';
+                        $page->saveUrl     = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Save+List';
+                        $page->requestUrl  = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Send+List';
+                        $page->loginStat   = ($_REQUEST['status']) ? 'Invalid username or password.': '';
+                        $page->isLoggedIn  = $this->isLoggedIn();
+                        $page->username    = $page->isLoggedIn;
+                        $page->baseurl     = BASE_URL;
+                        $page->recordSet   = $recordSet;
+                        $page->numberedSet = count($recordSet);
+                        $temp->compile("tripPlannerList.tpl");
+                        $out .= $temp->BufferedOutputObject($page);
+                    }
+                }
+                //echo '<pre>'.print_r($page, true).'</pre>';
+                echo $out;
+            } catch(PDOException $e) {
+                 Toolkit_Common::handleError($e);
+            }
+        } else {
+            echo $this->showEmpty();
+        }
+    }
+
+    // }}}
+
+    // {{{ isLoggedIn()
+
+    /**
+     * check if user is logged in or not
+     *
+     * @access public
+     * @return string
+     */
+    function isLoggedIn()
+    {
+               $authContainer = new Toolkit_Members_TripPlanner_AuthContainer(
+                       Toolkit_Database::getInstance(),
+                       array(
+                               'table'                 => 'contact',
+                               'usernamecol'   => 'email',
+                               'passwordcol'   => 'password',
+                               'db_fields'             => array('id', 'fname', 'lname'),
+                               'cryptType'             => 'md5',
+                       )
+               );
+
+        $tripPlannerAuth = new Toolkit_Members_TripPlanner_TripAuth(
+                       $authContainer,
+                       '',
+                       false
+               );
+        $tripPlannerAuth->setIdle();
+        $tripPlannerAuth->start();
+
+        $test = $tripPlannerAuth->checkAuth();
+        if ($test) {
+            // give back the username
+            return $tripPlannerAuth->getUsername();
+        } else {
+            return false;
+        }
+    }
+
+    // }}}
+
+       //      {{{ printAncestors()
+
+       /**
+        * printAncestors
+        *
+        * @param mixed $catid page id
+        *
+        * @access public
+        * @return string
+        */
+       function printAncestors($catid)
+       {
+               $ancestors = $this->getAncestors($catid, 0);
+               if (is_array($ancestors)) {
+                       for ($i = 0; $i < count($ancestors); ++$i) {
+                $out[] = '<a href="' .
+                    $ancestors[$i]["link"] .
+                    '">' . $ancestors[$i]["label"] . '</a>';
+                       }
+                       if (is_array($out)) {
+                               return implode(" / ", $out);
+                       }
+               }
+       }
+
+       //      }}}
+
+    // {{{ saveList()
+
+
+    /**
+     * Short description for function
+     *
+     * Long description (if any) ...
+     *
+     * @return string Return description (if any) ...
+     * @access public
+     */
+    function saveList()
+    {
+        if ($this->isLoggedIn()) {
+            $contactId = $_SESSION['_authsession']['data']['id'];
+            // if they already have something saved then wipe it out.
+            // (only one list per contact)
+            try {
+                $sql = "
+                                       DELETE FROM member_session
+                                        WHERE contact_id = :contact_id";
+                $del = $this->dbh->prepare($sql);
+                $del->bindParam(":contact_id", $contactId, PDO::PARAM_INT);
+                $del->execute();
+            } catch(PDOException $e) {
+                Toolkit_Common::handleError($e);
+            }
+
+            $sql = "
+                               INSERT INTO member_session (member_id, contact_id, catid)
+                               VALUES (:member_id,:contact_id,:catid)";
+            $stmt = $this->dbh->prepare($sql);
+            if (is_array($_SESSION['wish_list'])) {
+                foreach ($_SESSION['wish_list'] as $member_id => $mData) {
+                    $catid = $mData['catid'];
+                    try {
+                        $stmt->bindParam(
+                                                       ':member_id',
+                                                       $member_id,
+                                                       PDO::PARAM_INT
+                                               );
+                        $stmt->bindParam(
+                                                       ':contact_id',
+                                                       $contactId,
+                                                       PDO::PARAM_INT
+                                               );
+                        $stmt->bindParam(':catid', $catid, PDO::PARAM_INT);
+                        $stmt->execute();
+                    } catch(PDOException $e) {
+                        Toolkit_Common::handleError($e);
+                    }
+                }
+                $html = '<p>You list has been saved.</p>';
+            }
+        }
+        return $html;
+    }
+
+    // }}}
+    // {{{ show()
+
+
+    /**
+     * Calls the appropiate function for listing,saving,sending
+     * or printing the list also will need to handle grabbing list from
+     * database and repopulate the session.
+     *
+     * @return void
+     * @access public
+     */
+    function show()
+    {
+        echo $this->toHTML();
+    }
+
+    // }}}
+    // {{{ showEmpty()
+
+    /**
+     * shows the template tripPlannerNoList.tpl
+     *
+     * @access public
+     * @return string
+     */
+    function showEmpty()
+    {
+        $temp             = new HTML_Template_Flexy($this->flexyConfig);
+        $temp->compile("tripPlannerNoList.tpl");
+        $page             = new stdClass;
+        $page->accountUrl = Toolkit_Template_Page::getSeoUrl(
+                       $this->pageGateway,
+                       $this->plannerFormPageId
+               );
+        $page->forgotUrl  = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=forgot';
+        $page->loginUrl   = BASE_URL . 'Toolkit/Members/TripPlanner/login.php';
+        $page->logoutUrl  = BASE_URL . 'Toolkit/Members/TripPlanner/login.php?logout=1';
+        $page->saveUrl    = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Save+List';
+        $page->requestUrl = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Send+List';
+        $page->loginStat  = ($_REQUEST['status']) ? 'Invalid username or password.': '';
+        $page->isLoggedIn = $this->isLoggedIn();
+        $page->username   = $page->isLoggedIn;
+        $page->baseurl    = BASE_URL;
+        return $temp->BufferedOutputObject($page);
+    }
+
+    // }}}
+
+    // {{{ toHTML()
+
+    /**
+     * Description for toHtml
+     *
+     * Long description (if any) ...
+     *
+     * @return string Return description (if any) ...
+     * @access public
+     */
+    function toHTML()
+    {
+               $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'gallery/thickbox-3.1.1.js';
+               $GLOBALS['styleSheets'][]   = GLM_APP_BASE_URL . 'gallery/gallery.css';
+               $GLOBALS['styleSheets'][]   = GLM_APP_BASE_URL . 'gallery/thickbox.css';
+               $GLOBALS['styleSheets'][]   = BASE_URL . 'Toolkit/Members/css/member.css';
+
+        if (   is_array($_SESSION['wish_list'])
+                       && !empty($_SESSION['wish_list'])
+               ) {
+            switch ($_REQUEST['cPage']) {
+            case "Send List":
+                $pp = new Toolkit_Contacts_SendTripPlanner(
+                                       $this->dbh,
+                    'TravelList',
+                    'post',
+                    BASE_URL .
+                    'index.php?catid='.$this->plannerListPageId
+                               );
+                $pp->configureForm();
+                $html = $pp->toHTML();
+                break;
+
+            case "Save List":
+                $html = $this->saveList();
+                $html .= $this->getSessionList();
+                break;
+
+            case "forgot":
+                $pp = new Toolkit_Members_TripPlanner_Forgot(
+                                       $this->dbh,
+                    'TravelList',
+                    'post',
+                    BASE_URL .
+                    'index.php?catid='.$this->plannerListPageId.'&cPage=forgot'
+                               );
+                $pp->configureForm();
+                $html = $pp->toHTML();
+                break;
+
+            case "Login":
+                break;
+
+            case "Show List":
+            default:
+                $html = $this->getSessionList();
+                break;
+            }
+        } else {
+            switch ($_REQUEST['cPage']) {
+            case "forgot":
+                $pp = new Toolkit_Members_TripPlanner_Forgot(
+                                       $this->dbh,
+                    'TravelList',
+                    'post',
+                    BASE_URL .
+                    'index.php?catid='.$this->plannerListPageId.'&cPage=forgot'
+                               );
+                $pp->configureForm();
+                $html = $pp->toHTML();
+                break;
+
+            default:
+                $html = $this->showEmpty();
+                break;
+            }
+        }
+
+        return $html;
+    }
+
+    // }}}
+}
diff --git a/Toolkit/Members/UserSearchForm.php b/Toolkit/Members/UserSearchForm.php
new file mode 100644 (file)
index 0000000..1f0cb02
--- /dev/null
@@ -0,0 +1,828 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Member Search Form Class
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: UserSearchForm.php,v 1.27 2010/07/14 23:31:14 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Member Search Form
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_UserSearchForm
+{
+       //      {{{     properties
+
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $memberCatsAssignedToPage = array();
+
+    /**
+     * Description for $memberRegiansAssignedToPage
+     * @var array
+     * @access protected
+     */
+       protected $memberRegionsAssignedToPage = array();
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member';
+
+       /**
+        * Array of data that holds the meta data info on the table
+        *
+        * Contains information on the type of fields in the database.
+        * That way when we run our automated SQL queries with our PDO
+        * we can properly bind data to our SQL queries.  This will
+        * allow for one more layer of protection against any sql
+        * injection attempts.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableMetaData;
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The name of the template used to render the member info form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'userSearchForm.html';
+
+       /**
+        * Form access from inside the template
+        *
+        * @var object
+        * @access protected
+        */
+       protected $view;
+
+       /**
+        * registered rules for the form
+        *
+        * @var array
+        * @access protected
+        */
+       protected $registeredRules = array();
+
+    /**
+     * catid to use in the form
+     *
+     * @var    integer
+     * @access private
+     */
+    private $_catid;
+
+    /**
+     * Database Connection Object
+     *
+     * @var PDO
+     */
+    protected $dbh;
+
+    const PARENT_CATEGORY_ACTIVITIES = 7;
+    const PARENT_CATEGORY_PARKS      = 8;
+
+       //      }}}
+
+    public function __construct()
+    {
+        $this->dbh = Toolkit_Database::getInstance();
+    }
+
+       //      {{{ configureFilters()
+
+       /**
+        * Setup the filters to apply to the elements before we are
+        * handed the values submitted
+        *
+     * @return void
+        * @access public
+        */
+       public function configureFilters()
+       {
+       }
+
+       //      }}}
+       //      {{{ configureForm()
+
+       /**
+        * Helper method to configure the entire form
+        *
+     * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+        * @access public
+        */
+       public function configureForm(PDO $dbh, Config_Container $c)
+       {
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+       }
+
+       //      }}}
+    //  {{{ createAvailableMemberTypesFromRegions()
+
+    /**
+     * Get available categories from members assigned to regions
+     *
+     * @param PDO   $dbh     Database handler
+     * @param array $regions Available regions to get members from
+     *
+     * @return void
+     * @access protected
+     */
+    protected function createAvailableMemberTypesFromRegions(
+               PDO $dbh,
+               array $regions
+       ) {
+        try {
+            $regionCats   = array();
+            $availRegions = array();
+            $availCats    = array();
+            $mainCats     = array();
+            if (!empty($this->memberCatsAssignedToPage)) {
+                foreach ($this->memberCatsAssignedToPage as $i) {
+                    $cats = Toolkit_Common::getHierarchicalTreeStructure(
+                        $dbh,
+                        'category',
+                        'category_id',
+                        'parent_id',
+                        'pos',
+                        $i,
+                        0,
+                        false
+                    );
+                    if (is_array($cats) && !empty($cats)) {
+                        $availCats = array_merge($availCats, array_keys($cats));
+                    }
+                }
+            }
+            if ($availCats && !empty($availCats)) {
+                $availCats = implode(', ', $availCats);
+            }
+
+            if (!empty($this->memberRegionsAssignedToPage)) {
+                $availRegions = implode(', ', $availRegions);
+            }
+            $pNameSql = "
+            SELECT name
+              FROM category
+             WHERE parent_id = :cid";
+            $getParentName = $dbh->prepare($pNameSql);
+            $sql = "SELECT distinct c.category_id, c.parent_id,
+                                          ( SELECT name
+                               FROM category
+                              WHERE category_id = c.parent_id) AS parent,
+                                          c.name AS category
+                                         FROM category c
+                     WHERE c.category_id IN (
+                            SELECT distinct c.category_id
+                              FROM category c, member_category mc, member m
+                             WHERE
+                              c.category_id = mc.category_id
+                               AND mc.member_id = m.member_id
+                               AND m.active";
+            if ($regions) {
+                $sql .= " AND (region = :rid OR region IS NULL) ";
+            }
+
+            $sql .= ")
+                       AND c.parent_id > 0 ";
+            if ($availRegions) {
+                $sql .= " AND region in ($availRegions) ";
+            }
+            if ($availCats) {
+                $sql .= " AND c.category_id in ($availCats) ";
+            }
+            $sql .=  " ORDER BY c.name";
+            $stmt = $dbh->prepare($sql);
+            if ($regions) {
+                foreach ($regions as $i => $j) {
+                    if (is_numeric($i)) {
+                        $stmt->bindParam(':rid', $i, PDO::PARAM_INT);
+                        $stmt->execute();
+                        $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
+                        foreach ($row as $x) {
+                            $regionCats[$i][$x['parent_id']][$x['category_id']]
+                                = $x['category'];
+                            $mainCats[$x['parent_id']] = $x['parent'];
+                        }
+                    }
+                }
+            } else {
+                $stmt->execute();
+                $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
+                foreach ($row as $x) {
+                    $regionCats[$i][$x['parent_id']][$x['category_id']]
+                        = $x['category'];
+                    $mainCats[$x['parent_id']] = $x['parent'];
+                }
+            }
+
+                       asort($mainCats);
+            $this->regionCategories = $regionCats;
+            $this->mainCats = $mainCats;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+       //      {{{     getAvailableRegions()
+
+    /**
+     * Returns all available regions that derive from members assigned to
+     * this page
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array regions available to this page
+     * @access protected
+     */
+       protected function getAvailableRegions(PDO $dbh)
+       {
+        // Make sure we have all sub-cats nos also
+
+
+        try {
+            $sql = "SELECT DISTINCT c.category_id
+                      FROM category c, member_category mc, member m
+                     WHERE c.category_id = mc.category_id
+                       AND m.member_id = mc.member_id
+                       AND m.active ";
+            if (is_array($this->memberCatsAssignedToPage)
+                && !empty($this->memberCatsAssignedToPage)) {
+                $mcats = implode(',', $this->memberCatsAssignedToPage);
+                $sql  .= " AND c.parent_id IN ($mcats)";
+            }
+            $mcstmt = $this->dbh->prepare($sql);
+            $mcstmt->execute();
+        } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+        while ($row = $mcstmt->fetch()) {
+                   $this->memberCatsAssignedToPage[] = $row['category_id'];
+               }
+
+           $regions = array();
+        $memCats = array();
+               try {
+
+                   $sql = "
+                SELECT *
+                  FROM region
+                 WHERE region_id in (
+                        SELECT distinct(region)
+                          FROM member
+                          WHERE active = 't'
+                          AND region is not null";
+            if (!empty($this->memberCatsAssignedToPage)) {
+                $sql .= " AND member_id in (SELECT distinct(member_id)
+                    FROM member_category
+                    WHERE category_id in (".implode(',', $this->memberCatsAssignedToPage).")
+                )";
+            }
+
+            if (!empty($this->memberRegionsAssignedToPage)) {
+                $sql .= " AND region_id in (".implode(',', $this->memberRegionsAssignedToPage).") ";
+            }
+
+            $sql .= " )
+                 ORDER BY region_name";
+
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch()) {
+                $regions[$row['region_id']] = $row['region_name'];
+            }
+
+            asort($regions);
+
+                       return $regions;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberAmenities()
+
+    /**
+     * Get all the amenities for the member
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array member amenities
+     * @access protected
+     */
+       protected function getMemberAmenities(PDO $dbh)
+       {
+               try {
+                       $amenities = array();
+            $sql = "
+            SELECT accommodations
+              FROM category
+             WHERE category_id = :cid";
+            $isAccommodationCategory = $dbh->prepare($sql);
+                       $sql = "
+            SELECT a.*
+              FROM amenity a
+           NATURAL JOIN member_amenity ma
+           NATURAL JOIN member_category mc
+           NATURAL JOIN member m
+             WHERE m.new_member <> CAST(1 AS BOOLEAN)
+               AND m.active = CAST(1 AS BOOLEAN)
+               AND a.display_form = CAST(1 AS BOOLEAN)
+               AND (mc.category_id = :cid
+                OR mc.category_id in (
+                    SELECT category_id
+                      FROM category
+                     WHERE parent_id      = :cid))
+             ORDER BY amenity_name";
+
+                       $stmt = $dbh->prepare($sql);
+                       foreach ($this->memberCatsAssignedToPage as $id) {
+                $isAccommodationCategory->bindParam(':cid', $id, PDO::PARAM_INT);
+                $isAccommodationCategory->execute();
+                if (!$isAccommodationCategory->fetchColumn()) {
+                    continue;
+                }
+                               $stmt->bindParam(':cid', $id, PDO::PARAM_INT);
+                               $stmt->execute();
+                               while ($row = $stmt->fetch()) {
+                                       $amenities[$row['amenity_name']] = $row['amenity_id'];
+                               }
+                       }
+                       return $amenities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberCats()
+
+    /**
+     * Get all the main categories available from the categories that
+     * are assigned to the page.
+     *
+     * If a main category is assigned to a page, then add to list.
+     *
+     * If a sub category is assgined to page, then add parent (main) category
+     * to the list.
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array Main categories available for page
+     * @access protected
+     */
+       protected function getMemberCats(PDO $dbh)
+       {
+           try {
+
+                       $sql = "
+                SELECT *
+                  FROM category
+                 WHERE category_id = :cid";
+
+                       $stmt = $dbh->prepare($sql);
+            $categories = array();
+                       foreach ($this->memberCatsAssignedToPage as $id) {
+                               $stmt->bindParam(':cid', $id, PDO::PARAM_INT);
+                               $stmt->execute();
+                if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                    if ($row['parent_id'] == '0') {
+                                       $categories[$row['category_id']] = $row['name'];
+                    } else {
+                        $stmt->bindParam(':cid', $row['parent_id'], PDO::PARAM_INT);
+                        $stmt->execute();
+                        if ($parRow = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                            $categories[$parRow['category_id']] = $parRow['name'];
+                                               }
+                    }
+                }
+            }
+            asort($categories);
+
+                       return $categories;
+
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberSubCats()
+
+    /**
+     * Get all the sub categories available from the main categories that
+     * are available to the page.
+     *
+     * @param PDO     $dbh         Database handler
+     * @param array   $categories  Main level categories to get sub levels for
+     * @param integer $parentIdKey (optional) Main level that was searched on
+     *
+     * @return array     Sub categories available for page
+     * @access protected
+     */
+       protected function getMemberSubCats(
+               PDO $dbh,
+               array $categories,
+               $parentIdKey = null
+       ) {
+        if (empty($categories)) {
+            return array();
+        }
+
+               try {
+            //  Get the category information
+                       $sql = "
+                SELECT *
+                  FROM category
+                 WHERE category_id = :cid";
+
+                       $catStmt = $dbh->prepare($sql);
+
+            //  Get the sub-category information
+            $sql = "
+                SELECT c.*
+                  FROM category c, member_category mc, member m
+                 WHERE c.parent_id = :parent_id
+                                  AND c.category_id = mc.category_id
+                   AND mc.member_id = m.member_id
+                   AND m.active
+                 ";
+            $subCatStmt = $dbh->prepare($sql);
+            $subCategories = array();
+
+            while (list($id,) = each($categories)) {
+                $catStmt->bindParam(':cid', $id, PDO::PARAM_INT);
+                $catStmt->execute();
+                $category = $catStmt->fetch();
+                try {
+                    $subCatStmt->bindParam(
+                        ':parent_id',
+                        $category['category_id'],
+                        PDO::PARAM_INT
+                    );
+                    $subCatStmt->execute();
+                    if ($subCatData = $subCatStmt->fetchAll()) {
+                        foreach ($subCatData as $key => $val) {
+                            $catStmt->bindParam(
+                                ':cid',
+                                $val['category_id'],
+                                PDO::PARAM_INT
+                            );
+                            $catStmt->execute();
+                            $subCat = $catStmt->fetch();
+                            if (in_array($subCat['category_id'], $this->memberCatsAssignedToPage)) {
+                                //  Subcat assgined to page, only assign
+                                //  child of parent cat that is assigned
+                                //  to page.
+                                $subCategories[$subCat['parent_id']][$subCat['category_id']] = $subCat['name'];
+                            } elseif (in_array($subCat['parent_id'], $this->memberCatsAssignedToPage)) {
+                                //  Parent category assigned to page, add all
+                                //  children found
+                                $subCategories[$subCat['parent_id']][$subCat['category_id']] = $subCat['name'];
+                            }
+                        }
+                    }
+                } catch (PDOException $e) {
+                    return Toolkit_Common::handleError($e);
+                }
+            }
+
+            if (   is_numeric($parentIdKey)
+                && array_key_exists($parentIdKey, $subCategories)
+            ) {
+                           return $subCategories[$parentIdKey];
+            } else {
+                $subCategories
+                    = Toolkit_Common::arrayFlatten($subCategories, 2);
+                asort($subCategories);
+                           return $subCategories;
+            }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+        * @param array                               $flexyOpts   Flexy template engine options
+     * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway Page gateway
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(
+               array $flexyOpts,
+               Toolkit_Toolbox_PageGatewayAbstract $pageGateway
+       ) {
+               $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Members/css/member.css';
+        $tpl = new HTML_Template_Flexy($flexyOpts);
+        $tpl->compile($this->formTemplate);
+
+        $activity = $this->getActivities();
+        $parks    = $this->getParks();
+        $regions  = $this->memberRegionsAssignedToPage;
+        $counties = $this->getCounties();
+
+        $page             = new stdClass();
+        $page->formURL    = BASE_URL . 'index.php?catid=' . $this->_catid;
+        $page->activities
+            = (!empty($activity) && count($activity) > 1)
+            ? $activity
+            : null;
+        $page->parks
+            = (!empty($parks) && count($parks) > 1)
+            ? $parks
+            : null;
+        $page->regions
+            = (!empty($regions) && count($regions) > 1)
+            ? $regions
+            : null;
+        $page->counties
+            = (!empty($counties) && count($counties) > 1)
+            ? $counties
+            : null;
+
+        return $tpl->bufferedOutputObject($page);
+       }
+
+       //      }}}
+
+    protected function getActivities()
+    {
+        $activities = array();
+        try {
+            $cats
+                = ($this->memberCatsAssignedToPage)
+                ? " AND (category_id IN ("
+                    .implode(',', $this->memberCatsAssignedToPage).")
+                    OR parent_id IN (".implode(',', $this->memberCatsAssignedToPage)."))"
+                : '';
+            $sql = "
+            SELECT *
+              FROM category
+             WHERE parent_id = "
+                . self::PARENT_CATEGORY_ACTIVITIES
+                . $cats
+                . " AND category_id IN (
+                    SELECT category_id
+                      FROM member_category)"
+                . " ORDER BY name";
+            $stmt = $this->dbh->query($sql);
+            while ($category = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $activities[$category['category_id']] = $category['name'];
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $activities;
+    }
+
+    protected function getParks()
+    {
+        $parks = array();
+        try {
+            $cats
+                = ($this->memberCatsAssignedToPage)
+                ? " AND (category_id IN ("
+                    .implode(',', $this->memberCatsAssignedToPage).")
+                    OR parent_id IN (".implode(',', $this->memberCatsAssignedToPage)."))"
+                : '';
+            $sql = "
+            SELECT *
+              FROM category
+             WHERE parent_id = "
+                . self::PARENT_CATEGORY_PARKS
+                . $cats
+                . " AND category_id IN (
+                    SELECT category_id
+                      FROM member_category)"
+                . " ORDER BY name";
+            $stmt = $this->dbh->query($sql);
+            while ($category = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $parks[$category['category_id']] = $category['name'];
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $parks;
+    }
+
+       //      {{{     setCatId()
+
+    /**
+     * set the catid to use in the form
+     *
+     * @param integer $catid page catid
+     *
+     * @return PEAR    Error return a PEAR error if an invalid catid is passed in
+     * @access public
+     */
+       public function setCatId($catid)
+       {
+        if (ctype_digit((string)$catid)) {
+            $this->_catid = $catid;
+        } else {
+            return PEAR::raiseError('Invalid catid');
+        }
+       }
+
+       //      }}}
+       //      {{{     setPageMemberCategories()
+
+    /**
+     * Relate toolbox categories with main member categories
+     *
+        * @param Toolkit_Toolbox_GatewayAbstract $gateway Page gateway to get categories from
+        *
+     * @return array  toolbox -> category relations
+     * @access public
+     */
+       public function setPageMemberCategories(
+               Toolkit_Toolbox_GatewayAbstract $gateway
+       ) {
+               $page = $gateway->find($this->_catid);
+
+               $this->memberCatsAssignedToPage = $page['member_categories'];
+
+        // If there's no member category filter selected, use all with members
+        if (count($this->memberCatsAssignedToPage) == 0) {
+            $sql = "
+            SELECT DISTINCT c.category_id
+              FROM category c
+             WHERE (
+                   c.category_id IN (
+                    SELECT distinct c.category_id
+                      FROM category c, member_category mc, member m
+                     WHERE c.parent_id = 0
+                       AND c.category_id = mc.category_id
+                       AND mc.member_id = m.member_id
+                       AND m.active
+                    )
+                  )
+               OR (
+                  c.category_id IN (
+                    SELECT distinct sc.parent_id
+                      FROM category sc, member_category smc, member sm
+                     WHERE sc.parent_id > 0
+                       AND sc.parent_id != sc.category_id
+                       AND sc.category_id = smc.category_id
+                       AND smc.member_id = sm.member_id
+                       AND sm.active
+                    )
+                  )
+                    ;";
+                       $mcstmt = $this->dbh->prepare($sql);
+                       $mcstmt->execute();
+               while ($row = $mcstmt->fetch()) {
+                           $this->memberCatsAssignedToPage[] = $row['category_id'];
+                       }
+                       $page['member_categories'] = $this->memberCatsAssignedToPage;
+
+           // Otherwise add any subgategories for the selected cats with active members
+        } else {
+
+            $sql = "
+            SELECT DISTINCT c.category_id
+              FROM category c, member_category mc, member m
+             WHERE c.category_id = mc.category_id
+               AND m.member_id = mc.member_id
+               AND m.active";
+            if (is_array($this->memberCatsAssignedToPage)
+                && !empty($this->memberCatsAssignedToPage)) {
+                $mcats = implode(',', $this->memberCatsAssignedToPage);
+                $sql .= " AND c.parent_id IN ($mcats)";
+            }
+                       $mcstmt = $this->dbh->prepare($sql);
+                       $mcstmt->execute();
+               while ($row = $mcstmt->fetch()) {
+                           $this->memberCatsAssignedToPage[] = $row['category_id'];
+                       }
+                       $page['member_categories'] = $this->memberCatsAssignedToPage;
+        }
+
+               return $page['member_categories'];
+       }
+
+       //      }}}
+       //      {{{     setPageMemberRegions()
+
+    /**
+     * Relate toolbox member cities
+     *
+        * @param Toolkit_Toolbox_GatewayAbstract $gateway Page gateway to get categories from
+        *
+     * @return array  toolbox -> category relations
+     * @access public
+     */
+       public function setPageMemberRegions(
+               Toolkit_Toolbox_GatewayAbstract $gateway
+       ) {
+           $page = $gateway->find($this->_catid);
+               $memberRegionsAssignedToPage = array() + $page['member_regions'];
+               // If no regions specified then use all regions
+        if (count($this->memberRegionsAssignedToPage) == 0) {
+            $sql .= "
+            SELECT DISTINCT region
+              FROM member
+             WHERE active
+               AND region is not null;";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch()) {
+                $memberRegionsAssignedToPage[] = $row['region'];
+            }
+        }
+        $sql = "
+        SELECT region_name
+          FROM region
+         WHERE region_id = :id";
+        $getRegionName = $this->dbh->prepare($sql);
+        foreach ($memberRegionsAssignedToPage as $region) {
+            $getRegionName->bindParam(':id', $region, PDO::PARAM_INT);
+            $getRegionName->execute();
+            $this->memberRegionsAssignedToPage[$region]
+                = $getRegionName->fetchColumn();
+        }
+       }
+
+       //      }}}
+
+    public function getCounties()
+    {
+        $counties = array();
+        $sql .= "
+        SELECT *
+          FROM county
+         WHERE county_id IN (
+            SELECT DISTINCT county
+              FROM member
+             WHERE active
+               AND county is not null)";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch()) {
+                $counties[$row['county_id']] = $row['county_name'];
+            }
+        return $counties;
+    }
+}
diff --git a/Toolkit/Members/UserSearchForm.php.save b/Toolkit/Members/UserSearchForm.php.save
new file mode 100644 (file)
index 0000000..b363890
--- /dev/null
@@ -0,0 +1,936 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Member Search Form Class
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: UserSearchForm.php,v 1.27 2010/07/14 23:31:14 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+
+/**
+ * Member Search Form
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_Members_UserSearchForm
+    extends Toolkit_FormBuilder
+{
+       //      {{{     properties
+
+
+    /**
+     * Description for protected
+     * @var    array
+     * @access protected
+     */
+       protected $memberCatsAssignedToPage = array();
+
+    /**
+     * Description for $memberRegiansAssignedToPage
+     * @var array
+     * @access protected
+     */
+       protected $memberRegionsAssignedToPage = array();
+
+       /**
+        * The Table name used to store the data of the member record in the database.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableName = 'member';
+
+       /**
+        * Array of data that holds the meta data info on the table
+        *
+        * Contains information on the type of fields in the database.
+        * That way when we run our automated SQL queries with our PDO
+        * we can properly bind data to our SQL queries.  This will
+        * allow for one more layer of protection against any sql
+        * injection attempts.
+        *
+        * @var string
+        * @access public
+        */
+       public $tableMetaData;
+
+       /**
+        * Flexy options used in the renderer
+        *
+        * @var array
+        * @access protected
+        */
+       protected $flexyOptions;
+
+       /**
+        * The name of the template used to render the member info form
+        *
+        * @var string
+        * @access protected
+        */
+       protected $formTemplate = 'memberSearchForm.tpl';
+
+       /**
+        * Form access from inside the template
+        *
+        * @var object
+        * @access protected
+        */
+       protected $view;
+
+       /**
+        * registered rules for the form
+        *
+        * @var array
+        * @access protected
+        */
+       protected $registeredRules = array();
+
+    /**
+     * catid to use in the form
+     *
+     * @var    integer
+     * @access private
+     */
+    private $_catid;
+
+       //      }}}
+
+       //      {{{ configureConstants()
+
+       /**
+        * Sets the constants for the form
+        *
+        * The member category select list must always default
+        * to the -- Choose Category -- option
+        *
+        * @return void
+        * @access public
+        */
+       public function configureConstants()
+       {
+               $c = array(
+                       'catid' => $this->_catid,
+                       'search' => 1,
+               );
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{ configureDefaults()
+
+       /**
+        * Sets the defaults for the an existing member
+        *
+        * Populates data for the main member form.  Also grabs
+        * data to populate the modules on the form if needed.
+        *
+        * @return array $defaults Returns the array of defaults
+        *                                                 so children who call this function
+        *                                                 can obtain a copy of these values.
+        * @access public
+        */
+       public function configureDefaults()
+       {
+               $d = array();
+
+               $this->setupDefaults($d);
+
+               return $d;
+       }
+
+       //      }}}
+       //      {{{ configureElements()
+
+       /**
+        * Setup the elements to use on the form.
+        *
+     * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+     *
+        * @return void
+        * @access public
+        */
+       public function configureElements(PDO $dbh, Config_Container $c)
+       {
+        $e = array();
+
+        //  get reference to [listing type] section of config file
+        $singularType = $c->getItem('section', 'listing type')
+                       ->getItem('directive', 'singular')
+                       ->getContent();
+        $pluralType = $c->getItem('section', 'listing type')
+                       ->getItem('directive', 'plural')
+                       ->getContent();
+        $hasRegions = $c->getItem('section', 'conf')
+                       ->getItem('directive', 'regions')
+                       ->getContent();
+
+               $memberCategories    = $this->getMemberCats($dbh);
+               if (!isset($_GET['category_id'])) {
+                       $_GET['category_id'] = null;
+               }
+        $memberSubCategories
+            = $this->getMemberSubCats(
+                               $dbh,
+                               $memberCategories,
+                               $_GET['category_id']
+                       );
+               $memberAmenities = $this->getMemberAmenities($dbh);
+
+        $regions = ($hasRegions) ? $this->getAvailableRegions($dbh) : array();
+        $this->createAvailableMemberTypesFromRegions($dbh, $regions);
+
+               //      All Grouped Elements are created here.
+               foreach ($memberAmenities as $k => $v) {
+                       $amenities[] = array(
+                'type' => 'checkbox',
+                'req' => false,
+                'name' => $v,
+                'display' => $k
+            );
+               }
+
+               //      All Elements are created here.  This includes group element definitions.
+               $e[] = array(
+            'type' => 'header',
+            'req' => false,
+            'name' => 'SearchForm_hdr'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'catid'
+        );
+               $e[] = array(
+            'type' => 'hidden',
+            'req' => false,
+            'name' => 'search'
+        );
+               $e[] = array(
+            'type' => 'text',
+            'req' => false,
+            'name' => 'member_name',
+            'display' => "Name",
+            'opts' => array('class' => 'text')
+        );
+        if (isset($regions) && !empty($regions) && count($regions) > 1) {
+            $e[] = array(
+                'type' => 'select',
+                'req' => false,
+                'name' => 'region_id',
+                'display' => 'Region',
+                'opts' => array('' => '-- Select --') + $regions,
+            );
+        } else if (isset($regions) && count($regions) == 1) {
+//            $e[] = array(
+//                'type' => 'hidden',
+//                'req' => false,
+//                'name' => 'region_id',
+//                'display' => implode('', array_keys($regions))
+//            );
+        }
+        if (    isset($memberCategories)
+            && is_array($memberCategories)
+            && !empty($memberCategories)
+        ) {
+            $e[] = array(
+                'type' => 'select',
+                'req' => false,
+                'name' => 'category_id',
+                'display' => "Category",
+                'opts' => array('' => '-- Select --') + $memberCategories
+            );
+        }
+        if (    isset($memberSubCategories)
+            && is_array($memberSubCategories)
+            && !empty($memberSubCategories)
+        ) {
+            $e[] = array(
+                'type' => 'select',
+                'req' => false,
+                'name' => 'sub_category_id',
+                'display' => "Subcategory",
+                'opts' => array('' => '-- Select --') + $memberSubCategories
+            );
+        }
+               //      Only show do if we have amenities to show.
+               if (!empty($memberAmenities)) {
+                       $e[] = array(
+                'type' => 'group',
+                'req' => false,
+                'name' => 'amenities',
+                'group' => $amenities,
+                'seperator' => '',
+                'appendName' => true
+            );
+                       $e[] = array(
+                'type' => 'checkbox',
+                'req' => false,
+                'name' => 'search_all_amenity',
+                'opts' => 'Only show members who offer all selected amenities'
+            );
+               }
+
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{ configureFilters()
+
+       /**
+        * Setup the filters to apply to the elements before we are
+        * handed the values submitted
+        *
+     * @return void
+        * @access public
+        */
+       public function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+               $this->setupFilters($f);
+       }
+
+       //      }}}
+       //      {{{ configureForm()
+
+       /**
+        * Helper method to configure the entire form
+        *
+     * @param PDO              $dbh Database handler
+     * @param Config_Container $c   Configuration object
+     *
+     * @return void
+        * @access public
+        */
+       public function configureForm(PDO $dbh, Config_Container $c)
+       {
+               $this->configureElements($dbh, $c);
+               $this->configureRules();
+               $this->configureFilters();
+               $this->configureDefaults();
+               $this->configureConstants();
+       }
+
+       //      }}}
+       //      {{{ configureRules()
+
+       /**
+        * Sets up all the rules to be used when the form is validated.
+        *
+     * @return void
+        * @access public
+        */
+       public function configureRules()
+       {
+               //      No Rules
+               $r = array();
+               $this->setupRules($r);
+       }
+
+       //      }}}
+    //  {{{ createAvailableMemberTypesFromRegions()
+
+    /**
+     * Get available categories from members assigned to regions
+     *
+     * @param PDO   $dbh     Database handler
+     * @param array $regions Available regions to get members from
+     *
+     * @return void
+     * @access protected
+     */
+    protected function createAvailableMemberTypesFromRegions(
+               PDO $dbh,
+               array $regions
+       ) {
+        try {
+            $regionCats   = array();
+            $availRegions = array();
+            $availCats    = array();
+            $mainCats     = array();
+            if (!empty($this->memberCatsAssignedToPage)) {
+                foreach ($this->memberCatsAssignedToPage as $i) {
+                    $cats = Toolkit_Common::getHierarchicalTreeStructure(
+                        $dbh,
+                        'category',
+                        'category_id',
+                        'parent_id',
+                        'pos',
+                        $i,
+                        0,
+                        false
+                    );
+                    if (is_array($cats) && !empty($cats)) {
+                        $availCats = array_merge($availCats, array_keys($cats));
+                    }
+                }
+            }
+            if ($availCats && !empty($availCats)) {
+                $availCats = implode(', ', $availCats);
+            }
+
+            if (!empty($this->memberRegionsAssignedToPage)) {
+                $availRegions = implode(', ', $availRegions);
+            }
+            $pNameSql = "
+            SELECT name
+              FROM category
+             WHERE parent_id = :cid";
+            $getParentName = $dbh->prepare($pNameSql);
+            $sql = "SELECT distinct c.category_id, c.parent_id,
+                                          ( SELECT name FROM category WHERE category_id = c.parent_id) AS parent,
+                                          c.name AS category
+                                         FROM category c
+                     WHERE c.category_id IN (
+                            SELECT distinct c.category_id
+                              FROM category c, member_category mc, member m
+                             WHERE
+                              c.category_id = mc.category_id
+                               AND mc.member_id = m.member_id
+                               AND m.active";
+            if ($regions) {
+                $sql .= " AND (region = :rid OR region IS NULL) ";
+            }
+
+            $sql .= ")
+                       AND c.parent_id > 0 ";
+            if ($availRegions) {
+                $sql .= " AND region in ($availRegions) ";
+            }
+            if ($availCats) {
+                $sql .= " AND c.category_id in ($availCats) ";
+            }
+            $sql .=  " ORDER BY c.name";
+            $stmt = $dbh->prepare($sql);
+            if ($regions) {
+                foreach ($regions as $i => $j) {
+                    if (is_numeric($i)) {
+                        $stmt->bindParam(':rid', $i, PDO::PARAM_INT);
+                        $stmt->execute();
+                        $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
+                        foreach ($row as $x) {
+                            $regionCats[$i][$x['parent_id']][$x['category_id']] = $x['category'];
+                            $mainCats[$x['parent_id']] = $x['parent'];
+                        }
+                    }
+                }
+            } else {
+                $stmt->execute();
+                $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
+                foreach ($row as $x) {
+                    $regionCats[$i][$x['parent_id']][$x['category_id']] = $x['category'];
+                    $mainCats[$x['parent_id']] = $x['parent'];
+                }
+            }
+
+                       asort($mainCats);
+            $this->regionCategories = $regionCats;
+            $this->mainCats = $mainCats;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    //  }}}
+
+       //      {{{     getAvailableRegions()
+
+    /**
+     * Returns all available regions that derive from members assigned to
+     * this page
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array regions available to this page
+     * @access protected
+     */
+       protected function getAvailableRegions(PDO $dbh)
+       {
+        // Make sure we have all sub-cats nos also
+
+
+        try {
+            $sql = "SELECT DISTINCT c.category_id
+                      FROM category c, member_category mc, member m
+                     WHERE c.category_id = mc.category_id
+                       AND m.member_id = mc.member_id
+                       AND m.active ";
+            if (is_array($this->memberCatsAssignedToPage)
+                && !empty($this->memberCatsAssignedToPage)) {
+                $mcats = implode(',', $this->memberCatsAssignedToPage);
+                $sql  .= " AND c.parent_id IN ($mcats)";
+            }
+            $mcstmt = $this->dbh->prepare($sql);
+            $mcstmt->execute();
+        } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+        while ($row = $mcstmt->fetch()) {
+                   $this->memberCatsAssignedToPage[] = $row['category_id'];
+               }
+
+           $regions = array();
+        $memCats = array();
+               try {
+
+                   $sql = "
+                SELECT *
+                  FROM region
+                 WHERE region_id in (
+                        SELECT distinct(region)
+                          FROM member
+                          WHERE active = 't'
+                          AND region is not null";
+            if (!empty($this->memberCatsAssignedToPage)) {
+                $sql .= " AND member_id in (SELECT distinct(member_id)
+                    FROM member_category
+                    WHERE category_id in (".implode(',', $this->memberCatsAssignedToPage).")
+                )";
+            }
+
+            if (!empty($this->memberRegionsAssignedToPage)) {
+                $sql .= " AND region_id in (".implode(',', $this->memberRegionsAssignedToPage).") ";
+            }
+
+            $sql .= " )
+                 ORDER BY region_name";
+
+            $stmt = $dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch()) {
+                $regions[$row['region_id']] = $row['region_name'];
+            }
+
+            asort($regions);
+
+                       return $regions;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberAmenities()
+
+    /**
+     * Get all the amenities for the member
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array member amenities
+     * @access protected
+     */
+       protected function getMemberAmenities(PDO $dbh)
+       {
+               try {
+                       $amenities = array();
+            $sql = "
+            SELECT accommodations
+              FROM category
+             WHERE category_id = :cid";
+            $isAccommodationCategory = $dbh->prepare($sql);
+                       $sql = "
+            SELECT a.*
+              FROM amenity a
+           NATURAL JOIN member_amenity ma
+           NATURAL JOIN member_category mc
+           NATURAL JOIN member m
+             WHERE m.new_member <> CAST(1 AS BOOLEAN)
+               AND m.active = CAST(1 AS BOOLEAN)
+               AND a.display_form = CAST(1 AS BOOLEAN)
+               AND (mc.category_id = :cid
+                OR mc.category_id in (
+                    SELECT category_id
+                      FROM category
+                     WHERE parent_id      = :cid))
+             ORDER BY amenity_name";
+
+                       $stmt = $dbh->prepare($sql);
+                       foreach ($this->memberCatsAssignedToPage as $id) {
+                $isAccommodationCategory->bindParam(':cid', $id, PDO::PARAM_INT);
+                $isAccommodationCategory->execute();
+                if (!$isAccommodationCategory->fetchColumn()) {
+                    continue;
+                }
+                               $stmt->bindParam(':cid', $id, PDO::PARAM_INT);
+                               $stmt->execute();
+                               while ($row = $stmt->fetch()) {
+                                       $amenities[$row['amenity_name']] = $row['amenity_id'];
+                               }
+                       }
+                       return $amenities;
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberCats()
+
+    /**
+     * Get all the main categories available from the categories that
+     * are assigned to the page.
+     *
+     * If a main category is assigned to a page, then add to list.
+     *
+     * If a sub category is assgined to page, then add parent (main) category
+     * to the list.
+     *
+        * @param PDO $dbh Database handler
+        *
+     * @return array Main categories available for page
+     * @access protected
+     */
+       protected function getMemberCats(PDO $dbh)
+       {
+           try {
+
+                       $sql = "
+                SELECT *
+                  FROM category
+                 WHERE category_id = :cid";
+
+                       $stmt = $dbh->prepare($sql);
+            $categories = array();
+                       foreach ($this->memberCatsAssignedToPage as $id) {
+                               $stmt->bindParam(':cid', $id, PDO::PARAM_INT);
+                               $stmt->execute();
+                if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                    if ($row['parent_id'] == '0') {
+                                       $categories[$row['category_id']] = $row['name'];
+                    } else {
+                        $stmt->bindParam(':cid', $row['parent_id'], PDO::PARAM_INT);
+                        $stmt->execute();
+                        if ($parRow = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                            $categories[$parRow['category_id']] = $parRow['name'];
+                                               }
+                    }
+                }
+            }
+            asort($categories);
+
+                       return $categories;
+
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberSubCats()
+
+    /**
+     * Get all the sub categories available from the main categories that
+     * are available to the page.
+     *
+     * @param PDO     $dbh         Database handler
+     * @param array   $categories  Main level categories to get sub levels for
+     * @param integer $parentIdKey (optional) Main level that was searched on
+     *
+     * @return array     Sub categories available for page
+     * @access protected
+     */
+       protected function getMemberSubCats(
+               PDO $dbh,
+               array $categories,
+               $parentIdKey = null
+       ) {
+        if (empty($categories)) {
+            return array();
+        }
+
+               try {
+            //  Get the category information
+                       $sql = "
+                SELECT *
+                  FROM category
+                 WHERE category_id = :cid";
+
+                       $catStmt = $dbh->prepare($sql);
+
+            //  Get the sub-category information
+            $sql = "
+                SELECT c.*
+                  FROM category c, member_category mc, member m
+                 WHERE c.parent_id = :parent_id
+                                  AND c.category_id = mc.category_id
+                   AND mc.member_id = m.member_id
+                   AND m.active
+                 ";
+            $subCatStmt = $dbh->prepare($sql);
+            $subCategories = array();
+
+            while (list($id,) = each($categories)) {
+                $catStmt->bindParam(':cid', $id, PDO::PARAM_INT);
+                $catStmt->execute();
+                $category = $catStmt->fetch();
+                try {
+                    $subCatStmt->bindParam(
+                        ':parent_id',
+                        $category['category_id'],
+                        PDO::PARAM_INT
+                    );
+                    $subCatStmt->execute();
+                    if ($subCatData = $subCatStmt->fetchAll()) {
+                        foreach ($subCatData as $key => $val) {
+                            $catStmt->bindParam(
+                                ':cid',
+                                $val['category_id'],
+                                PDO::PARAM_INT
+                            );
+                            $catStmt->execute();
+                            $subCat = $catStmt->fetch();
+                            if (in_array($subCat['category_id'], $this->memberCatsAssignedToPage)) {
+                                //  Subcat assgined to page, only assign
+                                //  child of parent cat that is assigned
+                                //  to page.
+                                $subCategories[$subCat['parent_id']][$subCat['category_id']] = $subCat['name'];
+                            } elseif (in_array($subCat['parent_id'], $this->memberCatsAssignedToPage)) {
+                                //  Parent category assigned to page, add all
+                                //  children found
+                                $subCategories[$subCat['parent_id']][$subCat['category_id']] = $subCat['name'];
+                            }
+                        }
+                    }
+                } catch (PDOException $e) {
+                    return Toolkit_Common::handleError($e);
+                }
+            }
+
+            if (   is_numeric($parentIdKey)
+                && array_key_exists($parentIdKey, $subCategories)
+            ) {
+                           return $subCategories[$parentIdKey];
+            } else {
+                $subCategories
+                    = Toolkit_Common::arrayFlatten($subCategories, 2);
+                asort($subCategories);
+                           return $subCategories;
+            }
+               } catch (PDOException $e) {
+                       return Toolkit_Common::handleError($e);
+               }
+       }
+
+       //      }}}
+
+       //      {{{ toHtml()
+
+       /**
+        * Renders the form
+        *
+        * sets the page the form should be redirected to instead of coming back
+        * around to itself.
+        *
+        * @param array                               $flexyOpts   Flexy template engine options
+     * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway Page gateway
+        *
+        * @return string The rendered form
+        * @access public
+        */
+       public function toHtml(
+               array $flexyOpts,
+               Toolkit_Toolbox_PageGatewayAbstract $pageGateway
+       ) {
+               $GLOBALS['bottomScripts'][]
+                       = BASE_URL . 'Toolkit/Members/libjs/business-search.js';
+
+               $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Members/css/member.css';
+
+               //      We need to validate (and freeze if needed)
+               //      before we render the form. That way the
+               //      template knows about any errors on the form.
+               $this->validated = $this->validate();
+
+               $page = $pageGateway->find($this->_catid);
+
+               //      ProcessData handles settingup the lat/lon coordinates if they were not entered
+               //      into the form.  these values ar calculated and then inserted into the forms
+               //      element values.  So we need to process the data first and then render the form.
+               $this->setupRenderers($flexyOpts);
+
+               return $this->template->bufferedOutputObject($this->view);
+       }
+
+       //      }}}
+
+       //      {{{     setCatId()
+
+    /**
+     * set the catid to use in the form
+     *
+     * @param integer $catid page catid
+     *
+     * @return PEAR    Error return a PEAR error if an invalid catid is passed in
+     * @access public
+     */
+       public function setCatId($catid)
+       {
+        if (ctype_digit((string)$catid)) {
+            $this->_catid = $catid;
+        } else {
+            return PEAR::raiseError('Invalid catid');
+        }
+       }
+
+       //      }}}
+       //      {{{     setPageMemberCategories()
+
+    /**
+     * Relate toolbox categories with main member categories
+     *
+        * @param Toolkit_Toolbox_GatewayAbstract $gateway Page gateway to get categories from
+        *
+     * @return array  toolbox -> category relations
+     * @access public
+     */
+       public function setPageMemberCategories(
+               Toolkit_Toolbox_GatewayAbstract $gateway
+       ) {
+               $page                           = $gateway->find($this->_catid);
+
+               $this->memberCatsAssignedToPage = $page['member_categories'];
+
+        // If there's no member category filter selected, use all with members
+        if (count($this->memberCatsAssignedToPage) == 0) {
+            $sql = "SELECT DISTINCT c.category_id
+                      FROM category c
+                     WHERE (
+                            c.category_id IN (
+                                            SELECT distinct c.category_id
+                                              FROM category c, member_category mc, member m
+                                             WHERE c.parent_id = 0
+                                               AND c.category_id = mc.category_id
+                                               AND mc.member_id = m.member_id
+                                               AND m.active
+                                            )
+                            )
+                        OR (
+                            c.category_id IN (
+                                            SELECT distinct sc.parent_id
+                                              FROM category sc, member_category smc, member sm
+                                             WHERE sc.parent_id > 0
+                                               AND sc.parent_id != sc.category_id
+                                               AND sc.category_id = smc.category_id
+                                               AND smc.member_id = sm.member_id
+                                               AND sm.active
+                                            )
+                            )
+                    ;";
+                       $mcstmt = $this->dbh->prepare($sql);
+                       $mcstmt->execute();
+               while ($row = $mcstmt->fetch()) {
+                           $this->memberCatsAssignedToPage[] = $row['category_id'];
+                       }
+                       $page['member_categories'] = $this->memberCatsAssignedToPage;
+
+           // Otherwise add any subgategories for the selected cats with active members
+        } else {
+
+            $sql = "SELECT DISTINCT c.category_id
+                      FROM category c, member_category mc, member m
+                     WHERE c.category_id = mc.category_id
+                       AND m.member_id = mc.member_id
+                       AND m.active";
+            if (is_array($this->memberCatsAssignedToPage)
+                && !empty($this->memberCatsAssignedToPage)) {
+                $mcats = implode(',', $this->memberCatsAssignedToPage);
+                $sql .= " AND c.parent_id IN ($mcats)";
+            }
+                       $mcstmt = $this->dbh->prepare($sql);
+                       $mcstmt->execute();
+               while ($row = $mcstmt->fetch()) {
+                           $this->memberCatsAssignedToPage[] = $row['category_id'];
+                       }
+                       $page['member_categories'] = $this->memberCatsAssignedToPage;
+        }
+
+               return $page['member_categories'];
+       }
+
+       //      }}}
+       //      {{{     setPageMemberRegions()
+
+    /**
+     * Relate toolbox member cities
+     *
+        * @param Toolkit_Toolbox_GatewayAbstract $gateway Page gateway to get categories from
+        *
+     * @return array  toolbox -> category relations
+     * @access public
+     */
+       public function setPageMemberRegions(
+               Toolkit_Toolbox_GatewayAbstract $gateway
+       ) {
+           $page                           = $gateway->find($this->_catid);
+               $this->memberRegionsAssignedToPage = $page['member_regions'];
+
+               // If no regions specified then use all regions
+        if (count($this->memberRegionsAssignedToPage) == 0) {
+            $sql .= "
+                       SELECT DISTINCT region
+                         FROM member
+                        WHERE active
+                          AND region is not null;";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch()) {
+                $this->memberRegionsAssignedToPage[] = $row['region'];
+            }
+            $page['member_regions'] = $this->memberRegionsAssignedToPage;
+        }
+
+               return $page['member_regions'];
+       }
+
+       //      }}}
+       //      {{{ setupRenderers()
+
+    /**
+     * Sets up the Flexy template
+     *
+        * @param array $flexyOpts Flexy template engine options
+        *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers(array $flexyOpts)
+       {
+               $renderer = new HTML_QuickForm_Renderer_Object(true);
+
+               $this->accept($renderer);
+
+               $this->template = new HTML_Template_Flexy($flexyOpts);
+
+               //      Make the view a copy of the $this object
+               //      That way we have access to call functions in
+               //      this class from within the template.
+               $this->view = $this;
+               $this->view->form = $renderer->toObject();
+               $this->template->compile($this->formTemplate);
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/Members/addressHelp.html b/Toolkit/Members/addressHelp.html
new file mode 100644 (file)
index 0000000..69de4d5
--- /dev/null
@@ -0,0 +1,10 @@
+<h2>My business is not in the correct spot in Google Maps.<br>What can I do?</h2>
+
+<p>Google provides the tools needed for placing your business correctly on their maps.
+Visit this page: <a target="_blank" href="http://www.google.com/lbc">http://www.google.com/lbc</a></p>
+<p>In addition to your correct location in their maps, you can also add other information pertaining 
+to your business such as opening hours, services, contact information etc.</p>
+
+<h2>What is the Latitude/Longitude fields on this page.</h2>
+<p>You can use this option to set your lat/long information for the Google Maps on this site only.</p>
+<p>Once your location is displaying right from the Google Local Business Center, you can remove numbers in these fields.</p>
diff --git a/Toolkit/Members/assets/.keepme b/Toolkit/Members/assets/.keepme
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/Toolkit/Members/assets/btn_close.gif b/Toolkit/Members/assets/btn_close.gif
new file mode 100755 (executable)
index 0000000..a7e3193
Binary files /dev/null and b/Toolkit/Members/assets/btn_close.gif differ
diff --git a/Toolkit/Members/assets/btn_planneractions.gif b/Toolkit/Members/assets/btn_planneractions.gif
new file mode 100755 (executable)
index 0000000..a1125b4
Binary files /dev/null and b/Toolkit/Members/assets/btn_planneractions.gif differ
diff --git a/Toolkit/Members/assets/btn_submit.gif b/Toolkit/Members/assets/btn_submit.gif
new file mode 100755 (executable)
index 0000000..13eb0c1
Binary files /dev/null and b/Toolkit/Members/assets/btn_submit.gif differ
diff --git a/Toolkit/Members/assets/saveplanner.gif b/Toolkit/Members/assets/saveplanner.gif
new file mode 100755 (executable)
index 0000000..e950408
Binary files /dev/null and b/Toolkit/Members/assets/saveplanner.gif differ
diff --git a/Toolkit/Members/config.ini b/Toolkit/Members/config.ini
new file mode 100644 (file)
index 0000000..0559739
--- /dev/null
@@ -0,0 +1,106 @@
+; Member Database configuration file
+[conf]
+salt = 8qq5i6k519WHqh
+; Turn on/off amenities for the application
+amenities = On
+; Allow regions in the application.
+regions = On
+; Only allow cities in member records that are added by an admin user.
+; Turning on will provide admin with an extra form that will allow them
+; to add/edit/remove cities.
+; Turning off will allow any city name to be entered when editing member
+; records.
+controlledCities = On
+counties = On
+newMemberRequests = Off
+; Determines if member changes must be first approved by admin
+; before they will be written to their actual record.
+strictPending = Off
+; Allow duplicate member names in the database
+duplicateMembers = Off
+; Show the mailing address in the members profile page
+showMailingAddress = Off
+; Date start years
+dateStartYear = 2005
+; Default state for member listings
+defaultState = 23
+; uses Gaslight Medias online travel reservation system
+glmReservations = Off
+; to use map numbers for search results
+searchResultNumbered = On
+; turn on to have the member icon click to go up to the member location on map
+searchMapIconActive = Off
+
+[add your business]
+approvalNeeded = Off
+
+; uses auth.net for processing
+[authorize net]
+useAuthNet = Off
+authNetLoginId = ""
+authNetTranKey = ""
+
+[photos]
+; Maximum number of photos a member is allowed to upload per record
+maxPhotos = 100
+; Maximum length allowed in text fields for photo captions
+maxCaptionLength = 60
+; This is the template when editing / adding photos to a members gallery
+; Not to be confused w/ the templates for the add / edit photo forms.
+editGalleryTemplate = "editPhotoGallery.tpl"
+
+; How the app should be displayed (Business, Members, Users, etc...)
+; [List Businesses] [Add Business Listing] [Pending Business Listing Update]
+; [List Members] [Add Member Listing] [Pending Member Listing Update]
+[listing type]
+singular = "Trail"
+plural = "Trails"
+
+; How the regions should be displayed (Regions, Counties, Areas, etc...)
+; [Regions] [List Regions] [Add Regions]
+; [Counties] [List Counties] [Add Counties]
+[region type]
+singular = "Region"
+plural = "Regions"
+
+[county type]
+singular = "County"
+plural = "Counties"
+
+[tables]
+pendingTable = "member_updates"
+photosTable = "member_photos"
+
+; Settings when logged into the members only area
+[members only]
+; Show the coupons subnav link
+coupons = Off
+; Show the events subnav link
+events = Off
+; show the amenities tab in the record navigation tabs
+amenities = Off
+; show the packages tab in the record navigation tabs
+packages = Off
+; show the photos tab in the record navigation tabs
+photos = Off
+; show the files tab in the record navigation tabs
+files = Off
+; show the contacts tab in the record navigation tabs
+contacts = Off
+
+; Settings for the admin > members area
+[admin]
+; show the amenities tab in the record navigation tabs
+amenities = On
+; show the packages tab in the record navigation tabs
+packages = Off
+; show the photos tab in the record navigation tabs
+photos = On
+; show the files tab in the record navigation tabs
+files = On
+; show the contacts tab in the record navigation tabs
+contacts = Off
+; show billing module
+billing = Off
+; the rest of the billing module config setting are in
+; Toolkit/Members/Billing/config.ini
\ No newline at end of file
diff --git a/Toolkit/Members/css/member-admin.css b/Toolkit/Members/css/member-admin.css
new file mode 100755 (executable)
index 0000000..47f65d8
--- /dev/null
@@ -0,0 +1,966 @@
+body#memberdb {
+  margin: 0;
+  padding: 0;
+  text-align: center;
+  font-family: arial, sans-serif;
+  font-size: 12px;
+       background-color: #ddd;
+       }
+a {outline: 0}
+
+#memberdb #cal {
+       display: inline;
+       margin-left: 5px;
+}
+#memberdb #wrapper {
+       width: 760px;
+       margin: 0 auto;
+       background:#fff url("../../../images/shadowr.gif") top right repeat-y;
+       text-align: left;
+       margin-top: 15px;
+       height: 1%;
+       overflow: hidden;
+       padding-bottom: 20px;
+       }
+#memberdb #bottom {
+  width: 760px;
+  margin: 0 auto;
+       background:#fff url("../../../images/shadowb.gif") top right no-repeat;
+       height:7px;
+       font-size: 1px;
+       }
+#memberdb #copyright {
+       width: 760px;
+       font-size: 0.9em;
+       margin: 10px auto;
+       }
+
+#memberdb #top {
+       background: url("../../../images/top2.jpg") no-repeat;
+       height: 150px;
+       margin-right: 6px;
+       position: relative;
+       }
+#memberdb #top h1 {
+       position: absolute;
+       top: 10px;
+       left: 20px;
+       color: #000;
+       color: #CC6C06;
+       font-size: 26px;
+       margin: 0;
+       display: none;}
+#memberdb #top img {
+       position: absolute;
+       top: 30px;
+       left: 20px;
+       border: 0px solid #244b8d;
+       background: white;
+       padding: 5px 5px;
+       }
+h2 {font-size: 20px;}
+/*
+fieldset {float: left; width:600px;}
+fieldset form {width:600px;}
+.fieldset-form {margin:0;padding:0;float:left;width:600px;}
+input {font-size: 1.1em;}
+*/
+/* Navigation */
+#navcontainer {
+       margin-right: 6px;
+       height: 1%;
+       overflow: hidden;
+       }
+#navcontainer ul {
+  padding: 0;
+  margin: 0;
+  background-color: #004C64;
+  color: White;
+  float: left;
+  width: 100%;
+}
+#navcontainer ul li { display: inline; }
+#navcontainer ul li a {
+  padding: 0.6em 1.5em;
+  background-color: #004C64;
+  color: White;
+  text-decoration: none;
+  float: left;
+  border-right: 1px solid #fff;
+       font-weight: bold;
+       border-bottom: 1px solid #fff;
+       }
+#navcontainer ul li a:hover {
+  background-color: #2C788F;
+  color: #fff;
+
+}
+#navcontainer ul li a.active  {background-color: #2C788F; color: white;}
+
+/*sub*/
+#navcontainer div + div ul {
+       background-color: #2C788F;
+}
+#navcontainer div + div ul li a {
+       padding: 0.5em 1em;
+       background-color: #2C788F;
+       border-right: 1px solid #ccc;
+       font-weight: normal;
+       border-bottom: none;
+}
+#navcontainer div + div ul li a:hover {
+       color: #000;
+}
+#navcontainer div + div ul li a.active  {
+       background-color: #fff;
+       color: black;
+       font-weight: bold;
+}
+#navcontainer div + div ul li a.hasPending {
+       background: url("../../../images/flag_green.png") center right no-repeat;
+       padding-right: 21px;
+}
+#navcontainer div + div ul li a.active.hasPending {
+       background: white url("../../../images/flag_green.png") center right no-repeat;
+}
+/*
+#subnavcontainer {margin-right: 6px;}
+#subnavcontainer ul {
+  padding: 0;
+  margin: 0;
+  background-color: #2C788F;
+  color: white;
+  float: left;
+  width: 100%;
+}
+#subnavcontainer ul li { display: inline; }
+#subnavcontainer ul li a {
+  padding: 0.5em 1em;
+  background-color: #2C788F;
+  color: white;
+  text-decoration: none;
+  float: left;
+  border-right: 1px solid #ccc;
+       font-weight: normal;
+       }
+#subnavcontainer ul li a:hover {
+  background-color: #2C788F;
+  color: #000;
+}
+#subnavcontainer ul li a.active  {background-color: #fff; color: black; font-weight: bold;}
+*/
+ /* Content area */
+#content {
+       margin: 20px 10px;
+       clear: left;
+       }
+/* BUTTONS what the hell? */
+
+.buttons a, .buttons button {
+    display:block;
+    float:left;
+    margin:0 7px 0 0;
+    background-color:#f5f5f5;
+    border:1px solid #dedede;
+    border-top:1px solid #eee;
+    border-left:1px solid #eee;
+
+    font-family:"Lucida Grande", Tahoma, Arial, Verdana, sans-serif;
+    font-size:100%;
+    line-height:130%;
+    text-decoration:none;
+    font-weight:bold;
+    color:#565656;
+    cursor:pointer;
+    padding:5px 10px 6px 7px; /* Links */
+}
+.buttons button{
+    width:auto;
+    overflow:visible;
+    padding:4px 10px 3px 7px; /* IE6 */
+}
+.buttons button[type]{
+    padding:5px 10px 5px 7px; /* Firefox */
+    line-height:17px; /* Safari */
+}
+.buttons button img, .buttons a img{
+    margin:0 3px -3px 0 !important;
+    padding:0;
+    border:none;
+    width:16px;
+    height:16px;
+}
+/* STANDARD */
+
+.buttons button:hover, .buttons a:hover{
+    background-color:#dff4ff;
+    border:1px solid #c2e1ef;
+    color:#336699;
+}
+.buttons a:active{
+    background-color:#6299c5;
+    border:1px solid #6299c5;
+    color:#fff;
+}
+
+/* POSITIVE */
+
+button.positive, .buttons a.positive{
+    color:#529214;
+}
+.buttons a.positive:hover, button.positive:hover{
+    background-color:#E6EFC2;
+    border:1px solid #C6D880;
+    color:#529214;
+}
+.buttons a.positive:active{
+    background-color:#529214;
+    border:1px solid #529214;
+    color:#fff;
+}
+
+/* NEGATIVE */
+
+.buttons a.negative, button.negative{
+    color:#d12f19;
+}
+.buttons a.negative:hover, button.negative:hover{
+    background:#fbe3e4;
+    border:1px solid #fbc2c4;
+    color:#d12f19;
+}
+.buttons a.negative:active{
+    background-color:#d12f19;
+    border:1px solid #d12f19;
+    color:#fff;
+}
+/* TOOLBOX NAV */
+ul#toolbox {list-style-position:inside;list-style-type:circle;}
+ul#toolbox li {list-style-type:circle}
+ul#toolbox li.toolboxArrow {list-style-type:none;padding-left:0;margin-left:-7px;}
+* html ul#toolbox li.toolboxArrow {margin-left:-20px;} /*style for IE*/
+.member-admin-table {clear:left;}
+.page-links {float:left;height:40px;width:100%;text-align:center;}
+.highlight1 tr,.highlight1 td { margin:1px 0; border:#8fae74 solid 1px; background-color:#8fae74;color:#000; }
+.highlight2 tr,.highlight2 td { margin:1px 0; border:#c2d8ae solid 1px; background-color:#c2d8ae;color:#000; }
+.highlight3 tr,.highlight3 td { margin:1px 0; border:#8fae74 solid 1px; background-color:#8fae74;color:#000; }
+.highlight4 tr,.highlight4 td { margin:1px 0; border:#c2d8ae solid 1px; background-color:#c2d8ae;color:#000; }
+.highlight5 tr,.highlight5 td { margin:1px 0; border:#8fae74 solid 1px; background-color:#8fae74;color:#000; }
+.highlight6 tr,.highlight6 td { margin:1px 0; border:#c2d8ae solid 1px; background-color:#c2d8ae;color:#000; }
+/*     -----------------       */
+/*       NEW MEMBER DB         */
+/*     -----------------       */
+
+/*     DATAGRID PAGER  */
+.paging {
+       text-align: center;
+       margin: 1.0em 0;
+       padding: 8px 0;
+       width: 100%;
+}
+.paging b,
+.paging a {
+       margin-right: 15px;
+}
+.paging b {
+       color: red;
+       padding: 5px 7px;
+       border: 1px solid #585F47;
+}
+.paging a:link,
+.paging a:visited {
+       border: solid 1px #DDDDDD;
+       color: #585F47;
+       padding: 5px 7px;
+       text-decoration: none;
+}
+.paging a:hover {
+       border: 1px solid #585F47;
+}
+
+/*     DATAGRID SORTER  */
+#gridSorter {
+       margin: 10px auto;
+       padding: 10px;
+       text-align: center;
+       border: 1px solid #96A379;
+}
+#gridSorter table,
+#gridSorter td {
+       border: none;
+}
+#gridSorter .fieldcell {
+       width: auto;
+}
+#advanced-search {
+       text-align: right;
+       cursor: pointer;
+       color: blue;
+}
+.req {
+       color: red;
+}
+#form-warning-top {
+       color: black;
+       font-size: 110%;
+       font-weight: bold;
+       margin: 10px;
+       padding: 7px;
+       border: 1px solid red;
+       background-color: #FFCCCC;
+}
+#form-success-top {
+       color: black;
+       font-size: 110%;
+       font-weight: bold;
+       margin: 10px;
+       padding: 7px;
+       border: 1px solid green;
+       background-color: #CCFFCC;
+}
+
+img {
+       border: 0;
+       display: block;
+       }
+/*   ---------------   */
+/*     NAVIGATION      */
+/*   ---------------   */
+#nav-detail {
+       margin-top: 12px;
+       height: 1%;
+       overflow: hidden;
+       clear: left;
+       }
+#nav-detail ul {
+  padding: 0px 0;
+       padding-bottom: 3px;
+  margin: 0;
+       margin-top: 10px;
+  border-bottom: 1px solid #666;
+  font-weight: bold;
+}
+#nav-detail ul li {
+  list-style: none;
+  margin: 0;
+  display: inline;
+}
+#nav-detail ul li a {
+  padding: 3px 0.5em;
+  margin-left: 3px;
+  border: 1px solid #666;
+  border-bottom: none;
+  background: #E6EFD1;
+  text-decoration: none;
+}
+#nav-detail ul li a:link { color: #666; }
+#nav-detail ul li a:visited { color: #666; }
+#nav-detail ul li a:hover {
+  color: #666;
+  background: #ccc;
+       background: #FFFBDF;
+  border-color: #666;
+}
+#nav-detail ul li a.current {
+  background: white;
+  border-bottom: 1px solid white;
+       color: #000;
+}
+
+/* Member Box */
+#member-info   {
+       margin: 0;
+       border: 1px solid #666;
+       border-top: 0;
+       padding: 6px;
+       position: relative;
+       height: 1%;
+       overflow: hidden;
+       clear: left;
+       }
+#member-info h1 {
+       font-size: 16px;
+       }
+#mRow1 {
+       margin: 10px;
+       }
+#memberdb #mRow1 {
+       float: left;
+       position: relative;
+       width: 400px;
+       }
+#mRow1 table {width: 100%;}
+
+#mRow2 {
+       margin: 10px;
+       }
+#memberdb #mRow2 {
+       float: right;
+       position: relative;
+       width: 285px;
+       }
+#mRow2 table {width: 100%;}
+
+#mRow1 .text {
+       width: 180px;
+       }
+#mRow2 .text {
+       width: 150px;
+       }
+.form {
+       clear: left;
+       display: block;
+       position: relative;
+       margin: 2em 0 1em 0;
+       padding: 0;
+       border: 0;
+       }
+#memberdb .form {
+       margin-top: 0;
+       }
+/* narrower column */
+.formNarrow {
+       clear: right;
+       margin: 0 0 1em 0;
+       }
+.form legend {
+       font-size: 1.2em;
+       font-weight: bold;
+       margin: 0;
+       padding: 0 0 0.3em 0;
+       color: #000;
+       }
+.form table,
+.form td {
+       border-collapse: collapse;
+       border: 1px solid #fff;
+       padding: 0;
+       background: #D6DFC3;
+       }
+.form td {
+       padding: 4px 6px;
+       }
+.form tr.fieldPending td {
+       background: #FFFF99;
+       border: 1px solid orange;
+       }
+.form label {
+       display: block;
+       }
+.labelcell {
+       text-align: right;
+       /* width: 120px; */
+       }
+.formNarrow .labelcell {
+       /* width: 110px; */
+       }
+.fieldcell {
+       text-align: left;
+       /* width: 220px; */
+       }
+.fieldcell img {float: left;}
+.formNarrow .fieldcell {
+       /* width: 150px; */
+       }
+
+/* Multiple rows in one cell    */
+.fieldcell i {
+       display: block;
+       font-style: normal;
+       padding: 5px;
+       text-align: left;
+       background-color: #eee;
+       margin-bottom: 1px;
+       }
+.fieldcell i img {
+ margin-right: 6px; }
+/* Category Dropdown */
+.fieldcell i optgroup {
+       font-style: normal;
+       font-size: 11px;
+       }
+.fieldcell i optgroup option {
+       padding: 0;
+       padding-left: 4px;
+       }
+
+
+/* Small graphics */
+.remove {
+       float: right;
+       clear: right;}
+.add {
+       display: block;
+       /* float: right; */
+       display: block;
+       font-style: normal;
+       padding: 5px;
+       text-align: left;
+       background-color: #eee;
+       margin-bottom: 1px;
+       }
+.add img {float: left; margin-right: 10px;}
+.fieldcell .info {
+       float: right;
+       }
+
+.priceFrom,
+.priceTo {
+       width: 4em;
+       }
+.submit {display: block;}
+
+/* Submit */
+.submitArea {
+       background: #D6DFC3;
+       text-align: center;
+       padding: 10px;
+       clear: both;
+       }
+.submitArea input {
+       margin: 0 auto;
+       display: block;
+       }
+
+
+/*   ---------------   */
+/*        PHOTOS       */
+/*   ---------------   */
+
+.movable {
+       background-image: url("../../../assets/buttons/arrow_out.png");
+       background-repeat: no-repeat;
+       background-position: 8px 8px;
+       }
+.photoItem {
+       margin-top: 1em;
+       padding: 28px 18px 18px 28px;
+       border: 1px solid #ccc;
+       height: 1%;
+       overflow: hidden;
+       position: relative;
+       background-color: #eee;
+       }
+.photoItem form {
+       height: 1%;
+       overflow: hidden;
+       border: 0px solid red;
+       }
+.photoItem .thumb {
+       float: left;
+       position: relative;
+       margin-right: 20px;
+       cursor: move;
+       }
+.photoItem i {
+       font-style: normal;
+       font-weight: bold;
+       display: block;
+       }
+.photoItem input {margin-top: 0.5em;}
+.photoItem input.text {
+       width: 400px;
+       }
+.photoItem .photoDelete {
+/*     display: block;
+       margin-top: 1em;
+       border: 1px solid #ccc;
+       background: #FFEFEF;
+       width: 130px;
+       padding: 3px;
+       color: #000;
+*/
+       position: absolute;
+       bottom: 20px;
+       right: 20px;
+
+       }
+.photoDelete:hover {background: #EFD1D1;}
+.photoItem .photoDelete img {
+       float: left;
+       margin-right: 6px;
+       }
+.photoOptions {}
+#pos-info {
+       font-size: 110%;
+       font-weight: bolder;
+       padding: 5px;
+       margin: 5px 0;
+       text-align: center;
+}
+
+
+/*   ---------------   */
+/*      CONTACTS          */
+/*   ---------------   */
+.contact {
+       margin-top: 1em;
+       padding: 20px;
+       border: 1px solid #96A379;
+       overflow: hidden;
+       position: relative;
+       background: #D6DFC3;
+}
+
+.contact input.text {
+       width: 200px;
+       display: block;
+}
+/* SPECIFIC TO Contacts RESULT HERE */
+.contactList {
+       border: 1px solid #96A379;
+       padding: 10px 10px;
+       margin: 5px 0;
+       background-color: #D6DFC3;
+       height: 1%;
+       overflow: hidden;
+       position: relative;
+}
+.contactListOn {
+       background-color: #E6EFD1;
+       cursor: hand;
+       cursor: pointer;
+}
+.contactList h3 {
+       font-size: 15px;
+       color: #333;
+       margin: 0 0 0 24px;
+       float: left;
+       width: 175px;
+}
+.contactListOn h3 {
+       color: #000;
+}
+.contactList .title {
+       position: absolute;
+       bottom: 10px;
+       right: 300px;
+       width: 170px;
+}
+.contactList a.remove {
+       position: absolute;
+       left: 10px;
+}
+.contactList .phone {
+       position: absolute;
+       bottom: 10px;
+       right: 240px;
+}
+.contactList .mail{
+       position: absolute;
+       bottom: 6px;
+       right: 8px;
+}
+.contactList a.email {
+       position: absolute;
+       bottom: 10px;
+       right: 40px;
+}
+.contactList a {
+       color: #96A379;
+   text-decoration: none;
+}
+.contactList a.email {
+       text-decoration: underline;
+}
+.contactList a:link {color: #585F47;}
+.contactList a:visited {color: #585F47;}
+.contactList a:hover {color: #585F47;}
+.contactList a:active {color: #585F47;}
+
+/*   ---------------   */
+/*      PACKAGES       */
+/*   ---------------   */
+
+.packageItem {
+       margin-top: 1em;
+       padding: 20px;
+       border: 1px solid #96A379;
+       height: 1%;
+       overflow: hidden;
+       position: relative;
+       background: #D6DFC3;
+       }
+
+.packageItem .thumb {
+       position: relative;
+       margin-bottom: 1em;
+       }
+.packageText {
+       float: left;
+       width: 400px;
+       padding-bottom: 1em;
+}
+.packageItem i {
+       font-style: normal;
+       font-weight: bold;
+       display: block;
+       padding-top: 1em;
+
+       }
+.packageItem input {margin-top: 0.5em;}
+.packageItem input.text {
+       width: 200px;
+       display: block;
+       }
+.packageItem textarea {
+       width: 300px;
+       height: 150px;
+       }
+.packageItem .packageDelete {
+       display: block;
+       margin-top: 1em;
+       border: 1px solid #ccc;
+       background: #FFEFEF;
+       width: 140px;
+       padding: 3px;
+       position: absolute;
+       bottom: 20px;
+       right: 20px;
+       color: #000;
+       }
+.packageDelete:hover {background: #EFD1D1;}
+.packageItem .packageDelete img {
+       float: left;
+       margin-right: 6px;
+       }
+.packageOptions {float: left;}
+
+
+
+/*   ---------------   */
+/*      AMENITIES      */
+/*   ---------------   */
+.amenityList {
+       list-style-type: none;
+       float: left;
+       position: relative;
+       zoom: 1;
+       width: 200px;
+       margin-right: 20px;
+       }
+#memberdb .amenityList {
+       margin-right: 50px;
+       }
+.amenityList input {
+       /* No Luck, see http://meyerweb.com/eric/thoughts/2007/05/15/formal-weirdness/ */
+}
+.amenityList li {
+       vertical-align: middle;
+       height: 1%;
+       overflow: hidden;
+       font-size: 1.1em;
+       }
+.amenityList label {
+  padding: 4px;
+  display: block;
+       background: #D6DFC3;
+       margin-bottom: 1px;
+}
+.amenityList label.amenityOn {
+       background-color: #E6EFD1;
+       cursor: hand;
+       cursor: pointer;
+       }
+.amenityList li.fieldPending label {
+       background: #FFFF99;
+       border: 1px solid orange;
+       }
+.amenityList li.fieldPending label.amenityOn {
+       background: #FFFFb2;
+       cursor: hand;
+       cursor: pointer;
+       }
+
+/* SPECIFIC TO SEARCH RESULT HERE */
+.searchResult {
+       border: 1px solid #96A379;
+       padding: 10px 20px;
+       margin: 5px 0;
+       background-color: #D6DFC3;
+       height: 1%;
+       overflow: hidden;
+       position: relative;
+}
+.searchResultOn {
+       background: url("../../../assets/searchResultOn.gif") no-repeat 98% center #E6EFD1;
+       cursor: hand;
+       cursor: pointer;
+}
+.searchResult a.remove {
+       position: absolute;
+       left: 10px;
+}
+.searchResult h3 {
+       font-size: 15px;
+       color: #333;
+       margin: 0 0 0 20px;
+       float: left;
+       width: 280px;
+       }
+.searchResultOn h3 {
+       color: #000;
+}
+.searchResult .phone {
+       position: absolute;
+       bottom: 10px;
+       right: 300px;
+}
+.searchResult a.email {
+       position: absolute;
+       bottom: 10px;
+       right: 90px;
+}
+.searchResult a {
+       color: #96A379;
+   text-decoration: none;
+}
+.searchResult a.email {
+       text-decoration: underline;
+}
+.searchResult a:link {color: #585F47;}
+.searchResult a:visited {color: #585F47;}
+.searchResult a:hover {color: #585F47;}
+.searchResult a:active {color: #585F47;}
+
+.pending {
+       background-color: #FFFF99;
+       border: 1px solid orange;
+}
+.pendingMsg {
+       padding: 5px;
+       text-align: center;
+}
+.pendingPhotoCaption, .pendingLogo,
+.pendingFileName {
+       text-align: center;
+}
+.pendingFileName a {
+       text-decoration: none;
+       margin-bottom: 5px;
+       display: block;
+}
+/*
+#pendingUpdates {
+       width: 100%;
+}
+#pendingUpdates .labelcell {
+       width: 100px;
+}
+#pendingUpdates .fieldcell {
+       width: 100%;
+}
+#pendingUpdates .fieldcell div {
+       float: left;
+       color: green;
+}
+#pendingUpdates .fieldcell div + div {
+       color: red;
+}
+label.pendingUpdate {
+       display: block;
+}
+*/
+#subnavcontainer a.hasPending {
+       background: url("../../../images/flag_green.png") center right no-repeat;
+       padding-right: 21px;
+}
+.fieldcell .form_calendar {
+       display: inline;
+       float: none;
+       vertical-align: bottom;
+}
+
+/* Pending Member Stuff */
+
+.pendingUpdates {
+       width: 100%;
+}
+.pendingPhotoCaption img,
+.pendingUpdates img  {
+       float: left;
+}
+.updates .field {
+       float: left;
+       clear: left;
+       margin-top: 3px;
+       position: relative;
+}
+.authorization {
+        float: right;
+       position: relative;
+       width: 100px;
+       padding: 10px;
+       background: #EAEFE0;
+       border: 1px solid #C3CFA8;
+}
+.authorization label {
+       margin: 5px;
+       font-weight: bold;
+       font-size: 13px;
+}
+
+/* search result pagination */
+.pages {
+       padding: 1em 0;
+       clear: left;
+}
+.pages a, .pages b {
+       color: #003366;
+       display: block;
+       float: left;
+       padding: 0.2em 0.5em;
+       margin-right: 0.1em;
+       border: 1px solid #fff;
+       background: #fff;
+}
+.pages b, .business-first-letter a.curr {
+       border: 1px solid #2E6AB1;
+       font-weight: bold;
+       background: #2E6AB1;
+       color: #fff;
+}
+.pages a {
+       border: 1px solid #9AAFE5;
+       text-decoration: none;
+}
+.pages a:hover, .business-first-letter a:hover {
+       border-color: #2E6AB1;
+}
+.business-first-letter {
+       margin: 1em 0;
+}
+.business-first-letter > div {
+       margin-bottom: 1em;
+}
+.business-first-letter a {
+       margin-right: 0.1em;
+       color: #003366;
+       padding: 0.1em 0.4em;
+       border: 1px solid #9AAFE5;
+       text-decoration: none;
+}
+.level-0 {
+        font-weight: bold;
+        padding-left: 0;
+        background-color: #ccc;
+}
+.level-1 {
+        padding-left: 20px;
+        background-color: #ddd;
+        }
+.level-2 {padding-left: 40px;}
+.level-3 {padding-left: 60px;}
+.level-4 {padding-left: 80px;}
+.level-5 {padding-left: 100px;}
+.level-6 {padding-left: 120px;}
+
+#advanced-record-search img.ui-datepicker-trigger {
+       display: inline;
+       float: none;
+}
+.treeOperators {margin: 1em 0;}
+.treeOperators button {
+       margin-right: 10px;
+}
+.tree li a {background-image: url("../../../images/note_edit.png");}
diff --git a/Toolkit/Members/css/member.css b/Toolkit/Members/css/member.css
new file mode 100755 (executable)
index 0000000..1a07e08
--- /dev/null
@@ -0,0 +1,682 @@
+/* Member Search and display */
+#category-search {
+       clear: both;
+       padding: 0;
+       margin-top: 22px;
+}
+#category-search li {
+       list-style-image:none;
+}
+#category-search fieldset {
+background-color: #ffffff;
+  background-image: -moz-linear-gradient(top, #ffffff, #E9F0F7); /* FF3.6 */
+  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #ffffff),color-stop(1, #E9F0F7)); /* Saf4+, Chrome */
+            filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E9F0F7'); /* IE6,IE7 */
+        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E9F0F7')"; /* IE8 */
+  background-position: 0 -1px;
+  background-repeat: repeat-x;
+  border: 1px solid #95B1CD;
+       -moz-border-radius: 5px;
+       -webkit-border-radius: 5px;
+       border-radius: 5px;
+       clear: both;
+  margin-bottom: 1.5em;
+  padding: 0;
+}
+#category-search legend {
+       color: #000;
+       font-weight: bold;
+       margin-left: 1em;
+}
+#category-search fieldset ol {
+       list-style-image: none;
+       list-style-position: outside;
+       list-style-type: none;
+       padding: 1em 1em 0;
+}
+#category-search fieldset li {
+  clear:       left;
+  /* float:    left; */
+  padding-bottom:      0.5em;
+  width:       100%;
+}
+#category-search fieldset.submit {
+  border-style: none;
+  left: 120px;
+  position: relative;
+  width: 100px;
+}
+
+#category-search #amenitySearchAll label {
+       display: inline;
+       float: none;
+       width: auto;
+}
+#category-search-result {
+  clear: both;
+  margin: 10px;
+}
+#amenities label {
+       text-align: left !important;
+       width: 190px !important;
+       margin-left: 30px;
+       float: left;
+       }
+
+.reservation-button {
+       float: right;
+       margin: 15px 7px 0 7px;
+       }
+
+/* Member List */
+.search-result-item {
+       padding: 15px 20px;
+  background-color: #eee;
+  height: 1%;
+  margin-bottom: 5px;
+  overflow: hidden;
+  position: relative;
+       background-color: #ffffff;
+       background-image: -moz-linear-gradient(top, #ffffff, #E9F0F7); /* FF3.6 */
+       background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #ffffff),color-stop(1, #E9F0F7)); /* Saf4+, Chrome */
+       filter:  progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E9F0F7'); /* IE6,IE7 */
+       -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E9F0F7')"; /* IE8 */
+       border: 1px solid #95B1CD;
+       -moz-border-radius: 5px;
+       -webkit-border-radius: 5px;
+       border-radius: 5px;
+}
+.search-result-item-on {
+  border: 1px solid #726646 !important;
+}
+.memberSR {
+       float: right;
+       }
+.list-add-link img, .list-view-link img {
+       margin-bottom: 10px;
+}
+.search-result-img {
+       clear: right;
+       }
+.search-result-item h2 {
+  padding: 0;
+       margin: 0 0 0.5em 0;
+}
+.search-result-item h2 a:link {color: #00456C;}
+.search-result-item h2 a:visited {color: #00456C;}
+.search-result-item h2 a:hover {color: #3D8D3A;}
+.search-result-item h2 a:active {color: #00456C;}
+
+.search-result-location {
+       float: left;
+}
+.search-result-distance {
+  clear: left;
+  float: left;
+  font-style: italic;
+  position: relative;
+}
+.search-result-more2 {
+  border: 0 none;
+  position: absolute;
+  right: 10px;
+  top: 60px;
+}
+div.search-result-more-div {
+       clear: left;
+       margin-top: 3px;
+}
+div.search-result-more-div a {
+       display: block;
+       width: 150px;
+       padding: 3px;
+       font-weight: bold;
+       border: 1px solid #077582;
+       text-decoration: none;
+       text-align: center;
+       margin-top: 3px;
+       }
+div.search-result-more-div a:link {
+       background-image:url(assets/listing-bg1.gif);
+       color: #077582;
+       }
+div.search-result-more-div a:visited {
+       background-image:url(assets/listing-bg1.gif);
+       color: #077582;
+       }
+div.search-result-more-div a:hover {
+       background-image:url(assets/listing-bg2.gif);
+       color: #077582;
+       }
+div.search-result-more-div a:active {
+       background-image:url(assets/listing-bg1.gif);
+       color: #077582;
+       }
+.member-coupon, .member-valuecard {
+       float: left;
+       clear: left;
+       position: relative;
+       margin-top: 10px;
+       margin-left: 76px;
+       display: inline;
+       }
+#member-detail {
+       clear: left;
+       padding-top: 10px;
+       }
+#member-img-1 { padding-right:10px; }
+#business-list-contacts {clear: left;}
+#business-list-contacts h2 {margin-bottom: 0;}
+#member-detail .vcard {
+       float: left;
+       width:  200px;
+       }
+#member-detail .member-button {
+       float: left;
+       clear: right;
+       position: relative;
+       margin: 15px 5px 15px 0;
+       }
+.business-contact {display: list-item; margin-left: 20px;}
+.vcard h1 {
+       font-size: 18px;
+       }
+#image-box {
+       float: right;
+       width: 270px;
+       margin-bottom: 10px;
+       margin-left: 10px;
+       }
+#photo-caption {
+       text-align: center;
+       margin-top: 3px;
+       }
+#google-div {
+       margin: 1em 0;
+       clear: left;
+       width: 230px;
+       background: #CBDEF2;
+       border: 1px solid #28578F;
+       padding: 6px 10px;
+       position: relative;
+       }
+#google-div h3 {margin: 0; font-size: 12px !important; margin-bottom: 3px}
+#google-div input {font-size: 12px;}
+#ccards {
+       height: 1%;
+       overflow: hidden;
+       float: right;
+       border: 1px solid #ccc;
+       padding: 5px;
+       width: 150px;
+       clear: right;
+       margin-top: 12px;
+       margin-left: 12px;
+       }
+#ccards img {float: left; margin: 0 10px 10px 0;}
+#ccards h2 {font-size: 12px; margin: 0;}
+#member-img-l {
+       display:block;
+}
+.member-img-s {
+       cursor: pointer;
+       cursor: hand;
+  float: left;
+  margin: 10px 10px 0 0;
+  position: relative;
+       display: inline;
+}
+.business-list-amenities {
+       font-weight: bold;
+       line-height: 15px;
+}
+.business-list-amenities ul {
+  margin:0;
+  padding:10px;
+       margin-left: 10px;}
+.business-list-amenities li {
+       }
+.business-list-amenities ul {
+       margin: 0;
+       padding: 10px;
+       list-style-type: disc;
+  }
+.business-list-amenities li {
+       border: 0;
+       background: none;
+       list-style-type: disc;
+  }
+.member-travel-item {
+       margin-top: 1em;
+       clear: both;
+       }
+.member-travel-item img {
+       float: right;
+       clear: right;
+       padding-bottom: 10px;
+       }
+.member-travel-item h2 {
+       clear: both;
+       }
+#search-more {
+  height: 1%;
+  margin: 10px 10px 10px 10px;
+  overflow: hidden;
+  padding: 10px;
+}
+#search-more fieldset {
+  background-color: #AFCDEF;
+       background-position: 0 -1px;
+  background-repeat: repeat-x;
+  border: 1px solid #244B8D;
+  clear: both;
+  margin: 0 10px 0 0;
+  padding: 5px 0;
+}
+#search-more legend {
+  color: #000;
+  font-weight: bold;
+  margin-left: 1em;
+}
+#search-more form {
+       margin: 0;
+}
+fieldset.submit {
+       border-style: none;
+}
+#search-more select {margin-top: 3px;}
+#search-more label {
+  display: block;
+  float: left;
+  height: 1%;
+  margin: 5px;
+  text-align: right;
+  width: 100px;
+  clear: left;
+}
+/*
+3 Specialty Sections.
+Restaurant, Hotels and Golf Courses
+*/
+
+#member-files {
+       margin-top: 1em;
+       height: 1%;
+       overflow: hidden;
+}
+/* Header Sizes */
+.member-golf-result h2,
+.member-hotel-result h2,
+.member-restaurant-item h2,
+#member-files h2 {
+       font-size: 15px;
+       }
+/* Golf result list */
+.member-golf-result {
+       clear: both;
+       height: 1%;
+       overflow: hidden;
+       margin-top: 1em;
+       }
+/* walking Course? */
+.member-golf-walking {
+       margin-left: 20px;      }
+/* Par stats table */
+.member-golf-stats {
+       float: left;
+       clear: left;
+       margin-top: 2px;
+       margin-left: 2px;
+       margin-bottom: 6px;
+       margin-right: 20px
+       }
+/* Fees Table */
+.member-golf-fees { float: left;       }
+.member-golf-result table, .member-golf-result td, .member-golf-result th {
+       border: 1px solid #BDD8BC;
+       border-collapse: collapse;
+       background: #eee;
+       font-size: 11px;
+       }
+.member-golf-result td, .member-golf-result th {
+       padding: 3px 6px;
+       }
+/* Accommodations Result List */
+.search-result-item-info .member-hotel-result {
+       height: 1%;
+       overflow: hidden;
+       position: absolute;
+       top: 14px;
+       right: 12px;
+       height: 50px;
+       display: none;
+       }
+#member-detail .member-hotel-result {
+       position: relative;
+       float: right;
+       margin: 0 0 20px 20px;
+       background: #ddd;
+       border: 2px solid #ccc;
+       padding: 10px;
+       }
+#member-detail .member-hotel-result img {
+       margin-bottom: 2px;
+       }
+#member-detail p {margin-top: 0;}
+/* Restaurant Information */
+.member-restaurant-item {
+       clear: left;
+       margin-top: 1em;
+       margin-left: 0;
+       margin-bottom: 6px;
+       margin-right: 20px;
+       }
+.member-restaurant-item table, .member-restaurant-item td, .member-restaurant-item th {
+       border: 1px solid #BDD8BC;
+       border-collapse: collapse;
+       background: #eee;
+       font-size: 12px;
+       }
+.member-restaurant-item td, .member-restaurant-item th {
+       padding: 4px 8px;
+       }
+
+/* Controls the transfer box when updating a member image
+ * on the member-detail page
+ */
+.ui-effects-transfer {border: 2px solid black;}
+/* Right Column Member Deatil */
+#mColumn {
+       clear: right;
+       float: right;
+       position: relative;
+       width: 146px;
+       border: 1px solid #ccc;
+       border-bottom: 0;
+       margin-left: 20px;
+       }
+#mColumn h2 {
+       font-size: 12px;
+       border-bottom: 1px solid #ccc;
+       padding: 8px 8px 4px 8px;
+       margin: 0;
+       background: #eee;
+       }
+#mColumn ul, #mColumn li {
+       margin: 0;
+       padding: 0;
+       list-style-type: none;
+       font-size: 12px;
+        }
+#mColumn li {
+       border-bottom: 1px solid #ccc;
+       background-position: 5px 5px;
+       background-repeat: no-repeat;
+       }
+#mColumn ul ul {
+       margin: 0;
+       padding: 10px;
+       list-style-type: disc;
+       list-style-position: inside;
+  }
+#mColumn ul ul li {
+       border: 0;
+       background: none;
+       list-style-type: disc;
+  }
+#mColumn p {
+       margin: 0;
+       padding: 4px 8px 4px 28px;
+  }
+#mColumn a {
+       margin: 0;
+       display: block;
+       padding: 4px 8px 4px 28px;
+       }
+#mColumn ul ul a {
+       display: inline;
+       padding: 0;
+       }
+#mColumn a:hover {
+               text-decoration: none;
+       }
+/* Icons */
+.mFacebook     { background-image: url(http://app.gaslightmedia.com/assets/deadsimple/facebook.gif); }
+.mPinterest    { background-image: url(http://app.gaslightmedia.com/assets/deadsimple/pinterest.png); }
+.mMyspace      { background-image: url(http://app.gaslightmedia.com/assets/deadsimple/myspace.gif); }
+.mTwitter      { background-image: url(http://app.gaslightmedia.com/assets/deadsimple/twitter.gif); }
+.mLinkedIn     { background-image: url(http://app.gaslightmedia.com/assets/deadsimple/linkedin.gif); }
+.mBlog         { background-image: url(http://app.gaslightmedia.com/assets/deadsimple/blogger.gif); }
+.mYouTube      { background-image: url(http://app.gaslightmedia.com/assets/deadsimple/youtube2.gif); }
+.mReservations { background-image: url(http://app.gaslightmedia.com/assets/icons/book_open.png); }
+/* Photo Gallery on member detail pages */
+#member-detail #photo-gallery {
+       clear: both;
+       margin: 0;
+       border-top: 1px dotted #aaa;
+       padding-top: 1em;
+}
+/* Trip Planner Stuff */
+.tpBox {
+       border-right: 1px solid #3D1006;
+       border-bottom: 1px solid #3D1006;
+       border-left: 1px solid #CBCBAA;
+       border-top: 1px solid #CBCBAA;
+       background: #eee;
+       }
+#accountBox {
+       height: 1%;
+       overflow: hidden;
+       }
+#accountBox h2 {
+       margin: 0 0 6px 0;
+       padding: 0;
+       }
+#loggedInAs {
+       float: left;
+       width: 65%;
+       padding: 6px;
+       }
+#plannerLogin, #plannerAcc {
+       width: 31%;
+       float: left;
+       padding: 6px;
+       }
+.tpBoxNoList #plannerAcc, .tpBoxNoList #plannerLogin  {
+       width: 44%;
+       padding: 16px;
+       }
+#plannerAcc {
+       border-right: 1px dashed #ccc;
+       border-left: 1px dashed #ccc;
+       }
+.tpBoxNoList #plannerAcc {
+       border: 0;
+       }
+.tpBoxNoList #plannerLogin {
+       border-right: 1px dashed #ccc;
+       }
+#plannerUser, #plannerP, #plannerSubmit {
+       margin: 3px 0;
+       }
+.tpBoxNoList #plannerUser, .tpBoxNoList #plannerP, .tpBoxNoList #plannerSubmit {
+text-align: right;     }
+
+#accountBox #plannerLogin input {
+       width: 140px;
+       display: block;
+       font-size: 14px;
+       }
+#accountBox.tpBoxNoList #plannerLogin input {
+       width: 140px;
+       display: inline;
+       font-size: 14px;
+       }
+#plannerForgot {
+       font-size: 11px;
+       margin: 3px 0;
+       }
+#accountBox #plannerNew {
+       display: block;
+       padding: 6px 6px 6px 26px;
+       background: url(http://app.gaslightmedia.com/assets/icons/add.png) no-repeat 5px center #fff;
+       margin-left: 0;
+       border: 1px solid #ccc;
+       font-size: 16px;
+       }
+#accountBox #plannerNew:hover {
+       background-color: green;
+       color: white;
+       }
+/* Items */
+#plannerList {
+       padding: 6px;
+       margin: 0;
+       clear: both;
+       }
+/* page break */
+.page-break { display:none; }
+
+.plannerItem {
+       border: 1px solid #ddd;
+       border-left: 20px solid #eee;
+       background: #fff;
+       padding: 1px 0 6px 0;
+       position: relative;
+       clear: both;
+       margin-top: 12px;
+       height: 1%;
+       overflow: hidden;
+}
+.plannerRemove {
+       text-indent: -5000px;
+       background: url(http://app.gaslightmedia.com/assets/icons/delete.png) no-repeat;
+       width: 20px;
+       height: 20px;
+       display: block;
+       position: absolute;
+       top: 6px;
+       right: 6px;
+       }
+#tpBreadcrumbs {
+       font-size: 12px;
+       padding: 6px 0 3px 10px;
+       margin: 0;
+}
+#tpBreadcrumbs a {
+       font-weight: normal;
+}
+.plannerItem h2 {
+       font-size: 18px;
+       padding: 3px 0 0 10px;
+       margin: 0;
+       }
+.plannerAddress {
+       width: 48%;
+       float: left;
+       padding-top: 0.5em;
+               }
+.plannerItem p {
+       margin: 0 10px;
+       }
+.plannerInfo {
+       float: right;
+       width: 48%;
+       margin-top: 0px;
+       padding-top: 0.5em;
+       }
+p.plannerTime {
+       background: #CBCBAA;
+       background: transparent;
+       padding: 3px 6px;
+       padding: 0;
+       margin: 0;
+       position: absolute;
+       bottom: 6px;
+       left: 10px;
+       font-style: italic;
+       }
+ul#plannerNav {
+       list-style-type: none;
+       margin: 0;
+       padding: 10px;
+       width: 28%;
+       float: left;
+       }
+ul#plannerNav li {
+       list-style-type: none;
+       margin: 0;
+       padding: 0;
+}
+ul#plannerNav li a {
+       display: block;
+       padding: 5px 0 5px 26px;
+       background-position: 4px center;
+       background-repeat: no-repeat;
+       margin-bottom: 3px;
+       border: 1px solid #eee;
+       }
+ul#plannerNav li#pN1 a {
+       background-image: url(http://app.gaslightmedia.com/assets/icons/email_edit.png);
+}
+ul#plannerNav li#pN2 a {
+       background-image: url(http://app.gaslightmedia.com/assets/icons/printer.png);
+}
+ul#plannerNav li#pN3 a {
+       background-image: url(http://app.gaslightmedia.com/assets/icons/map.png);
+       }
+ul#plannerNav li#pN4 a {
+       background-image: url(http://app.gaslightmedia.com/assets/icons/help.png);
+       }
+ul#plannerNav a:hover {
+       background-color: white !important;
+       border: 1px solid #ccc;
+       }
+
+.pages {
+       padding: 1em 0;
+       clear: left;
+}
+.pages a, .pages b {
+       color: #003366;
+       display: block;
+       float: left;
+       padding: 0.2em 0.5em;
+       margin-right: 0.1em;
+       border: 1px solid #fff;
+       background: #fff;
+}
+.pages b, .business-first-letter a.curr {
+       border: 1px solid #2E6AB1;
+       font-weight: bold;
+       background: #2E6AB1;
+       color: #fff;
+}
+.pages a {
+       border: 1px solid #9AAFE5;
+       text-decoration: none;
+}
+.pages a:hover, .business-first-letter a:hover {
+       border-color: #2E6AB1;
+}
+.business-first-letter {
+       margin: 1em 0;
+}
+.business-first-letter > div {
+       margin-bottom: 1em;
+}
+.business-first-letter a {
+       margin-right: 0.1em;
+       color: #003366;
+       padding: 0.1em 0.4em;
+       border: 1px solid #9AAFE5;
+       text-decoration: none;
+}
+/* member db category search result, numbered icons */
+.search-result-map-img {
+       float: left;
+       margin-right: 7px;
+       }
+div.thumb {
+       margin: 2px 3px;
+       }
diff --git a/Toolkit/Members/export-images-is0.php b/Toolkit/Members/export-images-is0.php
new file mode 100755 (executable)
index 0000000..892db05
--- /dev/null
@@ -0,0 +1,81 @@
+<?php
+/**
+ * Export images from local directories into the Image Server
+ *
+ * PHP version 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: export-images-is0.php,v 1.4 2009/12/29 14:17:49 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * setup file
+ */
+require_once '../../setup.phtml';
+
+/**
+ * Image Server API
+ */
+require_once BASE.'Toolkit/Image/Server.php';
+
+$db = new PDO('pgsql:'.CONN_STR);
+
+/**
+ * Description for define
+ */
+define('OLDORG', 'http://demo.gaslightmedia.com/images/member_original/');
+$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+$sql = "
+  SELECT member_id, logo
+    FROM member
+   WHERE logo <> ''
+     AND logo not like 'is%'
+   ORDER BY member_id";
+try {
+    $stmt = $db->query($sql);
+    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
+    echo '<pre>';
+    print_r($data);
+    echo '</pre>';
+} catch(PDOException $e) {
+    die($e->getMessage());
+}
+$db->beginTransaction();
+$IServer = new Toolkit_Image_Server();
+if (is_array($data)) {
+    $prep2 = "
+    UPDATE member
+       SET logo = :image
+     WHERE member_id = :id";
+    $stmt3 = $db->prepare($prep2);
+
+    foreach ($data as &$row) {
+        $row['logo'] = trim($row['logo']);
+            var_dump(OLDORG.$row['logo']);
+        if (!preg_match("/^is/", $row['logo'])) {
+            $image_URL = OLDORG.urlencode($row['logo']);
+            $image     = $IServer->imageUpload($image_URL);
+            if ($image) {
+                try {
+                    $stmt3->bindParam(":image", $image, PDO::PARAM_STR);
+                    $stmt3->bindParam(":id", $row['member_id'], PDO::PARAM_INT);
+                    $stmt3->execute();
+                } catch(PDOException $e) {
+                    die($e->getMessage());
+                }
+            }
+            echo '<br>Image Name Returned: ';
+            var_dump($image);
+        }
+    }
+}
+//$db->commit();
+$db->rollBack();
+?>
diff --git a/Toolkit/Members/libjs/advancedsearch.js b/Toolkit/Members/libjs/advancedsearch.js
new file mode 100644 (file)
index 0000000..bed3ca6
--- /dev/null
@@ -0,0 +1,71 @@
+var AdvancedSearch =
+{
+       init: function()
+       {
+               //      select groups that need a calendar
+               var $elements = new Array(
+                       'create_date_beg',
+                       'create_date_end',
+                       'join_date_beg',
+                       'join_date_end',
+                       'last_modified_date_beg',
+                       'last_modified_date_end'
+               );
+
+               for (i in $elements) {
+                       //      Used to create unique ids for the hidden elements
+                       var $myDate = new Date();
+                       var $selectElem = $("select[name='"+$elements[i]+"[Y]']");
+                       var $newId = 'datePicker_' + $myDate.valueOf();
+                       $('<input type="hidden" disabled="disabled" id="'+$newId+'">').insertAfter($selectElem);
+
+                       var $minYear = $selectElem.find('option:nth-child(2)');
+                       var $maxYear = $selectElem.find('option:last-child');
+                       $('#' + $newId).datepicker({
+                               beforeShow: AdvancedSearch.readSelected,
+                               onSelect: AdvancedSearch.updateSelected,
+                               minDate: new Date($minYear.val(), 1 - 1, 1),
+                               maxDate: new Date($maxYear.val(), 12 - 1, 31),
+                               showOn: 'both',
+                               buttonImageOnly: true,
+                               buttonImage: 'http://app.gaslightmedia.com/assets/icons/calendar.png'
+                       });
+               }
+       },
+
+       readSelected: function(input, inst)
+       {
+               var $selects = $('#' + inst.id).prevUntil('img');
+               var $tgtDate = $('#' + inst.id);
+               $tgtDate.val(
+                       $selects.get(2).value + '/' +
+                       $selects.get(1).value + '/' +
+                       $selects.get(0).value
+               );
+       },
+
+       updateSelected: function(date, inst)
+       {
+               var $selects = $('#' + inst.id).prevUntil('img');
+
+               //      select month values are 1, 2, 3  not 01, 02, 03
+               //      If we're on a single digit, just grab that single
+               //      digit substring value
+               var $month = (date.substring(0, 1) == '0')
+                       ? date.substring(1, 2)
+                       : date.substring(0, 2);
+
+               //      select day values are 1, 2, 3  not 01, 02, 03
+               //      If we're on a single digit, just grab that single
+               //      digit substring value
+               var $day = (date.substring(3, 4) == '0')
+                       ? date.substring(4, 5)
+                       : date.substring(3, 5);
+
+               $selects.get(2).value = $month;
+               $selects.get(1).value = $day;
+               $selects.get(0).value = date.substring(6, 10);
+       }
+};
+
+$(document).ready(AdvancedSearch.init);
diff --git a/Toolkit/Members/libjs/authorizeChanges.js b/Toolkit/Members/libjs/authorizeChanges.js
new file mode 100644 (file)
index 0000000..3abf74f
--- /dev/null
@@ -0,0 +1,19 @@
+/**
+ * setup CKEditors for any textarea field that might exists on the page.
+ */
+var AuthorizeChanges =
+{
+       init: function()
+       {
+        //  Only try to replace the textarea if the 
+        //  CKEditor is compatible w/ the browser.
+        if (CKEDITOR.env.isCompatible) {
+            CKEDITOR.replaceAll(function(textarea, config)
+                {
+                    config.toolbar = 'LimitedToolset';
+                });
+        }
+       }
+}
+
+$(document).ready(AuthorizeChanges.init);
diff --git a/Toolkit/Members/libjs/business-detail.js b/Toolkit/Members/libjs/business-detail.js
new file mode 100755 (executable)
index 0000000..6d4fab4
--- /dev/null
@@ -0,0 +1,83 @@
+var GDirs =
+{
+       dBox: null,
+       originalText: null,
+       addyBox: null,
+
+       init: function()
+       {
+               $('#member-detail a.external').each(function() {
+                       $(this).click(function() {
+                               var $newWindow = window.open($(this).attr('href'));
+                               $newWindow.focus();
+                               return false;
+                       });
+               });
+
+               GDirs.addyBox = $('#toaddress');
+               GDirs.originalText = GDirs.addyBox.val();
+               GDirs.dBox = $('#google-div');
+               GDirs.dBox.before('<a href="#" id="google-map-link" class="member-button" title="Get Driving Directions"> Directions </a>');
+               GDirs.dBox.hide();
+               $('#google-map-link').bind('click', GDirs.toggleBox);
+               $('#GDirs').bind('submit', GDirs.submitForm);
+               GDirs.addyBox.bind('focus', GDirs.clearForm);
+               GDirs.addyBox.bind('blur', GDirs.fillForm);
+        $('.list-add-link').click(function(){
+            var member_id = $(this).attr('rel');
+            $.ajax({
+                type: "POST",
+                url: glm_base_url + "trip-planner-list/" + member_id + "/" + glm_catid + "/",
+                beforeSend: function() {$('#loading-planner').show()},
+                complete: function() {$('#loading-planner').hide()},
+                success: function(ret){
+                    GDirs.toggleTravelLink(ret);
+                }
+            });
+            return false;
+        });
+        
+       },
+    
+    toggleTravelLink: function(event) {
+        GDirs.updateList(event);
+        var html = '<a href="' + glm_base_url + 'my-west-michigan-' + glm_trip_planner_id + '/" flexy:if="plink" class="list-view-link">';
+        html += '<img alt="View Your Travel List" title="View Your Travel List" src="';
+        html += glm_base_url + 'assets/viewTravelPlanner.png" style="float: right; margin: 10px;clear: right;">';
+        html += '</a>';
+        $('.list-add-link').replaceWith(html);
+    },
+
+       toggleBox: function(event)
+       {
+               event.preventDefault();
+               GDirs.dBox.slideToggle('normal');
+       },
+
+       submitForm: function(event)
+       {
+               if (GDirs.addyBox.val() == GDirs.originalText || GDirs.addyBox.val() == '') {
+                       event.preventDefault();
+                       alert('Please fill in your Address');
+               }
+       },
+
+       clearForm: function(event)
+       {
+               if (GDirs.addyBox.val() == GDirs.originalText) {
+                       GDirs.addyBox.val('');
+               }
+       },
+
+       fillForm: function(event)
+       {
+               if (GDirs.addyBox.val() == '') {
+                       GDirs.addyBox.val(GDirs.originalText);
+               }
+       },
+    updateList: function (listCount){
+        $(".trip-list-count").html(listCount);
+    }
+};
+
+$(document).ready(GDirs.init);
diff --git a/Toolkit/Members/libjs/business-search.js b/Toolkit/Members/libjs/business-search.js
new file mode 100644 (file)
index 0000000..69aa72e
--- /dev/null
@@ -0,0 +1,273 @@
+var Search =
+{
+    //  {{{ properties
+
+    catSelected: false,
+    subCatSelected: false,
+
+    //  }}}
+    //  {{{ init()
+
+       init: function()
+       {
+        $(".t-list-link").bind("click", function(){
+            var href = $(this).attr('href');
+            $(this).attr('href', href + '&pageOffset=' + window.pageYOffset);
+        });
+
+               $('.search-result-item')
+            .mouseover(Search.highlightMember)
+            .mouseout(Search.lowlightMember)
+            .click(Search.goToMember);
+
+               //      Stop the propagation so the goToMember function won't
+               //      be called when these links are clicked.
+               $('.search-result-email, .search-result-website, .search-result-directions')
+                       .click(function(event) {
+                               event.stopPropagation();
+                       });
+
+               $("select[name='category_id']").change(Search.populateMemberSubType);
+               $("select[name='region_id']").change(Search.repopulateCategories);
+
+        Search.setGET();
+               Search.repopulateCategories();
+               Search.populateMemberSubType();
+       },
+
+    //  }}}
+    //  {{{ setGET()
+
+    setGET: function()
+    {
+        var get=(""+location.search).substring(1).split("&");
+        window.location.GET = new Array();
+        for (var i in get) {
+            var temp = get[i].split("=");
+            window.location.GET[temp[0]] = temp.splice(1, temp.length-1).join("=");
+        }
+    },
+
+    //  }}}
+    //  {{{ highlightMember()
+
+       highlightMember: function(event)
+       {
+               if ($(this).find("a[title='More Info']").is('a')) {
+                       $(this).addClass('search-result-item-on');
+               }
+       },
+
+    //  }}}
+    //  {{{ lowlightMember()
+
+       lowlightMember: function(event)
+       {
+               if ($(this).find("a[title='More Info']").is('a')) {
+                       $(this).removeClass('search-result-item-on');
+               }
+       },
+
+    //  }}}
+    //  {{{ goToMember()
+
+       goToMember: function(event)
+       {
+               var link = $(this).find("a.moreInfo");
+               if (link.is('a')) {
+                       document.location.href = link.attr('href');
+               }
+       },
+
+    //  }}}
+    //  {{{ repopulateCategories()
+
+    /**
+     * repopulate the sub category box based on the the value
+     * selected in the region box
+     *
+     * if no region was selected, then get all main categories available
+     *
+     * if a region was selected, then get all main categories available in that
+     * region.
+     */
+    repopulateCategories: function(event)
+    {
+       // Get currently selected "Region"
+        if ($("[name='region_id']").is("select")) {
+            var region = $("select[name='region_id'] option:selected").val();
+        } else {
+            var region = $("input[name='region_id']").val();
+        }
+
+        // Get currently selected "Member Type" (category)
+               var catList = $("select[name='category_id']");
+
+               // Clear category list
+               $("select[name='category_id'], select[name='sub_category_id']")
+            .empty()
+            .append('<option value="">-- Select --</option>');
+
+               var usedValues = [];
+               var options = [];
+               var cats = [];
+
+       // If we have the RegionCats data (json)
+               if (window.RegionCats != undefined) {
+            var RegionCats = window.RegionCats;
+                       
+                       // If no region is selected
+                       if (region == undefined || region == '') {
+                // For each region
+                               $.each(RegionCats, function(id, obj) {
+                                       // If that region has categories in RegionCats
+                                       if (RegionCats[id]) {
+                                               // Add each of those categories
+                                               $.each(RegionCats[id], function(i, j) {
+                                                       if (!usedValues[i]) {
+                                                               usedValues[i] = true;
+                                                               cats[mainCats[i]] = i;
+                                                               options.push(mainCats[i]);
+                                                       }
+                                               });
+                                       }
+                               });
+                               
+                       // Otherwise do this for the selected region
+                       } else {
+                               // For each category in this region 
+                               $.each(RegionCats[region], function(id, obj) {
+                                       // Add the category
+                                       cats[mainCats[id]] = id;
+                                       options.push(mainCats[id]);
+                               });
+                       }
+                       
+        } // if RegionCats
+               
+               options.sort();
+               if (options.length == 0) {
+                       catList.append('<option value="">-- Select --</option>');
+               }
+               $.each(options, function(idx, itm) {
+                       catList.append('<option value="'+cats[itm]+'">'+itm+'</option>');
+               });
+
+        //  If only one option is available, default to have it selected.
+               var catListOptions = catList.children('option');
+        if (catListOptions.length == 2) {
+            $("select[name='category_id'] option:last")
+                               .attr('selected', 'selected');
+            //  need to repopulate the sub cats, b/c we already know what
+            //  the selected cat is.
+            Search.populateMemberSubType(false);
+        }
+
+        //  Figure out wich category we need to set as the selected value
+        var category_id = window.location.GET['category_id'];
+        if (!isNaN(parseInt(category_id))) {
+            if (!Search.catSelected) {
+                Search.catSelected = true;
+                $("select[name='category_id'] option[value='"+category_id+"']").attr('selected', 'selected');
+            }
+        }
+    },
+
+    //  }}}
+    //  {{{ populateMemberSubType()
+
+    /**
+     * repopulate the sub category box based on the the value
+     * selected in the main category box
+     *
+     * if no region was selected, then get all sub categories available
+     * under the main category selected
+     *
+     * if a region was selected, then get all sub categories available in that
+     * region under the main category selected.
+     */
+    populateMemberSubType: function(event)
+    {
+        //var region = $("select[name='region_id'] option:selected").val();
+        if ($("[name='region_id']").is("select")) {
+            var region = $("select[name='region_id'] option:selected").val();
+        } else {
+            var region = $("input[name='region_id']").val();
+        }
+        var cat  = $("select[name='category_id'] option:selected").val();
+               var subList = $("select[name='sub_category_id']");
+
+               // Clear sub-category list
+        subList.empty()
+               .append('<option value="">-- Select --</option>');
+
+        var usedValues = [];
+               var options = [];
+               var subCats = [];
+               
+               // If we have RegionCats data (json)
+       if (window.RegionCats != undefined) {
+
+               // If no region is selected
+               if (region == undefined || region == '') {
+                       // for each region
+                       $.each(RegionCats, function(id, obj) {
+                               // If that region has categories in RegionCats
+                               if (RegionCats[id]) {
+                                       // If this category has any sub-cats
+                                       if(RegionCats[id][cat]) {
+                                               // Add each of those categories
+                                                       $.each(RegionCats[id][cat], function(i, j) {
+                                                               if (!usedValues[i]) {
+                                                                       usedValues[i] = true;
+                                                                       subCats[j] = i;
+                                                                       options.push(j);
+                                                               } 
+                                                       });
+                                       }
+                               }
+                               });
+               // Otherwise do this for the selected region
+               } else {
+                               // For each sub-category in selected category in region
+                               $.each(RegionCats[region][cat], function(i, j) {
+                                       if (!usedValues[i]) {
+                                               usedValues[i] = true;
+                                               subCats[j] = i;
+                                               options.push(j);
+                                       }
+                               });
+               }
+               
+       }
+    
+    
+               options.sort();
+               if (options.length == 0) {
+                       subList.append('<option value="">-- Select --</option>');
+               }
+               $.each(options, function(idx, itm) {
+                       subList.append('<option value="'+subCats[itm]+'">'+itm+'</option>');
+               });
+
+        //  If only one option is available, default to have it selected.
+               var subListOptions = subList.children('option');
+        if (subListOptions.length == 2) {
+            $("select[name='sub_category_id'] option:last-child")
+                .attr('selected', 'selected');
+        }
+
+        //  Figure out which sub category we need to set as the selected value
+        var sub_category_id = window.location.GET['sub_category_id'];
+        if (parseInt(sub_category_id) != 'NaN') {
+            if (!Search.subCatSelected && event != false) {
+                Search.subCatSelected = true;
+                $("select[name='sub_category_id'] option[value='"+sub_category_id+"']").attr('selected', 'selected');
+            }
+        }
+    }
+
+    //  }}}
+};
+
+$(document).ready(Search.init);
diff --git a/Toolkit/Members/libjs/edit-amenity.js b/Toolkit/Members/libjs/edit-amenity.js
new file mode 100644 (file)
index 0000000..92b1e7c
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * When we are adding an amenity we want to focus on the first text field
+ * of the form.
+ */
+var MemberAmenity =
+{
+       init: function()
+       {
+               //      Find a member id in the search params, this will let us know we
+               //      are editing a member and then we don't want to focus on the
+               //      the first field.
+               var idRegExp = /.*(\?|&)id=\d+.*$/g;
+               if (!idRegExp.test(location.search)) {
+            $('form :input:text:visible:enabled:first').focus();
+               }
+        $("input[name='delete']").click(function(){
+            return confirm('This will delete the amenity and cannot be undone!\nAre you sure?');
+        });
+       }
+}
+
+$(document).ready(MemberAmenity.init);
diff --git a/Toolkit/Members/libjs/edit-category.js b/Toolkit/Members/libjs/edit-category.js
new file mode 100644 (file)
index 0000000..c88cc5a
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * When we are adding a category we want to focus on the first text field
+ * of the form.
+ */
+var MemberCategory =
+{
+       init: function()
+       {
+               //      Find a member id in the search params, this will let us know we
+               //      are editing a member and then we don't want to focus on the
+               //      the first field.
+               var idRegExp = /.*(\?|&)id=\d+.*$/g;
+               if (!idRegExp.test(location.search)) {
+            $('form :input:text:visible:enabled:first').focus();
+               }
+        $("input[name='delete']").click(function(){
+            return confirm('This will delete the category and cannot be undone!\nAre you sure?');
+        });
+       }
+}
+
+$(document).ready(MemberCategory.init);
diff --git a/Toolkit/Members/libjs/edit-city.js b/Toolkit/Members/libjs/edit-city.js
new file mode 100644 (file)
index 0000000..5a6b731
--- /dev/null
@@ -0,0 +1,33 @@
+/**
+ * When adding a city, set the focus to the first text field in the form
+ * after the page loads.
+ */
+var MemberCity =
+{
+       init: function()
+       {
+               //      Find a city id in the search params, this will let us know we
+               //      are editing a member and then we don't want to focus on the
+               //      the first field.
+               var idRegExp = /.*(\?|&)id=\d+.*$/g;
+               if (!idRegExp.test(location.search)) {
+                       $(":text:visible:enabled:first").focus();
+               }
+
+               if ($('#description').is('textarea')) {
+            //  Only try to replace the textarea if the
+            //  CKEditor is compatible w/ the browser.
+            if (CKEDITOR.env.isCompatible) {
+                CKEDITOR.replace('description',
+                    {
+                        toolbar : 'LimitedToolset'
+                    });
+            }
+               }
+        $("input[name='delete']").click(function(){
+            return confirm('This will delete the city and cannot be undone!\nAre you sure?');
+        });
+       }
+}
+
+$(document).ready(MemberCity.init);
diff --git a/Toolkit/Members/libjs/edit-county.js b/Toolkit/Members/libjs/edit-county.js
new file mode 100644 (file)
index 0000000..ac24c8d
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * When we are adding an region we want to focus on the first text field
+ * of the form.
+ */
+var MemberCounty =
+{
+       init: function()
+       {
+               //      Find a member id in the search params, this will let us know we
+               //      are editing a member and then we don't want to focus on the
+               //      the first field.
+               var idRegExp = /.*(\?|&)id=\d+.*$/g;
+               if (!idRegExp.test(location.search)) {
+            $('form :input:text:visible:enabled:first').focus();
+               }
+        $("input[name='delete']").click(function(){
+            return confirm('This will delete the county and cannot be undone!\nAre you sure?');
+        });
+       }
+}
+
+$(document).ready(MemberCounty.init);
diff --git a/Toolkit/Members/libjs/edit-html-email.js b/Toolkit/Members/libjs/edit-html-email.js
new file mode 100644 (file)
index 0000000..a5e784f
--- /dev/null
@@ -0,0 +1,36 @@
+/**
+ * When adding a html newsletter, set the focus to the first text field in the form
+ * after the page loads.
+ */
+var HtmlEmail =
+{
+       init: function()
+       {
+               //      Find a newsletter id in the search params, this will let us know we
+               //      are editing a newsletter and then we don't want to focus on the
+               //      the first field.
+               var idRegExp = /.*(\?|&)id=\d+.*$/g;
+               if (!idRegExp.test(location.search)) {
+                       $(":text:visible:enabled:first").focus();
+               }
+
+               if ($('#response').is('textarea')) {
+            //  Only try to replace the textarea if the 
+            //  CKEditor is compatible w/ the browser.
+            if (CKEDITOR.env.isCompatible) {
+                CKEDITOR.replace('response',
+                    {
+                        toolbar : 'Default',
+                        width : 600,
+                        height : 500,
+                        filebrowserImageBrowseUrl : '../Toolkit/CKImages/browser.php?folder=1',
+                        filebrowserImageUploadUrl : '../Toolkit/CKImages/controller.php?command=Upload',
+                                               filebrowserImageWindowWidth : '760',
+                                               filebrowserImageWindowHeight : '500'
+                    });
+            }
+               }
+       }
+}
+
+$(document).ready(HtmlEmail.init);
diff --git a/Toolkit/Members/libjs/edit-member-amenities.js b/Toolkit/Members/libjs/edit-member-amenities.js
new file mode 100644 (file)
index 0000000..f696ac5
--- /dev/null
@@ -0,0 +1,21 @@
+var MemberAmenity =
+{
+       init: function()
+       {
+               $('label').each(function() {
+            $(this).hover(MemberAmenity.highlight, MemberAmenity.lowlight);
+               });
+       },
+
+       highlight: function(event)
+       {
+               $(this).addClass('amenityOn');
+       },
+
+       lowlight: function(event)
+       {
+               $(this).removeClass('amenityOn');
+       }
+}
+
+$(document).ready(MemberAmenity.init);
diff --git a/Toolkit/Members/libjs/edit-member-contacts.js b/Toolkit/Members/libjs/edit-member-contacts.js
new file mode 100644 (file)
index 0000000..8e6399b
--- /dev/null
@@ -0,0 +1,39 @@
+var MemberContacts=
+{
+       init: function()
+       {
+               $('.remove').click(MemberContacts.remove);
+               
+               $('.contactList').each(function() {
+            $(this).hover(MemberContacts.mouseOn, MemberContacts.mouseOff);
+            $(this).click(MemberContacts.goToContact);
+               });
+       },
+
+       mouseOn: function(event)
+       {
+               $(this).addClass('contactListOn');
+       },
+
+       mouseOff: function(event)
+       {
+               $(this).removeClass('contactListOn');
+       },
+
+       goToContact: function(event)
+       {
+               document.location.href = $(this).find('h3 a').attr('href');
+               return false;
+       },
+
+       remove: function(event)
+       {
+               if (!confirm('Are you sure you wish to remove this contact?\nThis is not reversible!')) {
+            event.preventDefault();
+               }
+        //  Don't propagate so we won't go into the member record
+        event.stopImmediatePropagation();
+       }
+}
+
+$(document).ready(MemberContacts.init);
diff --git a/Toolkit/Members/libjs/edit-member-files.js b/Toolkit/Members/libjs/edit-member-files.js
new file mode 100644 (file)
index 0000000..87086e5
--- /dev/null
@@ -0,0 +1,18 @@
+var MemberFiles =
+{
+       init: function()
+       {
+               $('.fileDelete').each(function() {
+            $(this).click(MemberFiles.remove);
+               });
+       },
+
+       remove: function(event)
+       {
+               if (!confirm('Are you sure you wish to remove this file?\nThis is not reversible!')) {
+            event.preventDefault();
+               }
+       }
+}
+
+$(document).ready(MemberFiles.init);
diff --git a/Toolkit/Members/libjs/edit-member-packages.js b/Toolkit/Members/libjs/edit-member-packages.js
new file mode 100755 (executable)
index 0000000..9b3a9ef
--- /dev/null
@@ -0,0 +1,20 @@
+var MemberPackages =
+{
+       init: function()
+       {
+        if (CKEDITOR.env.isCompatible) {
+            $("textarea.ckeditor").each(function() {
+                CKEDITOR.replace(
+                    $(this).attr('id'),
+                    {
+                        toolbar : 'LimitedToolset',
+                        width : 300,
+                        height : 200
+                    }
+                );
+            });
+        }
+       }
+}
+
+$(document).ready(MemberPackages.init);
diff --git a/Toolkit/Members/libjs/edit-member-photos.js b/Toolkit/Members/libjs/edit-member-photos.js
new file mode 100755 (executable)
index 0000000..ae73b11
--- /dev/null
@@ -0,0 +1,58 @@
+var MemberPhotos =
+{
+       init: function()
+       {
+               $('.photoDelete').click(MemberPhotos.remove);
+
+               //      Make just the photos uploaded have an additional class
+               //      on them, so we can make them movable later.
+               $(".photoItem:not(.photoUploadForm)").addClass('movable');
+
+               //      Update the text on the update button.
+               //      Since they have javascript on, the only update
+               //      they will actually do on the form is the caption.
+               //      They won't be updating the position through the select list.
+               $(":submit[name='update']").val('Update Caption Text');
+
+               //      Remove all the positioning select elemnts
+               //      so they can't override any new position adjustments
+               //      done through drag and drop.
+               $('.position').remove();
+
+               //      Add a message for users to tell them how to 
+               //      reposition thier images.
+               $('#photoList').before('<div id="pos-info">Click and drag images to reorder positions. Image positions are saved when the fields flash yellow</div>');
+
+               $('div.container').sortable({
+                       placeholder: 'ui-state-highlight',
+                       handle: 'img.thumb',
+                       opacity: 0.6,
+                       revert: true,
+                       scroll: true,
+                       tolerance: 'pointer',
+                       zIndex: 5,
+                       axis: 'y',
+                       cursor: 'n-resize',
+                       update: MemberPhotos.updatePos
+               });
+               $('img.thumb').disableSelection();
+       },
+
+       updatePos: function(event, ui)
+       {
+               var url = '../member-save-photos/?' + $(this).sortable('serialize');
+               //      Update the photo positions through AJAX.
+               $.get(url, function(data) {
+                       $('.movable').effect('highlight', {}, 700);
+               });
+       },
+
+       remove: function(event)
+       {
+               if (!confirm('Are you sure you wish to remove this photo?\nThis is not reversible!')) {
+                       event.preventDefault();
+               }
+       }
+};
+
+$(document).ready(MemberPhotos.init);
diff --git a/Toolkit/Members/libjs/edit-member.js b/Toolkit/Members/libjs/edit-member.js
new file mode 100755 (executable)
index 0000000..9ef4468
--- /dev/null
@@ -0,0 +1,111 @@
+var Member =
+{
+       categorySelectList: null,
+
+       init: function()
+       {
+               //      Find a member id in the search params, this will let us know we
+               //      are editing a member and then we don't want to focus on the
+               //      the first field.
+               var idRegExp = /.*(\?|&)id=\d+.*$/g;
+               if (!idRegExp.test(location.search)) {
+                       $('form :input:text:visible:enabled:first').focus();
+               }
+
+//             var meals = ['breakfast', 'brunch', 'lunch', 'dinner'];
+//             jQuery.each(meals, function(i, j) {
+//                     $('#edit_member input[name='+j+']:checkbox').click(Member.toggleMealView);
+//                     $('#edit_member input[name='+j+']:checkbox:not(:checked)').parents('tr').next().toggle().next().toggle();
+//             });
+
+        $('.tooltip').cluetip({
+            //  character to split title text from body text
+            splitTitle: '|',
+            //  show arrow on cluetip
+            arrows: true,
+            //  hide cluetip on mouseout
+            mouseOutClose: true,
+            //  track mouse movements
+            tracking: true,
+            //  keep z index above all other elements on the page
+            cluezIndex: 10000,
+            //  effect to open cluetip with
+            fx: {open: 'fadeIn'}
+        });
+
+               if (Member.categorySelectList = $('#categories')) {
+                       Member.categorySelectList.after('<input type="button" id="addCat" value="Add">');
+                       $('#addCat').click(Member.addCategory);
+               }
+
+               if ($('#description').is('textarea')) {
+            //  Only try to replace the textarea if the
+            //  CKEditor is compatible w/ the browser.
+            if (CKEDITOR.env.isCompatible) {
+                CKEDITOR.replace('description',
+                    {
+                        toolbar : 'LimitedToolset'
+                    });
+            }
+               }
+        $("#edit_member").submit(function(){
+            var member_cats = Member.requireMemberCategory();
+            //alert(member_cats);
+            if (member_cats == 0) {
+                alert('You must supply at least one Member Category!');
+                return false;
+            } else {
+                return true;
+            }
+        });
+       },
+
+       addCategory: function(event)
+       {
+               //      Don't allow insertion of the -- Choose Category -- option.
+               if (Member.categorySelectList.get(0).selectedIndex == 0) {
+                       return;
+               }
+               var catid = Member.categorySelectList.get(0).value;
+               $('#edit_member').append('<input type="hidden" id="'+catid +'catid" value="'+catid+'" name="member_cats[]">');
+
+               var index = Member.categorySelectList.get(0).selectedIndex;
+               var category = Member.categorySelectList.get(0).options[index].innerHTML;
+               var d = new Date();
+               var id = d.getTime()
+               var i = '<i><label class="remove" for="' + id + '"><input type="checkbox" ' +
+                               'value="' + catid + '" id="' + id + '" name="removeCat[]">Remove</label>' +
+                               category + '</i>';
+               $('#addCategory').after(i);
+               Member.categorySelectList.get(0).selectedIndex = 0;
+       },
+
+       removeCategory: function(event)
+       {
+               event.stop();
+               $('catid' + this.readAttribute('rel')).remove();
+               this.up().remove();
+       },
+
+       toggleMealView: function(event)
+       {
+               $(this).parents('tr').next().toggle().next().toggle();
+       },
+
+    requireMemberCategory: function(event)
+    {
+        var count = 0;
+        $('input[name="member_cats[]"][type="hidden"]').each(function(){
+            var val = $(this).val();
+            var val2 = $('input:checkbox[name="removeCat[]"]:checked[id="'+val+'"]').val();
+            if (val2 != undefined) {
+                //alert('removed!!!' + val2);
+            } else {
+                ++count;
+            }
+        });
+        return count;
+    }
+};
+
+$(document).ready(Member.init);
diff --git a/Toolkit/Members/libjs/edit-region.js b/Toolkit/Members/libjs/edit-region.js
new file mode 100644 (file)
index 0000000..7ffa54a
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * When we are adding an region we want to focus on the first text field
+ * of the form.
+ */
+var MemberRegion =
+{
+       init: function()
+       {
+               //      Find a member id in the search params, this will let us know we
+               //      are editing a member and then we don't want to focus on the
+               //      the first field.
+               var idRegExp = /.*(\?|&)id=\d+.*$/g;
+               if (!idRegExp.test(location.search)) {
+            $('form :input:text:visible:enabled:first').focus();
+               }
+        $("input[name='delete']").click(function(){
+            return confirm('This will delete the region and cannot be undone!\nAre you sure?');
+        });
+       }
+}
+
+$(document).ready(MemberRegion.init);
diff --git a/Toolkit/Members/libjs/google-map.js b/Toolkit/Members/libjs/google-map.js
new file mode 100644 (file)
index 0000000..064aa3a
--- /dev/null
@@ -0,0 +1,139 @@
+var Map = {
+       _map: null,
+       _latLngBounds: null,
+       _infoWindow: null,
+    arrMarkers: [],
+
+       init: function()
+       {
+               var canvas = document.getElementById('map-canvas');
+               var myOptions = {
+                       zoom: 13,
+                       mapTypeControl: true,
+                       mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
+                       navigationControl: true,
+                       navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
+                       mapTypeId: google.maps.MapTypeId.ROADMAP
+               }
+
+               Map._map = new google.maps.Map(canvas, myOptions);
+               Map._latLngBounds = new google.maps.LatLngBounds();
+               Map._infoWindow = new google.maps.InfoWindow;
+
+               $.get("member-db-google-map/"+location.search, Map._loadData, 'xml');
+       },
+
+       _loadData: function(data)
+       {
+               var markers = data.documentElement.getElementsByTagName("marker");
+               for (i = 0; i < markers.length; i++) {
+                       var name = markers[i].getAttribute('member_name');
+                       var street = markers[i].getAttribute('street');
+                       var city = markers[i].getAttribute('city_name');
+                       var state = markers[i].getAttribute('state_abb');
+                       var zip = markers[i].getAttribute('zip');
+                       var lat = markers[i].getAttribute('lat');
+                       var lng = markers[i].getAttribute('lng');
+                       var phone = markers[i].getAttribute('phone');
+                       var clickThru = markers[i].getAttribute('url');
+                       var website = markers[i].getAttribute('website');
+                       var logoPath = markers[i].getAttribute('logoPath');
+                       var logo = markers[i].getAttribute('logo');
+                       var logoWidth = markers[i].getAttribute('logoWidth');
+                       var logoHeight = markers[i].getAttribute('logoHeight');
+                       var hasTripPlanner = markers[i].getAttribute('hasTripPlanner');
+                       var addToPlannerUrl = markers[i].getAttribute('addToPlannerUrl');
+                       var viewPlannerUrl = markers[i].getAttribute('viewPlannerUrl');
+                       var plannerText = markers[i].getAttribute('plannerText');
+                       var moreInfoUrl = markers[i].getAttribute('moreInfoUrl');
+            var iconUrl = markers[i].getAttribute('iconUrl');
+            var zIndex = markers[i].getAttribute('zIndex');
+
+                       var point = new google.maps.LatLng(
+                               parseFloat(lat),
+                               parseFloat(lng)
+                       );
+                       Map._latLngBounds.extend(point);
+
+                       var html = '<table><tbody><tr>';
+                       html += '<td><b>' + name + '</b><br>' +
+                                               street + '<br>' + city + ', ' + state + ' ' + zip;
+
+                       if (phone != '') {
+                               html += '<br>' + phone;
+                       }
+                       if (website != '') {
+                               html += '<br>' + '<a target="_blank" href="'+clickThru+'">'+website+'</a>';
+                       }
+
+                       html += '</td>';
+                       html += '</tr></tbody></table>';
+
+                       html += '<span class="infoWindow moreInfo"><a href="'+moreInfoUrl+'">More Info</a></span>';
+                       html += '<span class="infoWindow divider"> - </span>';
+                       if (addToPlannerUrl != '' && hasTripPlanner) {
+                               html += '<span class="infoWindow addToPlanner">' +
+                                                       '<a href="'+addToPlannerUrl+'">'+plannerText+'</a>' +
+                                                       '<a style="display: none;" href="'+viewPlannerUrl+'">View Planner</a>' +
+                                               '</span>';
+                               html += '<span class="infoWindow divider"> - </span>';
+                       }
+
+                       html += '<span class="infoWindow directions"><a target="_blank" href="http://maps.google.com/maps?daddr='+name+'@'+lat+','+lng+'">Get Directions</a></span>';
+            if (iconUrl && typeof(glm_catid) != 'undefined') {
+                var marker = new google.maps.Marker({
+                    title: name,
+                    map: Map._map,
+                    position: point,
+                    icon: iconUrl,
+                    zIndex: -zIndex
+                });
+            } else {
+                var marker = new google.maps.Marker({
+                    title: name,
+                    map: Map._map,
+                    position: point
+                });
+            }
+            Map.arrMarkers.push(marker);
+                       Map._bindInfoWindow(marker, Map._map, Map._infoWindow, html);
+               }
+
+               Map._map.setCenter(
+                       Map._latLngBounds.getCenter()
+               );
+               Map._map.fitBounds(Map._latLngBounds);
+
+        if (glm_searchMapIconActive) {
+            $(".map-link").click(function (){
+                var linkId = $(this).attr("rel");
+                google.maps.event.trigger(Map.arrMarkers[linkId], "click");
+                myAnchor = '#map-canvas';
+                window.location = String(window.location).replace(/\#.*$/, "") + myAnchor;
+                Map._map.setZoom(14);
+            });
+        }
+       },
+
+       _bindInfoWindow: function(marker, map, infoWindow, html)
+       {
+               google.maps.event.addListener(marker, 'click', function() {
+                       infoWindow.setContent(html);
+                       infoWindow.open(map, marker);
+
+                       $('.addToPlanner a:first').click(function(event) {
+                               if ($(this).text() == 'Add To Planner') {
+                                       event.preventDefault();
+
+                                       $.get($(this).attr('href'), function(data, textstatus) {
+                                               $(".trip-list-count").html(data);
+                                               $('.addToPlanner a').toggle();
+                                       });
+                                       return false;
+                               }
+                       });
+               });
+       }
+};
+
+$(document).ready(Map.init);
diff --git a/Toolkit/Members/libjs/list-categories.js b/Toolkit/Members/libjs/list-categories.js
new file mode 100644 (file)
index 0000000..97e3bb8
--- /dev/null
@@ -0,0 +1,50 @@
+var Tree =
+{
+       init: function()
+       {
+               Tree.insertGlobalFunctions();
+
+               tree1 = new tree_component();
+               tree1.init($("#categoryTree"), {
+                       cookies : {
+                               prefix : "tree1",
+                               opts : { path : '/' }
+                       },
+                       ui : {
+                               animation : 500
+                       }
+               });
+
+               $('#categoryTree a').bind('click', Tree.editNode);
+       },
+
+       insertGlobalFunctions: function()
+       {
+               $('#categoryTree').before('<div class="treeOperators">' +
+                       '<button class="expandAll">Expand All</button>' +
+                       '<button class="collapseAll">Collapse All</button>' +
+                       '</div>');
+
+               $('.expandAll').bind('click', Tree.expandAll);
+               $('.collapseAll').bind('click', Tree.collapseAll);
+       },
+
+       expandAll: function(event)
+       {
+               $('li.closed').toggleClass('open');
+               $('li.closed').toggleClass('closed');
+       },
+
+       collapseAll: function (event)
+       {
+               $('li.open').toggleClass('closed');
+               $('li.open').toggleClass('open');
+       },
+
+       editNode: function(event)
+       {
+               location.href = $(this).attr('href');
+       }
+};
+
+$(document).ready(Tree.init);
diff --git a/Toolkit/Members/libjs/member-list.js b/Toolkit/Members/libjs/member-list.js
new file mode 100644 (file)
index 0000000..bd9b8ec
--- /dev/null
@@ -0,0 +1,63 @@
+var MemberList =
+{
+       baseUrl: null,
+
+       init: function()
+       {
+               $('.searchResult').each(function() {
+                       $(this).hover(MemberList.mouseOn, MemberList.mouseOff);
+                       $(this).click(MemberList.goToMember);
+               });
+
+               $('.remove').each(function() {
+                       $(this).click(MemberList.remove);
+               });
+
+               if (   $('#advanced-record-search').is('form')
+                       && $('.searchResult').length > 0
+               ) {
+                       $('#advanced-record-search')
+                               .hide()
+                               .after('<div id="advanced-search-refine">Refine your search</div>');
+
+                       $('#advanced-search-refine').click(MemberList.toggleAdvancedSearch);
+               }
+       },
+
+       toggleAdvancedSearch: function(event)
+       {
+               if ($(this).text() == 'Refine your search') {
+                       $(this).text('Click here to hide');
+               } else {
+                       $(this).text('Refine your search');
+               }
+               $('#advanced-record-search').slideToggle('slow');
+       },
+
+       mouseOn: function(event)
+       {
+               $(this).addClass('searchResultOn');
+       },
+
+       mouseOff: function(event)
+       {
+               $(this).removeClass('searchResultOn');
+       },
+
+       goToMember: function(event)
+       {
+               document.location.href = $(this).find('h3 a').attr('href');
+               return false;
+       },
+
+       remove: function(event)
+       {
+               if (!confirm('Are you sure you wish to remove this business?\nThis is not reversible!')) {
+            event.preventDefault();
+        }
+        //  Don't propagate so we won't go into the member record
+        event.stopImmediatePropagation();
+       }
+};
+
+$(document).ready(MemberList.init);
diff --git a/Toolkit/Members/libjs/member-pending-list.js b/Toolkit/Members/libjs/member-pending-list.js
new file mode 100644 (file)
index 0000000..204260a
--- /dev/null
@@ -0,0 +1,28 @@
+var MemberPendingList =
+{
+    init: function()
+    {
+               $('.searchResult').each(function() {
+                       $(this).hover(MemberPendingList.mouseOn, MemberPendingList.mouseOff);
+                       $(this).click(MemberPendingList.goToMember);
+               });
+    },
+
+       mouseOn: function(event)
+       {
+               $(this).addClass('searchResultOn');
+       },
+
+       mouseOff: function(event)
+       {
+               $(this).removeClass('searchResultOn');
+       },
+
+       goToMember: function(event)
+       {
+               document.location.href = $(this).find('h3 a').attr('href');
+               return false;
+       }
+}
+
+$(document).ready(MemberPendingList.init);
diff --git a/Toolkit/Members/libjs/new-member-sign-up.js b/Toolkit/Members/libjs/new-member-sign-up.js
new file mode 100755 (executable)
index 0000000..f8d4a96
--- /dev/null
@@ -0,0 +1,10 @@
+var NewMember= 
+{
+       init: function()
+       {
+        $('#charcount').html('<span>1000</span>');
+        $('textarea').textlimit('#charcount span', 1000);
+       }
+};
+
+$(document).ready(NewMember.init);
diff --git a/Toolkit/Members/libjs/travel-list.js b/Toolkit/Members/libjs/travel-list.js
new file mode 100644 (file)
index 0000000..98e50d8
--- /dev/null
@@ -0,0 +1,40 @@
+var TravelList =
+{
+    //  {{{ init()
+    
+       init: function()
+       {
+         $("#glmLoad").bind("ajaxSend", function(){
+            $(this).show();
+         }).bind("ajaxComplete", function(){
+             $(this).hide();
+         });
+        $(".list-add-link").click(function(){
+            var member_id = $(this).attr('rel');
+            TravelList.addToList(member_id);
+            return false;
+        });
+       },
+
+    //  }}}
+    // {{{ addToList()
+    addToList: function (member_id){
+        $.ajax({
+            type: "GET",
+            url: glm_base_url + "trip-planner-list/" + member_id + "/" + glm_catid + "/",
+            success: function(msg) {
+                var viewLink = '<a href="' + glm_base_url + 'index.php?catid=' + glm_trip_planner_id + '" class="list-view-link" rel="'+member_id+'">';
+                viewLink += '<img title="View" src="' + glm_base_url + 'assets/viewTravelPlanner.gif" />';
+                viewLink += '</a>';
+                $("#add-"+member_id).replaceWith(viewLink);
+                TravelList.updateList(msg);
+            }
+        });
+    },
+    updateList: function (listCount){
+        $(".trip-list-count").html(listCount);
+    }
+    // }}}
+};
+
+$(document).ready(TravelList.init);
diff --git a/Toolkit/Members/libjs/trip-planner-map.js b/Toolkit/Members/libjs/trip-planner-map.js
new file mode 100644 (file)
index 0000000..8ad68c3
--- /dev/null
@@ -0,0 +1,105 @@
+var TPM = {
+       _map: null,
+       _latLngBounds: null,
+       _infoWindow: null,
+
+       init: function()
+       {
+               var canvas = document.getElementById('map-canvas');
+               var myOptions = {
+                       zoom: 10,
+                       center: new google.maps.LatLng(45.374893, -84.958404),
+                       mapTypeId: google.maps.MapTypeId.ROADMAP
+               }
+
+               TPM._map = new google.maps.Map(canvas, myOptions);
+               TPM._latLngBounds = new google.maps.LatLngBounds();
+               TPM._infoWindow = new google.maps.InfoWindow;
+
+               $.get('../../../trip-planner-members/', TPM._loadData, 'xml');
+       },
+
+       _loadData: function(data)
+       {
+               var markers = data.documentElement.getElementsByTagName('marker');
+               for (i = 0; i < markers.length; i++) {
+                       var name = markers[i].getAttribute('member_name');
+                       var url_name = markers[i].getAttribute('url_member_name');
+                       var street = markers[i].getAttribute('street');
+                       var city = markers[i].getAttribute('city_name');
+                       var state = markers[i].getAttribute('state_abb');
+                       var zip = markers[i].getAttribute('zip');
+                       var lat = markers[i].getAttribute('lat');
+                       var lng = markers[i].getAttribute('lng');
+                       var phone = markers[i].getAttribute('phone');
+                       var clickThru = markers[i].getAttribute('url');
+                       var website = markers[i].getAttribute('website');
+                       var logoPath = markers[i].getAttribute('logoPath');
+                       var logo = markers[i].getAttribute('logo');
+                       var logoWidth = markers[i].getAttribute('logoWidth');
+                       var logoHeight = markers[i].getAttribute('logoHeight');
+                       var moreInfoUrl = markers[i].getAttribute('moreInfoUrl');
+
+                       var point = new google.maps.LatLng(
+                               parseFloat(lat),
+                               parseFloat(lng)
+                       );
+                       TPM._latLngBounds.extend(point);
+
+                       var html = '<table><tbody><tr>';
+                       html += '<td><b>' + name + '</b><br>' +
+                                               street + '<br>' + city + ', ' + state + ' ' + zip;
+
+                       if (phone != '') {
+                               html += '<br>' + phone;
+                       }
+                       if (website != '') {
+                               html += '<br>' + '<a target="_blank" href="'+clickThru+'">'+website+'</a>';
+                       }
+
+                       html += '</td>';
+
+/*
+Commented out b/c the image server will take to long
+to generate the image dimensions for many members.
+
+this causes the page load to slow down to much
+if you uncomment this be sure to uncomment the command
+to get the image dimensions in /member-db-google-map/
+                       if (logo != '') {
+                               var img = '<img src="'+logoPath+logo+'" width="'+logoWidth+'" height="'+logoHeight+'">';
+                               html += '<td>'+img+'</td>';
+                       }
+*/
+                       html += '</tr></tbody></table>';
+                       
+//                     html += '<span class="infoWindow moreInfo"><a target="_parent" href="'+moreInfoUrl+'">More Info</a></span>';
+//                     html += '<span class="infoWindow divider"> - </span>';
+                       
+                       html += '<a target="_blank" href="http://maps.google.com/maps?daddr='+url_name+'@'+lat+','+lng+'">Get Directions</a>';
+                       var marker = new google.maps.Marker({
+                               map: TPM._map,
+                               position: point,
+                               title: name
+                       });
+
+                       TPM._bindInfoWindow(marker, TPM._map, TPM._infoWindow, html);
+               }
+
+               TPM._map.setCenter(
+                       TPM._latLngBounds.getCenter()
+               );
+
+               TPM._map.fitBounds(TPM._latLngBounds);
+       },
+
+       _bindInfoWindow: function(marker, map, infoWindow, html)
+       {
+               google.maps.event.addListener(marker, 'click', function() {
+                       infoWindow.setContent(html);
+                       infoWindow.open(map, marker);
+               });
+       }
+};
+
+$(document).ready(TPM.init);
diff --git a/Toolkit/Members/memberClickThru.php b/Toolkit/Members/memberClickThru.php
new file mode 100644 (file)
index 0000000..dfabd8d
--- /dev/null
@@ -0,0 +1,30 @@
+<?php
+
+/**
+ * tracks clicks for url links from members
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: memberClickThru.php,v 1.5 2010/05/15 16:36:12 jamie Exp $
+ * @link      <>
+ */
+
+$includeFunctions = false;
+/**
+ * Description for require_once
+ */
+require_once '../../setup.phtml';
+$memberId = filter_input(INPUT_GET, 'member_id', FILTER_VALIDATE_INT);
+if ($memberId) {
+    $exposure = new Toolkit_Members_Exposure($memberId, 'click');
+       $exposure->runUpdate();
+}
+if ($_GET['href']) {
+    $href = str_replace("http://", "", $_GET['href']);
+    header("Location: http://" . $href);
+}
\ No newline at end of file
diff --git a/Toolkit/Members/memberDBGoogleAreaMap.php b/Toolkit/Members/memberDBGoogleAreaMap.php
new file mode 100644 (file)
index 0000000..97d80ba
--- /dev/null
@@ -0,0 +1,256 @@
+<?php
+/**
+ * memberDBGoogleAreaMap.phgp
+ * 
+ * PHP Version 5.2
+ * 
+ * @category  Toolkit
+ * @package   Members
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: $id$
+ * @link      <>
+ */
+header("Content-type: text/xml");
+require_once '../../setup.phtml';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$dbh = Toolkit_Database::getInstance();
+
+$conf = new Config;
+$root =& $conf->parseConfig(
+       BASE . 'Toolkit/Members/config.ini',
+       'IniFile'
+);
+$radius =& $root
+    ->getItem('section', 'map')
+    ->getItem('directive', 'radius')
+    ->getContent();
+$memberCategories =& $root
+    ->getItem('section', 'map')
+    ->getItem('directive', 'category')
+    ->getContent();
+$latBounds =& $root
+    ->getItem('section', 'map')
+    ->getItem('directive', 'latBounds')
+    ->getContent();
+$lonBounds =& $root
+    ->getItem('section', 'map')
+    ->getItem('directive', 'lonBounds')
+    ->getContent();
+// setup category/subcategory array
+$sql = "
+SELECT category_id
+  FROM category
+ WHERE category_id IN (
+       SELECT category_id
+         FROM member_category
+        WHERE member_id = :member_id)
+   AND category_id IN (".implode(',', $memberCategories).")
+ ORDER BY parent_id,name";
+$getMemberCats = $dbh->prepare($sql);
+$catSubCatArray = array();
+$hexColorArray = array(
+    14 => 'E52222', // Adventure Sports
+    13 => 'FFFF7A', // Arts & Culture
+    6 => '258E25', // Culinary Travel
+    7 => '2C2CE0', // Family Fun
+    8 => '932493', // Girlfriend Getaways
+    9 => 'ED8115', // History
+    9 => '8E3B3B', // Mancations
+    10 => 'ffffff', // NightLife
+    11 => 'eeeeee', // Outdoor Recreation
+    12 => 'cccccc', // Pet Friendly
+    1 => 'dddddd', // Places to Stay
+    40 => 'bbbbbb' // Travel Services
+);
+$sql = "
+SELECT category_id,name
+  FROM category
+ ORDER BY category_id";
+$catStmt = $dbh->query($sql);
+while ($catRow = $catStmt->fetch()) {
+    $sql = "
+    SELECT category_id,name
+      FROM category
+     WHERE parent_id = :parent";
+    $subCatStmt = $dbh->prepare($sql);
+    $subCatStmt->bindParam(':parent', $catRow['category_id']);
+    $subCatStmt->execute();
+    while ($subCatRow = $subCatStmt->fetch()) {
+        $catSubCatArray[$subCatRow['category_id']] = $catRow['category_id'];
+    }
+}
+$is = new Toolkit_Image_Server();
+
+$params = array();
+$xmlEncoder  = new Toolkit_Members_MapArea();
+//$searchList  = new Toolkit_Members_SearchList($dbh, null, null, null, false);
+if (is_numeric($_GET['city_id'])) {
+    try {
+        $sql = "
+            SELECT lat, lon
+              FROM city
+             WHERE city_id = :cid";
+        $stmt = $dbh->prepare($sql);
+        $stmt->bindParam(':cid', $_GET['city_id'], PDO::PARAM_INT);
+        $stmt->execute();
+        $row = $stmt->fetch(PDO::FETCH_ASSOC);
+    } catch (PDOException $e) {
+        return Toolkit_Common::handleError($e);
+    }
+    list($lat, $lng) = array_values($row);
+    $distanceQuery = null;
+    try {
+        $foo = "
+            (pow(sin(((m.lat * pi()/180.0) - ($lat * pi()/180.0)) / 2.0),
+            2) + cos(($lat * pi() / 180.0)) * cos((m.lat * pi() / 180.0)) *
+            pow(sin(((m.lon * pi() / 180.0) - ($lng * pi() / 180.0)) / 2.0), 2))";
+
+        $distanceQuery = "ceil(3956 * 2 * atan2(sqrt($foo), sqrt(1 - ($foo))))";
+    } catch (PDOException $e) {
+        return Toolkit_Common::handleError($e);
+    }
+    $latDist = ($radius * .87) / 60;
+    $lngFactor = cos($lat * (2 * pi() / 360));
+    $lngDist = (($radius / $lngFactor) * .87) / 60;
+    $latMin = round($lat - $latDist, 6);
+    $latMax = round($lat + $latDist, 6);
+    $lngMin = round($lng - $lngDist, 6);
+    $lngMax = round($lng + $lngDist, 6);
+    $params[] = "$distanceQuery < {$radius}";
+    $distanceQuery .= ' AS distance,';
+} else {
+    $distanceQuery = null;
+}
+if (is_numeric($_GET['region'])) {
+    $params[] = "m.city_id IN (
+        SELECT city_id
+          FROM city
+         WHERE region_id = {$_GET['region']})";
+    $params[] = "m.region = {$_GET['region']}";
+}
+// we need to determine if the page has a search form on it
+// and if the search form has been submitted
+$sql = "
+SELECT m.*,$distanceQuery c.city_name, s.state_name AS state,
+       s.state_abb AS state_abbr, ma.reservation_id,
+       ma.num_rooms, ma.year_round
+  FROM member m NATURAL FULL JOIN member_accommodations ma
+       FULL JOIN state s USING (state_id) FULL JOIN city c USING (city_id)";
+
+$params[] = 'new_member != true';
+$params[] = 'active = true';
+if (!empty($params)) {
+    $sql .= "WHERE " . implode(" AND ", $params);
+}
+if (   empty($_GET['category'])
+    && !$_GET['city_id']
+    && !$_GET['region']) {
+    return false;
+} else if ($_GET['category']) {
+    $sqlCats = array();
+    $sql .= " AND m.member_id IN
+            (SELECT member_id
+               FROM member_category
+              WHERE category_id IN
+                (".implode(",",$_GET['category']).")
+                   )";
+
+}
+// add restriction for lat lon
+$sql .= " AND m.lat BETWEEN {$latBounds} AND m.lon BETWEEN {$lonBounds}";
+// need to add sort
+$sql .= " ORDER BY m.member_name ASC";
+try {
+       $members = array();
+    $url = BASE_URL . "trip-planner-list/%d/%d/";
+       $urlFormat
+               = BASE_URL . 'Toolkit/Members/memberClickThru.php?member_id=%s&href=%s';
+       $addToPlannerFormat
+               = $url;
+       $viewPlannerFormat
+               = BASE_URL . 'index.php?catid=%s';
+       $moreInfoFormat
+               = BASE_URL . 'member-profile/%s/%s/';
+    $count = 1;
+    $totalCatCounter = array();
+       foreach ($dbh->query($sql, PDO::FETCH_ASSOC) as $row) {
+               if (!is_null($row['lat']) && !is_null($row['lon'])) {
+                       $websiteUrl = sprintf(
+                               $urlFormat,
+                               $row['member_id'],
+                               urlencode(str_replace('http://', '', $row['url']))
+                       );
+                       $viewPlannerUrl = sprintf(
+                               $viewPlannerFormat,
+                               MEMBER_SESSION_PAGE
+                       );
+                       if ($_SESSION['wish_list'][$row['member_id']]) {
+                               $plannerText = 'View Planner';
+                $addToPlannerUrl = sprintf(
+                                       $viewPlannerFormat,
+                                       MEMBER_SESSION_PAGE
+                               );
+                       } else {
+                               $plannerText = 'Add To Planner';
+                               $addToPlannerUrl = sprintf(
+                    $addToPlannerFormat,
+                    $row['member_id'],
+                    MEMBER_MAP_PAGE
+                               );
+                       }
+                       $moreInfoUrl = sprintf(
+                               $moreInfoFormat,
+                               $_GET['catid'],
+                               $row['member_id']
+                       );
+            $searchResultNumbered =& $root
+                ->getItem('section', 'conf')
+                ->getItem('directive', 'searchResultNumbered')
+                ->getContent();
+
+            $totalCatCounter[] = $totalCats;
+            $iconUrl = BASE_URL . "areamap/62BBE8.png";
+            $moreInfoUrl
+                = (true)
+                ? sprintf(
+                        $moreInfoFormat,
+                        MEMBERS_GOOGLE_MAP_PAGE,
+                        $row['member_id']
+                    )
+                : '';
+                       $members[] = array(
+                               'member_id'       => $row['member_id'],
+                               'member_name'     => $row['member_name'],
+                               'lat'             => $row['lat'],
+                               'lng'             => $row['lon'],
+                               'street'          => $row['street'],
+                               'state_abb'       => $row['state_abbr'],
+                               'city_name'       => $row['city_name'],
+                               'zip'             => $row['zip'],
+                               'phone'           => $row['phone'],
+                               'url'             => $websiteUrl,
+                               'website'         => $row['url'],
+                               'logoPath'        => MEMBER_GOOGLE_MAP,
+                               'logo'            => $row['logo'],
+                               'logoWidth'       => $imgWidth,
+                               'logoHeight'      => $imgHeight,
+                               'hasTripPlanner'  => MEMBER_SESSION_LIST,
+                               'addToPlannerUrl' => $addToPlannerUrl,
+                               'viewPlannerUrl'  => $viewPlannerUrl,
+                               'plannerText'     => $plannerText,
+                               'moreInfoUrl'     => $moreInfoUrl,
+                'iconUrl'         => $iconUrl,
+                'zIndex'         => $count,
+                       );
+               }
+        ++$count;
+       }
+} catch (PDOException $e) {
+       Toolkit_Common::handleError($e);
+}
+echo $xmlEncoder->getMemberXML($members);
diff --git a/Toolkit/Members/memberDBGoogleMap.php b/Toolkit/Members/memberDBGoogleMap.php
new file mode 100644 (file)
index 0000000..217b9e2
--- /dev/null
@@ -0,0 +1,133 @@
+<?php
+/**
+ * memberDBGoogleMap.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   Members
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id$
+ * @link      <>
+ */
+
+header("Content-type: text/xml");
+require_once '../../setup.phtml';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$dbh = Toolkit_Database::getInstance();
+
+if (   defined("SHORT_URLS")
+       && SHORT_URLS
+       && isset($_GET['glmPage'])
+       && $_GET['glmPage']
+) {
+    $shortURL = new Toolkit_ShortURL(
+               Toolkit_Database::getInstance()
+       );
+    if (!$catid = $shortURL->getShortUrlId($_GET['glmPage'])) {
+        $catid = HOME_ID;
+    }
+    $_GET['catid'] = $catid;
+}
+
+$is = new Toolkit_Image_Server();
+$conf = new Config;
+$root =& $conf->parseConfig(
+       BASE . 'Toolkit/Members/config.ini',
+       'IniFile'
+);
+
+$xmlEncoder  = new Toolkit_Members_Map();
+$searchQuery = new Toolkit_Members_SearchQueryGenerator(true, $root);
+
+$sql = $searchQuery->getQuery($dbh);
+
+// need to add sort
+$sql .= " ORDER BY m.member_name ASC";
+
+try {
+       $members = array();
+       $urlFormat
+               = BASE_URL . 'Toolkit/Members/memberClickThru.php?member_id=%s&href=%s';
+       $addToPlannerFormat
+               = BASE_URL . 'trip-planner-wish-list/%s/%s/';
+       $viewPlannerFormat
+               = BASE_URL . 'index.php?catid=%s';
+       $moreInfoFormat
+               = BASE_URL . 'member-profile/%s/%s/';
+    $count = 1;
+       foreach ($dbh->query($sql, PDO::FETCH_ASSOC) as $row) {
+               if (!is_null($row['lat']) && !is_null($row['lon'])) {
+                       $websiteUrl = sprintf(
+                               $urlFormat,
+                               $row['member_id'],
+                               urlencode(str_replace('http://', '', $row['url']))
+                       );
+                       $viewPlannerUrl = sprintf(
+                               $viewPlannerFormat,
+                               MEMBER_SESSION_PAGE
+                       );
+                       if ($_SESSION['wish_list'][$row['member_id']]) {
+                               $plannerText = 'View Planner';
+                               $addToPlannerUrl = sprintf(
+                                       $viewPlannerFormat,
+                                       MEMBER_SESSION_PAGE
+                               );
+                       } else {
+                               $plannerText = 'Add To Planner';
+                               $addToPlannerUrl = sprintf(
+                                       $addToPlannerFormat,
+                                       $_GET['catid'],
+                    $row['member_id']
+                               );
+                       }
+                       $moreInfoUrl = sprintf(
+                               $moreInfoFormat,
+                               $_GET['catid'],
+                               $row['member_id']
+                       );
+            $searchResultNumbered =& $root
+                ->getItem('section', 'conf')
+                ->getItem('directive', 'searchResultNumbered')
+                ->getContent();
+            $iconUrl = ($searchResultNumbered == true)
+                ? BASE_URL
+                . "map/5680FC/{$count}.png"
+                : '';
+                       $members[] = array(
+                               'member_id'       => $row['member_id'],
+                               'member_name'     => $row['member_name'],
+                               'lat'             => $row['lat'],
+                               'lng'             => $row['lon'],
+                               'street'          => $row['street'],
+                               'state_abb'       => $row['state_abbr'],
+                               'city_name'       => $row['city_name'],
+                               'zip'             => $row['zip'],
+                               'phone'           => $row['phone'],
+                               'url'             => $websiteUrl,
+                               'website'         => $row['url'],
+                               'logoPath'        => MEMBER_GOOGLE_MAP,
+                               'logo'            => $row['logo'],
+                               'logoWidth'       => $imgWidth,
+                               'logoHeight'      => $imgHeight,
+                               'hasTripPlanner'  => MEMBER_SESSION_LIST,
+                               'addToPlannerUrl' => $addToPlannerUrl,
+                               'viewPlannerUrl'  => $viewPlannerUrl,
+                               'plannerText'     => $plannerText,
+                               'moreInfoUrl'     => $moreInfoUrl,
+                'iconUrl'         => $iconUrl,
+                'zIndex'         => $count,
+                       );
+               }
+        ++$count;
+       }
+} catch (PDOException $e) {
+       Toolkit_Common::handleError($e);
+}
+
+echo $xmlEncoder->getMemberXML($members);
diff --git a/Toolkit/Members/memberFileDownload.php b/Toolkit/Members/memberFileDownload.php
new file mode 100644 (file)
index 0000000..b223767
--- /dev/null
@@ -0,0 +1,32 @@
+<?php
+/**
+ * Handles Sending files downloads to the browser
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @version   CVS: $Id: memberFileDownload.php,v 1.4 2010/05/15 16:36:01 jamie Exp $
+ * @link      http://demo.gaslightmedia.com
+ */
+$includeFunctions = false;
+
+/**
+ * Description for require_once
+ */
+require_once '../../setup.phtml';
+
+$download = new Toolkit_Members_FileDownload(
+       Toolkit_Database::getInstance()
+);
+$file = $download->getFile($_GET['mid'], $_GET['fid']);
+
+if (!PEAR::isError($file)) {
+    $download->sendFileToBrowser($file);
+} else {
+    exit();
+}
+?>
diff --git a/Toolkit/Members/memberdb.css b/Toolkit/Members/memberdb.css
new file mode 100644 (file)
index 0000000..3ef3869
--- /dev/null
@@ -0,0 +1,410 @@
+/* 
+
+h1 {
+       font-size: 16px;
+       }       
+#content {
+       margin: 0px;
+}
+#subnavcontainer, #navcontainer,
+#top {
+       margin-right: 0px;
+}
+#wrapper {
+       width: 700px;
+       margin: 0 auto;
+       text-align: left;
+       background: white;
+       padding: 20px;
+       height: 1%;
+       overflow: hidden;
+       }
+Above is only for template , DISREGARD :) */   
+#advanced-search {
+       text-align: right;
+       cursor: pointer;
+       color: blue;
+}
+.req {
+       color: red;
+}
+#form-warning-top {
+       color: black;
+       font-size: 110%;
+       font-weight: bold;
+       margin: 10px;
+       padding: 7px;
+       border: 1px solid red;
+       background-color: #FFCCCC;
+}
+#form-success-top {
+       color: black;
+       font-size: 110%;
+       font-weight: bold;
+       margin: 10px;
+       padding: 7px;
+       border: 1px solid green;
+       background-color: #CCFFCC;
+}
+       
+img {
+       border: 0;
+       display: block;
+       }       
+/*   ---------------   */      
+/*     NAVIGATION      */
+/*   ---------------   */      
+#nav-detail {
+       margin-top: 12px;
+       height: 1%;
+       overflow: hidden;
+       clear: left;
+       }
+#nav-detail ul {
+  padding: 0px 0;
+       padding-bottom: 3px;
+  margin: 0;
+       margin-top: 10px;
+  border-bottom: 1px solid #666;
+  font-weight: bold;
+}
+#nav-detail ul li {
+  list-style: none;
+  margin: 0;
+  display: inline;
+}
+#nav-detail ul li a {
+  padding: 3px 0.5em;
+  margin-left: 3px;
+  border: 1px solid #666;
+  border-bottom: none;
+  background: #E6EFD1;
+  text-decoration: none;
+}
+#nav-detail ul li a:link { color: #666; }
+#nav-detail ul li a:visited { color: #666; }
+#nav-detail ul li a:hover {
+  color: #666;
+  background: #ccc;
+       background: #FFFBDF;
+  border-color: #666;
+}
+#nav-detail ul li a.current {
+  background: white;
+  border-bottom: 1px solid white;
+       color: #000;
+}
+
+/* Member Box */
+#member-info   {
+       margin: 0;
+       border: 1px solid #666;
+       border-top: 0;
+       padding: 10px;
+       position: relative;
+       height: 1%;
+       overflow: hidden;
+       clear: left;
+       }
+       
+#mRow1 {
+       float: left;
+       position: relative;
+       margin: 0 0 0 10px;
+       display: inline;
+       width: 380px;
+       }
+#mRow2 {
+       float: right;
+       position: relative;
+       }
+#mRow1 .text {
+       width: 180px;
+       }       
+#mRow2 .text {
+       width: 150px;
+       }               
+.form {
+       clear: left;
+       display: block;
+       position: relative;
+       margin: 0 0 1em 0;
+       padding: 0;
+       border: 0;
+       }
+/* narrower column */ 
+.formNarrow {
+       clear: right;
+       margin: 0 0 1em 0;
+       }       
+.form legend {
+       font-size: 1.2em;
+       font-weight: bold;
+       margin: 0;
+       padding: 0 0 0.4em 0;
+       color: #000;
+       }
+.form table,
+.form td {
+       border-collapse: collapse;
+       border: 1px solid #fff;
+       padding: 0;
+       background: #D6DFC3;
+       }       
+.form td {
+       padding: 4px 6px;
+       }
+.form label {
+       display: block;
+       }
+.labelcell {
+       text-align: right;
+       width: 120px;
+       }
+.formNarrow .labelcell {
+       width: 110px;
+       }       
+.fieldcell {
+       text-align: left;
+       width: 220px;
+       }
+.formNarrow .fieldcell {
+       width: 150px;
+       }
+       
+/* Multiple rows in one cell    */
+.fieldcell i {
+       display: block;
+       font-style: normal;
+       padding: 5px;
+       text-align: left;
+       background-color: #eee;
+       margin-bottom: 1px;
+       }
+.fieldcell i img {
+       margin-right: 6px;}
+       
+/* Small graphics */
+.remove {
+       float: right;
+       clear: right;}
+.add {
+       display: block;
+       /* float: right; */
+       display: block;
+       font-style: normal;
+       padding: 5px;
+       text-align: left;
+       background-color: #eee;
+       margin-bottom: 1px;
+       }
+.add img {float: left; margin-right: 10px;}    
+.info {
+       float: right;
+       }
+
+.priceFrom,
+.priceTo {
+       width: 4em;
+       }       
+.submit {display: block;}      
+
+/* Submit */
+.submitArea {
+       background: #D6DFC3;
+       text-align: center;
+       padding: 10px;
+       clear: both;
+       }
+.submitArea input {
+       margin: 0 auto;
+       display: block;
+       }
+
+       
+/*   ---------------   */      
+/*        PHOTOS       */
+/*   ---------------   */      
+.photoItem {
+       margin-top: 1em;
+       padding: 20px;
+       border: 1px solid #ccc;
+       height: 1%;
+       overflow: hidden;
+       position: relative;
+       background: #D6DFC3;
+       }
+.photoItem .thumb {
+       float: left;
+       position: relative;
+       margin-right: 20px;
+       }
+.photoItem i {
+       font-style: normal;
+       font-weight: bold;
+       display: block;
+       }
+.photoItem input {margin-top: 0.5em;}
+.photoItem input.text {
+       width: 400px;
+       display: block;
+       }       
+.photoItem .photoDelete {
+/*     display: block;
+       margin-top: 1em;
+       border: 1px solid #ccc;
+       background: #FFEFEF;
+       width: 130px;
+       padding: 3px;
+       color: #000;
+*/
+       position: absolute;
+       bottom: 20px;
+       right: 20px;    
+
+       }
+.photoDelete:hover {background: #EFD1D1;}      
+.photoItem .photoDelete img {
+       float: left;
+       margin-right: 6px;
+       }
+.photoOptions {float: left;}
+
+
+/*   ---------------   */      
+/*      PACKAGES       */
+/*   ---------------   */      
+
+.packageItem {
+       margin-top: 1em;
+       padding: 20px;
+       border: 1px solid #96A379;
+       height: 1%;
+       overflow: hidden;
+       position: relative;
+       background: #D6DFC3;
+       }
+
+.packageItem .thumb {
+       position: relative;
+       margin-bottom: 1em;
+       }
+.packageText {
+       float: left;
+       width: 350px;
+       padding-bottom: 1em;
+       }       
+.packageItem i {
+       font-style: normal;
+       font-weight: bold;
+       display: block;
+       padding-top: 1em;
+       
+       }
+.packageItem input {margin-top: 0.5em;}
+.packageItem input.text {
+       width: 200px;
+       display: block;
+       }
+.packageItem textarea {
+       width: 300px;
+       height: 150px;
+       }       
+.packageItem .packageDelete {
+       display: block;
+       margin-top: 1em;
+       border: 1px solid #ccc;
+       background: #FFEFEF;
+       width: 140px;
+       padding: 3px;
+       position: absolute;
+       bottom: 20px;
+       right: 20px;    
+       color: #000;
+       }
+.packageDelete:hover {background: #EFD1D1;}    
+.packageItem .packageDelete img {
+       float: left;
+       margin-right: 6px;
+       }
+.packageOptions {float: left;}
+
+
+
+/*   ---------------   */      
+/*      AMENITIES      */
+/*   ---------------   */      
+.amenityList {
+       list-style-type: none;
+       float: left;
+       position: relative;
+       margin-right: 50px;
+       zoom: 1;
+       width: 200px;
+       }
+.amenityList input {
+       /* No Luck, see http://meyerweb.com/eric/thoughts/2007/05/15/formal-weirdness/ */
+}
+.amenityList li {
+       vertical-align: middle;
+       height: 1%;
+       overflow: hidden;
+       font-size: 1.2em;
+       }
+.amenityList label {
+  padding: 4px;
+  display: block;
+       background: #D6DFC3;
+       margin-bottom: 1px;
+} 
+.amenityList label.amenityOn {
+       background-color: #E6EFD1;
+       cursor: hand;
+       cursor: pointer;
+       }       
+
+/* SPECIFIC TO SEARCH RESULT HERE */
+.searchResult {
+       border: 1px solid #96A379;
+       padding: 10px 20px;
+       margin: 5px 0;
+       background-color: #D6DFC3;
+       height: 1%;
+       overflow: hidden;
+       position: relative;
+}
+.searchResultOn {
+       background: url(../../assets/searchResultOn.gif) no-repeat 95% center #E6EFD1;
+       cursor: hand;
+       cursor: pointer;
+}
+.searchResult h3 {
+       font-size: 15px;
+       color: #333;
+       margin: 0;
+       float: left;
+}
+.searchResultOn h3 {
+       color: #000;
+}
+.searchResult .phone {
+       position: absolute;
+       bottom: 10px;
+       right: 300px;
+}
+.searchResult a.email {
+       position: absolute;
+       bottom: 10px;
+       right: 150px;
+}
+.searchResult a {
+       color: #96A379;
+   text-decoration: none;
+}
+.searchResult a.email {
+       text-decoration: underline;
+}
+.searchResult a:link {color: #585F47;}
+.searchResult a:visited {color: #585F47;}
+.searchResult a:hover {color: #585F47;}
+.searchResult a:active {color: #585F47;}
diff --git a/Toolkit/Members/sortPhotos.php b/Toolkit/Members/sortPhotos.php
new file mode 100644 (file)
index 0000000..72852c7
--- /dev/null
@@ -0,0 +1,55 @@
+<?php
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: sortPhotos.php,v 1.5 2009/12/29 14:17:49 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+require_once '../../setup.phtml';
+//     Make sure the users browser doesn't cache the result.
+
+//     Time in the past.
+header('Expires: Wed, 23 Dec 1980 00:30::00 GMT');
+header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
+header('Cache-Control: no-cache, must-revalidate');
+header('Pragma: no-cache');
+
+if (!is_array($_GET['photos'])) {
+       return;
+}
+$newOrder = $_GET['photos'];
+
+$dbh = Toolkit_Database::getInstance();
+try {
+       $dbh->beginTransaction();
+
+       $sql = "
+        UPDATE member_photos
+           SET pos = :pos
+         WHERE id  = :id";
+       $stmt = $dbh->prepare($sql);
+       foreach ($newOrder as $k => &$v) {
+               $pos = $k + 1;
+               $stmt->bindParam(':pos', $pos, PDO::PARAM_INT);
+               $stmt->bindParam(':id', $v, PDO::PARAM_INT);
+               $stmt->execute();
+       }
+       $dbh->commit();
+       echo true;
+} catch (PDOException $e) {
+       $dbh->rollBack();
+       echo 'PDO Exception Caught.  ';
+       echo 'Error with the database:<br>';
+       echo 'Error: ' . $e->getMessage() . '<br>';
+       echo 'File: ' . $e->getFile() . '<br>';
+       echo 'Line: ' . $e->getLine() . '<br>';
+       print_r($dbh->errorInfo());
+}
+?>
diff --git a/Toolkit/Members/templates/addPackage.tpl b/Toolkit/Members/templates/addPackage.tpl
new file mode 100644 (file)
index 0000000..aa40473
--- /dev/null
@@ -0,0 +1,41 @@
+<div class="packageItem packageUploadForm">
+       {form.javascript:h}
+       {form.outputHeader():h}
+    {form.hidden:h}
+               <div class="packageText">
+            <i>{form.title.label:h}</i>
+            <div flexy:if="form.title.error" class="req">{form.title.error:h}</div>
+            {form.title.html:h}
+            <i>{form.description.label:h}</i>
+            <div flexy:if="form.description.error" class="req">{form.description.error:h}</div>
+            {form.description.html:h}
+            <i>
+                <span class="req" flexy:if="form.sdate.required">*</span>
+                {form.sdate.label:h}
+            </i>
+            <div flexy:if="form.sdate.error" class="req">{form.sdate.error:h}</div>
+            {form.sdate.html:h}
+            <i>
+                <span class="req" flexy:if="form.edate.required">*</span>
+                {form.edate.label:h}
+            </i>
+            <div flexy:if="form.edate.error" class="req">{form.edate.error:h}</div>
+            {form.edate.html:h}
+        </div>
+        <div class="packagePhoto">
+            <div flexy:if="showCurrImg">
+                <label>
+                    {form.remove_img_rmv.html:h}
+                    {form.remove_img_rmv.label:h}
+                </label>
+                
+                <i>{form.curr_image.label:h}</i>
+                {form.curr_image.html:h}
+            </div>
+            <i>{form.image.label:h}</i>
+            <div flexy:if="form.image.error" class="req">{form.image.error:h}</div>
+            {form.image.html:h}
+        </div>
+        <div class="submitArea"> {form.add_rmv.html:h} </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/addPhoto.tpl b/Toolkit/Members/templates/addPhoto.tpl
new file mode 100644 (file)
index 0000000..edad160
--- /dev/null
@@ -0,0 +1,15 @@
+<div class="photoItem photoUploadForm">
+       {form.javascript:h}
+       {form.outputHeader():h}
+               {form.hidden:h}
+               <div class="photoOptions">
+                       <i>{form.file.label:h}</i>
+                       <div flexy:if="form.file.error" class="req">{form.file.error:h}</div>
+                       {form.file.html:h}
+                       <i>{form.caption.label:h}</i>
+                       <div flexy:if="form.caption.error" class="req">{form.caption.error:h}</div>
+                       {form.caption.html:h}
+                       {form.submit.html:h}
+               </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/addYourBusinessAdminEmail.tpl b/Toolkit/Members/templates/addYourBusinessAdminEmail.tpl
new file mode 100755 (executable)
index 0000000..ceb2cb5
--- /dev/null
@@ -0,0 +1,53 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+       <title>New Member Notification - {member_name:h}</title>
+</head>
+<body>
+<center>
+<table cellspacing="0" cellpadding="0" bgcolor="#ffffff" border="0">
+               <tr>
+                       <td>
+                               <table cellspacing="1" cellpadding="15" border="0" bgcolor="#cccccc" width="450">
+                                       <tr bgcolor="#cccccc">
+                                               <td bgcolor="#ffffff">
+                                                       <font size="4" face="arial, sans-serif">
+                                                               <b>You have a new member</b>
+                                                       </font>
+                                                       <br><br>
+                                                       <font size="3" face="arial, sans-serif">
+                                                               <b>{member_name:h}</b> has joined {client_name:h} from your website
+                                                       </font>
+                                                       <br><br>
+                                                       {if:approval_needed}
+                                                       <font size="2" face="arial, sans-serif">
+                                                               Your approval is required to complete this process.
+                                                               <br>
+                                                               <a href="baseurl/admin/members.php?page=memberRequests&module=listNewMemberRequests" target="_blank">Member administration area</a>
+                                                       </font>
+                                                       {end:}
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>
+               <tr>
+                       <td>
+                               <table cellspacing="0" cellpadding="15" border="0" width="450">
+                                       <tr>
+                                               <td bgcolor="#cccccc">
+                                                       <font size="1" face="arial, sans-serif">
+                                                               Please do not reply to this email, it will not go anywhere.
+                                                               <br><br>
+                                                               To ensure the delivery of these e-mails to your inbox, please add donotreply@gaslightmedia.com to your e-mail Address Book or Safe List.
+                                                       </font>
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>                           
+       </table>
+</center>
+</body>
+</html>
diff --git a/Toolkit/Members/templates/addYourBusinessMemberEmail.tpl b/Toolkit/Members/templates/addYourBusinessMemberEmail.tpl
new file mode 100644 (file)
index 0000000..0e9e4a0
--- /dev/null
@@ -0,0 +1,57 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+       <title>Registration - {client_name:h}</title>
+</head>
+<body>
+<center>
+<table cellspacing="0" cellpadding="0" bgcolor="#ffffff" border="0">
+               <tr>
+                       <td>
+                               <table cellspacing="1" cellpadding="15" border="0" bgcolor="#cccccc" width="450">
+                                       <tr bgcolor="#cccccc">
+                                               <td bgcolor="#ffffff">
+                                                       {if:!approval_needed}
+                                                       <font size="3" face="arial, sans-serif">
+                                                               <b>Your registration is complete</b>
+                                                       </font>
+                                                       <br><br>
+                                                       <font size="2" face="arial, sans-serif">
+                                                               Dear {first_name:h},<br>
+                                                               Thanks for joining the {client_name:h} website.<br>
+                                                               Below is the username and password you selected.
+                                                               <br><br>
+                                                               Username: {username:h}
+                                                               <br>
+                                                               Password: {password:h}
+                                                               <br><br>
+                                                               Use this to <a href="{base_url:h}index.php?catid={member_category}" target="_blank">log into your members area</a>.
+                                                               <br><br>
+                                                               Sincerely,<br>
+                                                               {client_name:h}
+                                                       </font>
+                                                       {else:}
+                                                       <font size="3" face="arial, sans-serif">
+                                                               <b>Your registration is pending.</b>
+                                                       </font>                                                         
+                                                       <br><br>
+                                                       <font size="2" face="arial, sans-serif">
+                                                               Dear {first_name:h},<br>
+                                                               Thanks for joining the {client_name:h} website.
+                                                               <br><br>
+                                                               We need to approve your information first. As soon as this is done we will notify you by email.
+                                                               <br><br>
+                                                               Sincerely,<br>
+                                                               {client_name:h}
+                                                       </font>
+                                                       {end:}
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>                           
+       </table>
+</center>
+</body>
+</html>
diff --git a/Toolkit/Members/templates/admin.tpl b/Toolkit/Members/templates/admin.tpl
new file mode 100644 (file)
index 0000000..2073404
--- /dev/null
@@ -0,0 +1,29 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<title>{title:h}</title>
+<meta http-equiv="content-type" content="text/html;charset=utf-8">
+<meta http-equiv="imagetoolbar" content="no">
+<meta http-equiv="imagetoolbar" content="false">
+{styles:h}
+{topScripts:h}
+</head>
+<body id="memberdb">
+       <div id="wrapper">
+               <div id="top"></div>
+               <div id="navcontainer"> {nav:h} </div>
+        <div flexy:if="breadcrumbs" id="breadcrumbs">
+            <a href="baseurl/admin/members.php?rt=Members&ac=listMembers">{listingType:h}</a>
+            &gt;
+            <a href="{searchResults:h}">Search Results</a>
+        </div>
+               <div id="content"> {content:h} </div>
+       </div><!-- /#wrapper -->
+       <div id="bottom"></div>
+       <div id="copyright">
+               Copyright &copy; 2008 Gaslight Media, All Rights Reserved
+       </div>
+       {bottomScripts:h}
+</body>
+</html>
diff --git a/Toolkit/Members/templates/authorizeChanges.tpl b/Toolkit/Members/templates/authorizeChanges.tpl
new file mode 100644 (file)
index 0000000..2467b32
--- /dev/null
@@ -0,0 +1,46 @@
+<div id="member-info">
+       <p class="reminder">
+               Remember to click on the Submit button on the
+               bottom of the page after doing any changes.
+       </p>
+       {form.javascript:h}
+       
+       {form.outputHeader():h}
+    {form.hidden:h}
+
+               <!-- Error or Success Message -->
+               {validated():h}
+               <div>
+            <fieldset flexy:foreach="form.sections,sec" class="form">
+                <legend>{sec.header}</legend>
+                <table class="pendingUpdates">
+                    <tbody>
+                        <tr flexy:foreach="sec.elements,elem">
+                            <td class="labelcell">
+                                {elem.label:h}
+                            </td>
+                            <td class="fieldcell updates">
+                                    <div flexy:foreach="elem.elements,gitem" class="field">{gitem.html:h}</div>
+                                <div class="authorization">
+                                    <label class="pendingUpdate" for="pmuyes{elem.name:h}">
+                                        <input type="radio" id="pmuyes{elem.name:h}"
+                                            value="yes" name="{group(elem.name):h}[{elem.name:h}]">
+                                        Accept
+                                    </label>
+                                    <label class="pendingUpdate" for="pmuno{elem.name:h}">
+                                        <input type="radio" id="pmuno{elem.name:h}"
+                                            value="no" name="{group(elem.name):h}[{elem.name:h}]">
+                                        Reject
+                                    </label>
+                                </div>
+                            </td>
+                        </tr>
+                    </tbody>
+                </table>
+            </fieldset>
+               </div>
+               <div class="submitArea">
+                       <input type="submit" class="submit" value="Submit">
+               </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/currentTables/Element.tpl b/Toolkit/Members/templates/currentTables/Element.tpl
new file mode 100644 (file)
index 0000000..595457b
--- /dev/null
@@ -0,0 +1,14 @@
+<tr>
+       <td class="labelcell">
+               <!-- BEGIN required -->
+               <span class="req">*</span>
+               <!-- END required -->
+               <label>{label}</label>
+       </td>
+       <td class="fieldcell">
+               <!-- BEGIN error -->
+               <div class="req"> {error} </div>
+               <!-- END error -->
+               {element}
+       </td>
+</tr>
diff --git a/Toolkit/Members/templates/currentTables/Form.tpl b/Toolkit/Members/templates/currentTables/Form.tpl
new file mode 100644 (file)
index 0000000..f59286a
--- /dev/null
@@ -0,0 +1,7 @@
+<div id="contact">
+       <form{attributes}>
+               <table>
+                       {content}
+               </table>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/currentTables/Group.tpl b/Toolkit/Members/templates/currentTables/Group.tpl
new file mode 100644 (file)
index 0000000..cdd24cf
--- /dev/null
@@ -0,0 +1,5 @@
+<table class="group">
+       <tbody>
+               {content}
+       </tbody>
+</table>
diff --git a/Toolkit/Members/templates/currentTables/GroupElement.tpl b/Toolkit/Members/templates/currentTables/GroupElement.tpl
new file mode 100644 (file)
index 0000000..1a4ba27
--- /dev/null
@@ -0,0 +1,9 @@
+<tr>
+       <td>
+               {element}
+               <!-- BEGIN required -->
+               <span class="req">*</span>
+               <!-- END required -->
+               {label}
+       </td>
+</tr>
diff --git a/Toolkit/Members/templates/currentTables/Header.tpl b/Toolkit/Members/templates/currentTables/Header.tpl
new file mode 100644 (file)
index 0000000..64ac244
--- /dev/null
@@ -0,0 +1,5 @@
+<tr class="hdr">
+       <td colspan="2">
+               {header}
+       </td>
+</tr>
diff --git a/Toolkit/Members/templates/currentTables/RequiredNote.tpl b/Toolkit/Members/templates/currentTables/RequiredNote.tpl
new file mode 100644 (file)
index 0000000..525ef33
--- /dev/null
@@ -0,0 +1 @@
+<span class="req">*</span> Denotes required field
diff --git a/Toolkit/Members/templates/editAmenities.tpl b/Toolkit/Members/templates/editAmenities.tpl
new file mode 100644 (file)
index 0000000..bc6d893
--- /dev/null
@@ -0,0 +1,42 @@
+<div id="nav-detail"> {nav:h} </div>
+<div id="member-info">
+       {if:pending}
+               <div class="pending pendingMsg">
+                       The yellow colored items are pending approval from the website
+                       administrator.<br>Upon approval, your changes will be visible on
+                       the website.
+               </div>
+       {end:}
+       {form.javascript:h}
+       
+       {form.outputHeader():h}
+       {form.hidden:h}
+
+       <!-- Error or Success Message -->
+       {validated():h}
+       <h1>Edit Amenities</h1>
+       <p>
+               Check off any available amenities and click
+               the submit button on the bottom of the page.
+       </p>
+       {foreach:form.sections,sec}
+               <ul class="amenityList">
+                       {foreach:sec.elements,elem}
+                               {if:fieldPending(elem)}
+                                       <li class="fieldPending">
+                               {else:}
+                                       <li>
+                               {end:}
+                                       <label>
+                                               {elem.html:h}
+                                               {elem.label:h}
+                                       </label>
+                               </li>
+                       {end:}
+               </ul>
+       {end:}
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Submit Changes">
+       </div>
+    </form>
+</div>
diff --git a/Toolkit/Members/templates/editAmenity.tpl b/Toolkit/Members/templates/editAmenity.tpl
new file mode 100644 (file)
index 0000000..bbea016
--- /dev/null
@@ -0,0 +1,42 @@
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- CheckBoxes go here. -->
+                    {if:elem.isType(#checkbox#)}
+                        <td class="labelcell"> {elem.html:h} </td>
+                        <td class="fieldcell"> {elem.label:h} </td>
+                    {else:}
+                        <!-- All regular elements go here. -->
+                        <td class="labelcell">
+                            <span flexy:if="elem.required" class="req">*</span>
+                            {if:elem.error}<span class="req">{end:}
+                                {elem.label}
+                            {if:elem.error}</span>{end:}
+                        </td>
+                        <td class="fieldcell">
+                            <div flexy:if="elem.error" class="req">
+                                {elem.error}
+                            </div>
+                            {elem.html:h}
+                        </td>
+                    {end:}
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Save Amenity">
+               {if:isEdit()}
+                       <input type="submit" name="delete" class="submit" value="Remove Amenity">
+               {end:}
+       </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/editBilling.tpl b/Toolkit/Members/templates/editBilling.tpl
new file mode 100644 (file)
index 0000000..0d80493
--- /dev/null
@@ -0,0 +1,48 @@
+<link rel="stylesheet" type="text/css" href="http://app.gaslightmedia.com/libjs/Jscal/system.css">
+
+<script type="text/javascript" src="baseurl/Toolkit/Members/Billing/js/edit-billing.js?t=1"></script>
+{jsCalScripts:h}
+<div id="nav-detail"> {nav:h} </div>
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- All regular elements go here. -->
+                    <td class="labelcell">
+                        <span flexy:if="elem.required" class="req">*</span>
+                        {if:elem.error}<span class="req">{end:}
+                            {elem.label}
+                        {if:elem.error}</span>{end:}
+                    </td>
+                    <td class="fieldcell">
+                        <span flexy:if="elem.error" class="req">
+                            {elem.error}
+                        </span>
+                        {elem.html:h}
+                    </td>
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+
+    <div class="submitArea" style="height:30px;width:400px;">
+        <b style="width:200px;float:left;">
+            <input type="submit" class="submit" value="Submit Changes">
+        </b>
+        {if:hasInfo()}
+        <b style="width:200px;float:left;">
+                       <input type="submit" name="delete" class="submit" value="Remove Billing Info"
+                   onClick="return(confirm('This cannot be undone! Are You Sure?'));">
+        </b>
+               {end:}
+       </div>
+    </form>
+    {memberStatements:h}
+</div>
diff --git a/Toolkit/Members/templates/editCategory.tpl b/Toolkit/Members/templates/editCategory.tpl
new file mode 100644 (file)
index 0000000..0ec0eba
--- /dev/null
@@ -0,0 +1,42 @@
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                                       <tr flexy:foreach="sec.elements,elem">
+                                               <!-- CheckBoxes go here. -->
+                                               {if:elem.isType(#checkbox#)}
+                                                       <td class="labelcell"> {elem.html:h} </td>
+                                                       <td class="fieldcell"> {elem.label:h} </td>
+                                               {else:}
+                                                       <!-- All regular elements go here. -->
+                                                       <td class="labelcell">
+                                <span flexy:if="elem.required" class="req">*</span>
+                                                               {if:elem.error}<span class="req">{end:}
+                                                                       {elem.label}
+                                                               {if:elem.error}</span>{end:}
+                                                       </td>
+                                                       <td class="fieldcell">
+                                                               <span flexy:if="elem.error" class="req">
+                                                                       {elem.error}
+                                                               </span>
+                                                               {elem.html:h}
+                                                       </td>
+                        {end:}
+                                       </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Save Category">
+        {if:isEdit()}
+        <input type="submit" name="delete" class="submit" value="Remove Category">
+        {end:}
+       </div>
+    </form>
+</div>
diff --git a/Toolkit/Members/templates/editCity.tpl b/Toolkit/Members/templates/editCity.tpl
new file mode 100644 (file)
index 0000000..f4e975f
--- /dev/null
@@ -0,0 +1,42 @@
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- CheckBoxes go here. -->
+                    {if:elem.isType(#checkbox#)}
+                        <td class="labelcell"> {elem.html:h} </td>
+                        <td class="fieldcell"> {elem.label:h} </td>
+                    {else:}
+                        <!-- All regular elements go here. -->
+                        <td class="labelcell">
+                            <span flexy:if="elem.required" class="req">*</span>
+                            {if:elem.error}<span class="req">{end:}
+                                {elem.label}
+                            {if:elem.error}</span>{end:}
+                        </td>
+                        <td class="fieldcell">
+                            <div flexy:if="elem.error" class="req">
+                                {elem.error}
+                            </div>
+                            {elem.html:h}
+                        </td>
+                    {end:}
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Save City">
+               {if:isEdit()}
+                       <input type="submit" name="delete" class="submit" value="Remove City">
+               {end:}
+       </div>
+    </form>
+</div>
diff --git a/Toolkit/Members/templates/editContact.html b/Toolkit/Members/templates/editContact.html
new file mode 100644 (file)
index 0000000..ccae41e
--- /dev/null
@@ -0,0 +1,21 @@
+<fieldset class="form">
+       {form.outputHeader():h}
+               {form.hidden:h}
+               <table>
+                       <tbody>
+                               <tr flexy:foreach="form.elements,e">
+                                       <td class="labelcell">
+                                               <span flexy:if="e.required" class="req">*</span>
+                                               {if:e.error}<span class="req">{end:}
+                                                       {e.label:h}
+                                               {if:e.error}</span>{end:}
+                                       </td>
+                                       <td class="fieldcell">
+                                               <div flexy:if="e.error" class="req">{e.error:h}</div>
+                                               {e.html:h}
+                                       </td>
+                               </tr>
+                       </tbody>
+               </table>
+       </form>
+</fieldset>
diff --git a/Toolkit/Members/templates/editContacts.tpl b/Toolkit/Members/templates/editContacts.tpl
new file mode 100644 (file)
index 0000000..8802c55
--- /dev/null
@@ -0,0 +1,57 @@
+<div id="nav-detail"> {nav:h} </div>
+<div id="member-info">
+       <h1>Contacts</h1>
+       {form.javascript:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       {foreach:form.sections,k,sec}
+               {if:isForm(k)}
+                       <fieldset class="form">
+                               <table>
+                                       <tbody>
+                                               {form.outputHeader():h}
+                                               {form.hidden:h}
+                                                       <input type="hidden" name="target" value="{k}">
+                            <tr flexy:foreach="sec.elements,elem">
+                                <td class="labelcell">
+                                    <span flexy:if="elem.required" class="req">*</span>
+                                    {if:elem.error}<span class="req">{end:}
+                                        {elem.label:h}
+                                    {if:elem.error}</span>{end:}
+                                </td>
+                                <td class="fieldcell">
+                                    <span flexy:if="elem.error" class="req">
+                                        {elem.error}
+                                    </span>
+                                    {elem.html:h}
+                                </td>
+                            </tr>
+                                               </form>
+                                       </tbody>
+                               </table>
+                       </fieldset>
+               {else:}
+                       <div class="contactList">
+                               <a class="remove" href="{getDelUrl(sec):h}">
+                    <img width="16" height="16" title="Delete Contact"
+                         src="glmappbaseurl/assets/icons/user_delete.png" alt="remove">
+                </a>
+                               {foreach:sec.elements,elem}
+                    <h3 flexy:if="isName(elem.name)">
+                        <a href="{getEditUrl(sec):h}">{elem.html:h}</a>
+                    </h3>
+                    <div flexy:if="isTitle(elem.name)" class="title">
+                        {elem.html:h}
+                    </div>
+                    <div flexy:if="isPhone(elem.name)" class="phone">
+                        {elem.html:h}
+                    </div>
+                    <a flexy:if="isEmail(elem.name)" class="email" href="mailto:{elem.html:h}">
+                        {elem.html:h}
+                    </a>
+                               {end:}
+                               {getMailIcon(sec.elements[5]):h}
+                       </div>
+               {end:}<!-- isForm(k) -->
+       {end:}
+</div><!-- /#member-info -->
diff --git a/Toolkit/Members/templates/editCounty.tpl b/Toolkit/Members/templates/editCounty.tpl
new file mode 100644 (file)
index 0000000..8d26ece
--- /dev/null
@@ -0,0 +1,36 @@
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- All regular elements go here. -->
+                    <td class="labelcell">
+                        <span flexy:if="elem.required" class="req">*</span>
+                        {if:elem.error}<span class="req">{end:}
+                            {elem.label}
+                        {if:elem.error}</span>{end:}
+                    </td>
+                    <td class="fieldcell">
+                        <span flexy:if="elem.error" class="req">
+                            {elem.error}
+                        </span>
+                        {elem.html:h}
+                    </td>
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Save County">
+               {if:isEdit()}
+                       <input type="submit" name="delete" class="submit" value="Remove County">
+               {end:}
+       </div>
+    </form>
+</div>
diff --git a/Toolkit/Members/templates/editCouponEmail.tpl b/Toolkit/Members/templates/editCouponEmail.tpl
new file mode 100755 (executable)
index 0000000..48aadbf
--- /dev/null
@@ -0,0 +1,54 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+       <title>Member Coupon Notification for - {member_name:h}</title>
+</head>
+<body>
+<center>
+<table cellspacing="0" cellpadding="0" bgcolor="#ffffff" border="0">
+               <tr>
+                       <td>
+                               <table cellspacing="1" cellpadding="15" border="0" bgcolor="#cccccc" width="450">
+                                       <tr bgcolor="#cccccc">
+                                               <td bgcolor="#ffffff">
+                                                       <font size="4" face="arial, sans-serif">
+                                                               <b>{member_name:h}</b>
+                                                               <br>
+                                                               {if:edit}
+                                                                       <b>has edited a coupon</b>
+                                                               {else:}
+                                                                       <b>has created a new coupon</b>
+                                                               {end:}
+                                                       </font>
+                                                       <br><br>
+                                                       <font size="2" face="arial, sans-serif">
+                                                               Your approval is required to complete this process.
+                                                               <br>
+                                                               Please follow this link to review this change
+                                                               <a href="{baseUrl:h}admin/index.phtml?page=coupons.php%3Fpage=editCoupon%26module=editCoupon%26id={coupon_id:h}" target="_blank">Coupons Admin</a>
+                                                       </font>
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>
+               <tr>
+                       <td>
+                               <table cellspacing="0" cellpadding="15" border="0" width="450">
+                                       <tr>
+                                               <td bgcolor="#cccccc">
+                                                       <font size="1" face="arial, sans-serif">
+                                                               Please do not reply to this email, it will not go anywhere.
+                                                               <br><br>
+                                                               To ensure the delivery of these e-mails to your inbox, please add donotreply@gaslightmedia.com to your e-mail Address Book or Safe List.
+                                                       </font>
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>
+       </table>
+</center>
+</body>
+</html>
diff --git a/Toolkit/Members/templates/editFile.tpl b/Toolkit/Members/templates/editFile.tpl
new file mode 100644 (file)
index 0000000..21efdc9
--- /dev/null
@@ -0,0 +1,45 @@
+<div id="nav-detail"> {nav:h} </div>
+<div id="member-info">
+       {if:pending}
+               <div class="pending pendingMsg">
+                       The yellow colored items are pending approval from the website
+                       administrator.<br>Upon approval, your changes will be visible on
+                       the website.
+               </div>
+       {end:}
+       <h1>Files</h1>
+       {form.javascript:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+    <div flexy:foreach="form.sections,k,sec" class="photoItem FileItem {pendingClass(k)}">
+        {form.outputHeader():h}
+        {form.hidden:h}
+            <!--
+                Check to see if the first element is an image.
+                If it is, then we need to output before the photoOptions
+                div
+            -->
+            {if:showFile(sec.elements[0])}
+                {sec.elements[0].html:h}
+            {end:}
+            <div class="photoOptions fileOptions">
+                {foreach:sec.elements,elem}
+                    <!--
+                        since we already output the image, if the current
+                        element is anything but an image, then show it.
+                        Otherwise, skip the image.
+                    -->
+                    {if:!elem.isType(#static#)}
+                        {if:elem.isType(#text#)}
+                            <i> {elem.label} </i>
+                        {end:}
+                        <div flexy:if="elem.error" class="req">
+                            {elem.error:h}
+                        </div>
+                        {elem.html:h}
+                    {end:}
+                {end:}
+            </div><!-- /.photoOptions -->
+        </form>
+    </div><!-- /.photoItem -->
+</div><!-- /#member-info -->
diff --git a/Toolkit/Members/templates/editHtmlEmail.tpl b/Toolkit/Members/templates/editHtmlEmail.tpl
new file mode 100644 (file)
index 0000000..0c6feef
--- /dev/null
@@ -0,0 +1,42 @@
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- CheckBoxes go here. -->
+                    {if:elem.isType(#checkbox#)}
+                        <td class="labelcell"> {elem.html:h} </td>
+                        <td class="fieldcell"> {elem.label:h} </td>
+                    {else:}
+                        <!-- All regular elements go here. -->
+                        <td class="labelcell">
+                            <span flexy:if="elem.required" class="req">*</span>
+                            {if:elem.error}<span class="req">{end:}
+                                {elem.label}
+                            {if:elem.error}</span>{end:}
+                        </td>
+                        <td class="fieldcell">
+                            <div flexy:if="elem.error" class="req">
+                                {elem.error}
+                            </div>
+                            {elem.html:h}
+                        </td>
+                    {end:}
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Save Html Email">
+               {if:isEdit()}
+                       <input type="submit" name="delete" class="submit" value="Remove Html Email">
+               {end:}
+       </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/editMember.tpl b/Toolkit/Members/templates/editMember.tpl
new file mode 100644 (file)
index 0000000..385c427
--- /dev/null
@@ -0,0 +1,142 @@
+<div id="nav-detail"> {nav:h} </div>
+<div id="member-info">
+       <div flexy:if="pending" class="pending pendingMsg">
+               The yellow colored items are pending approval from the website
+               administrator.<br>Upon approval, your changes will be visible on
+               the website.
+       </div>
+       <p class="reminder">
+               Remember to click on the Submit button on the
+               bottom of the page after doing any changes.
+       </p>
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+       {foreach:form.sections,sec}
+               {if:newColumn(sec.header)}
+                       </div>
+                       <div id="mRow2">
+               {end:}
+                       {if:inColumn2(sec.header)}
+                               <fieldset class="form formNarrow">
+                       {else:}
+                               <fieldset class="form">
+                       {end:}<!-- /inColumn2 -->
+                       <legend>
+                {sec.header}
+            </legend>
+                       <table>
+                               {foreach:sec.elements,elem}
+                                       {if:fieldPending(elem)}
+                                               <tr class="fieldPending">
+                                       {else:}
+                                               <tr>
+                                       {end:}
+                                               {if:elem.isType(#textarea#)}
+                                                       <td>
+                                <div flexy:if="elem.error" class="req">
+                                    {elem.error:h}
+                                </div>
+                                {elem.html:h}
+                            </td>
+                                               {else:}
+                                                       <!-- CheckBoxes go here. -->
+                                                       {if:elem.isType(#checkbox#)}
+                                {if:isMyCheckBox(elem.name)}
+                                    <td class="labelcell"> {elem.label:h} </td>
+                                    <td class="fieldcell active_field"> {elem.html:h} </td>
+                                {else:}
+                                    <td class="labelcell"> {elem.html:h} </td>
+                                    <td class="fieldcell"> {elem.label:h} </td>
+                                {end:}
+                                                       {else:}
+                                                               <!-- Grouped Elements go here. -->
+                                                               {if:elem.isType(#group#)}
+                                                                       <td class="labelcell">
+                                                                               {if:elem.error}<span class="req">{end:}
+                                                                                       {elem.label:h}
+                                                                               {if:elem.error}</span>{end:}
+                                                                       </td>
+                                                                       <td class="fieldcell">
+                                        <div flexy:if="elem.error" class="req">
+                                            {elem.error:h}
+                                        </div>
+                                                                               {foreach:elem.elements,gitem}
+                                                                                       {if:elem.isName(#city#)}
+                                                                                       <small>{gitem.label:h}</small><br>
+                                                                                       {end:}
+                                                                                       {gitem.html:h}
+                                                                                       {if:elem.separator}{elem.separator:h}{end:}
+                                                                               {end:}
+                                                                       </td>
+                                                               {else:}
+                                                                       {if:elem.isName(#member_cats[]#)}
+                                                                               <td class="fieldcell">
+                                                                                       <div flexy:if="elem.error" class="req">
+                                                                                               {elem.error:h}
+                                                                                       </div>
+                                                                                       <div id="addCategory">
+                                                                                               {elem.html:h}
+                                                                                       </div>
+                                                                                       {showCategories():h}
+                                                                               </td>
+                                                                       {else:}
+                                                                       <!-- All regular elements go here. -->
+                                                                       <td class="labelcell">
+                                                                               <span class="req" flexy:if="elem.required">*</span>
+                                                                               {if:elem.error}<span class="req">{end:}
+                                                                                       {elem.label}
+                                                                               {if:elem.error}</span>{end:}
+                                                                       </td>
+                                                                       <td class="fieldcell">
+                                        <div flexy:if="elem.error" class="req">
+                                            {elem.error:h}
+                                        </div>
+                                                                               {if:addInfoElement(elem.name)}
+                                            {if:elem.isName(#street#)}
+                                            <?php
+                                                $head = 'Additional Information';
+                                                $body = 'Enter an actual street address to
+                                                calculate driving directions.
+                                                Do not use a P.O. Box.';
+                                            ?>
+                                            {end:}
+                                            {if:elem.isName(#member_contact_email#)}
+                                            <?php
+                                                $head = 'Additional Information';
+                                                $body = 'Enter the email address for the
+                                                business you would like visitors
+                                                to see.';
+                                            ?>
+                                            {end:}
+                                                                                       <a>
+                                                <span class="tooltip" title="<?php echo $head . '|' . $body;?>">
+                                                                                               <img class="info" width="16" height="16"
+                                                                                                       title="" alt=""
+                                                                                                       src="glmappbaseurl/assets/icons/information.png">
+                                                </span>
+                                                                               {end:}
+                                                                               {elem.html:h}
+                                                                               {if:addInfoElement(elem.label)}
+                                                                                       </a>
+                                                                               {end:}
+                                                                       </td>
+                                                                       {end:}
+                                                               {end:}<!-- /isType(#group#) -->
+                                                       {end:}<!-- /isType(#checkbox#) -->
+                                               {end:}<!-- /isType(#textarea#) -->
+                                       </tr>
+                               {end:}<!-- /foreach() -->
+                       </table>
+               </fieldset>
+       {end:}<!-- /newColumn() -->
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Submit Changes">
+       </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/editPackage.tpl b/Toolkit/Members/templates/editPackage.tpl
new file mode 100644 (file)
index 0000000..778b866
--- /dev/null
@@ -0,0 +1,54 @@
+<div class="packageItem packageUploadForm">
+       {form.javascript:h}
+       {form.outputHeader():h}
+    {form.hidden:h}
+               <div class="packageText">
+            <i>{form.title.label:h}</i>
+            <div flexy:if="form.title.error" class="req">
+                               {form.title.error:h}
+                       </div>
+            {form.title.html:h}
+            <i>{form.description.label:h}</i>
+            <div flexy:if="form.description.error" class="req">
+                               {form.description.error:h}
+                       </div>
+            {form.description.html:h}
+            <i>
+                <span class="req" flexy:if="form.sdate.required">*</span>
+                {form.sdate.label:h}
+            </i>
+            <div flexy:if="form.sdate.error" class="req">
+                               {form.sdate.error:h}
+                       </div>
+            {form.sdate.html:h}
+            <i>
+                <span class="req" flexy:if="form.edate.required">*</span>
+                {form.edate.label:h}
+            </i>
+            <div flexy:if="form.edate.error" class="req">
+                               {form.edate.error:h}
+                       </div>
+            {form.edate.html:h}
+        </div>
+        <div class="packagePhoto">
+            <div flexy:if="showCurrImg">
+                <label>
+                    {form.remove_img_rmv.html:h}
+                    {form.remove_img_rmv.label:h}
+                </label>
+
+                <i>{form.curr_image.label:h}</i>
+                {form.curr_image.html:h}
+            </div>
+            <i>{form.image.label:h}</i>
+            <div flexy:if="form.image.error" class="req">
+                               {form.image.error:h}
+                       </div>
+            {form.image.html:h}
+        </div>
+        <div class="submitArea">
+            {form.add_rmv.html:h}
+            {form.remove_rmv.html:h}
+        </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/editPackages.tpl b/Toolkit/Members/templates/editPackages.tpl
new file mode 100644 (file)
index 0000000..a3f41c3
--- /dev/null
@@ -0,0 +1,27 @@
+<style type="text/css">
+.ui-state-highlight {
+       border: 3px dashed #666666;
+       height: 1%;
+       margin-top: 1em;
+       overflow: hidden;
+       padding: 28px 18px 18px 28px;
+       position: relative;
+}
+</style>
+<div id="nav-detail"> {nav:h} </div>
+<div id="member-info">
+       {if:hasPendingPackages}
+               <div class="pending pendingMsg">
+                       The yellow colored items are pending approval from the website
+                       administrator.<br>Upon approval, your changes will be visible on
+                       the website.
+               </div>
+       {end:}
+       <h1>Packages</h1>
+       {uploadForm:h}
+       <div id="packageList" class="container">
+       {foreach:editForm,i}
+               {i:h}
+       {end:}
+       </div>
+</div><!-- /#member-info -->
diff --git a/Toolkit/Members/templates/editPhoto.tpl b/Toolkit/Members/templates/editPhoto.tpl
new file mode 100644 (file)
index 0000000..c71b76e
--- /dev/null
@@ -0,0 +1,24 @@
+{if:pending}
+<div id="photos_{photoId}" class="pending photoItem">
+{else:}
+<div id="photos_{photoId}" class="photoItem">
+{end:}
+       {form.javascript:h}
+       {form.outputHeader():h}
+               {form.hidden:h}
+               <div>
+                       <img class="thumb" alt="{img_alt:h}" src="{img_src:h}">
+               </div>
+               <div class="photoOptions">
+                       <i>{form.caption.label:h}</i>
+                       <div flexy:if="form.caption.error" class="req">{form.caption.error:h}</div>
+                       {form.caption.html:h}
+                       <div class="position">
+                               {form.pos.label:h}
+                               {form.pos.html:h}
+                       </div>
+                       {form.update.html:h}
+                       {form.delete.html:h}
+               </div>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/editPhotoGallery.tpl b/Toolkit/Members/templates/editPhotoGallery.tpl
new file mode 100644 (file)
index 0000000..0cae10a
--- /dev/null
@@ -0,0 +1,27 @@
+<style type="text/css">
+.ui-state-highlight {
+       border: 3px dashed #666666;
+       height: 1%;
+       margin-top: 1em;
+       overflow: hidden;
+       padding: 28px 18px 18px 28px;
+       position: relative;
+}
+</style>
+<div id="nav-detail"> {nav:h} </div>
+<div id="member-info">
+       {if:hasPendingPhotos}
+               <div class="pending pendingMsg">
+                       The yellow colored items are pending approval from the website
+                       administrator.<br>Upon approval, your changes will be visible on
+                       the website.
+               </div>
+       {end:}
+       <h1>Photos</h1>
+       {uploadForm:h}
+       <div id="photoList" class="container">
+       {foreach:editForms,i}
+               {i:h}
+       {end:}
+       </div>
+</div><!-- /#member-info -->
diff --git a/Toolkit/Members/templates/editRegion.tpl b/Toolkit/Members/templates/editRegion.tpl
new file mode 100644 (file)
index 0000000..5e35a1b
--- /dev/null
@@ -0,0 +1,36 @@
+<div id="member-info">
+       {form.javascript:h}
+       {form.outputHeader():h}
+       {form.hidden:h}
+       <!-- Error or Success Message -->
+       {validated():h}
+       <div id="mRow1">
+               <fieldset flexy:foreach="form.sections,sec" class="form">
+                       <legend>{sec.header}</legend>
+                       <table>
+                <tr flexy:foreach="sec.elements,elem">
+                    <!-- All regular elements go here. -->
+                    <td class="labelcell">
+                        <span flexy:if="elem.required" class="req">*</span>
+                        {if:elem.error}<span class="req">{end:}
+                            {elem.label}
+                        {if:elem.error}</span>{end:}
+                    </td>
+                    <td class="fieldcell">
+                        <span flexy:if="elem.error" class="req">
+                            {elem.error}
+                        </span>
+                        {elem.html:h}
+                    </td>
+                </tr>
+                       </table>
+               </fieldset>
+       </div>
+       <div class="submitArea">
+               <input type="submit" class="submit" value="Save Region">
+               {if:isEdit()}
+                       <input type="submit" name="delete" class="submit" value="Remove Region">
+               {end:}
+       </div>
+    </form>
+</div>
diff --git a/Toolkit/Members/templates/emailOwner.tpl b/Toolkit/Members/templates/emailOwner.tpl
new file mode 100644 (file)
index 0000000..641e3fc
--- /dev/null
@@ -0,0 +1,51 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+       <title>Member Record update</title>
+</head>
+<body>
+<center>
+<table cellspacing="0" cellpadding="0" bgcolor="#ffffff" border="0">
+               <tr>
+                       <td>
+                               <table cellspacing="1" cellpadding="15" border="0" bgcolor="#cccccc" width="450">
+                                       <tr bgcolor="#cccccc">
+                                               <td bgcolor="#ffffff">
+                                                       <font size="4" face="arial, sans-serif">
+                                                               <b>You have a pending member record</b>
+                                                       </font>
+                                                       <br><br>
+                                                       <font size="3" face="arial, sans-serif">
+                                                               <b>{member:h}</b> has updated their member record and the changes are waiting your approval.
+                                                       </font>
+                                                       <br><br>
+                                                       <font size="2" face="arial, sans-serif">
+                                                               Your approval is required to complete this process.
+                                                               <br>
+                                                               <a href="{url:h}admin/members.php?page=memberUpdates&module=listPendingMembers" target="_blank">Member administration area</a>
+                                                       </font>
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>
+               <tr>
+                       <td>
+                               <table cellspacing="0" cellpadding="15" border="0" width="450">
+                                       <tr>
+                                               <td bgcolor="#cccccc">
+                                                       <font size="1" face="arial, sans-serif">
+                                                               Please do not reply to this email, it will not go anywhere.
+                                                               <br><br>
+                                                               To ensure the delivery of these e-mails to your inbox, please add {email:h} to your e-mail Address Book or Safe List.
+                                                       </font>
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>                           
+       </table>
+</center>
+</body>
+</html>
diff --git a/Toolkit/Members/templates/exposureDetail.tpl b/Toolkit/Members/templates/exposureDetail.tpl
new file mode 100755 (executable)
index 0000000..eb83569
--- /dev/null
@@ -0,0 +1,35 @@
+{if:numberedSet}
+<style type="text/css">
+#exposure-detail th, #exposure-detail td {
+       padding: 5px 30px;
+       text-align: center;
+       font-size: 1.1em;
+       }
+#exposure-detail td:first-child {
+       text-align: left;
+       }
+#exposure-detail th {
+       background: #eee;
+       }
+#exposure-detail td {
+       background: rgba(252, 123, 21, 0.3);
+       }
+</style>
+<h3>{recordSet[0][member_name]}</h3>
+    <table id="exposure-detail">
+        <tr>
+            <th>Month</th>
+            <th>Listed</th>
+            <th>Details</th>
+            <th>Clicks</th>
+      </tr>
+        <tr flexy:foreach="recordSet,k,row">
+            <td>{row[month]}</td>
+            <td>{row[list]}</td>
+            <td>{row[detail]}</td>
+            <td>{row[click]}</td>
+      </tr>
+    </table>
+{else:}
+       <div class="NoMembers">No reports are available at this time.</div>
+{end:}
diff --git a/Toolkit/Members/templates/exposureList.tpl b/Toolkit/Members/templates/exposureList.tpl
new file mode 100755 (executable)
index 0000000..ceea35d
--- /dev/null
@@ -0,0 +1,43 @@
+<h1>Exposure Reports</h1>
+<div>
+    Exposure Reports - check the statistics being compiled that include:
+    <ul>
+               <li>Listed - number of times your member record was viewed in search result page</li>
+               <li>Details - number of time your member profile page was visited</li>
+               <li>Clicks - number of times your Web site address was clicked on</li>
+    </ul>
+</div>
+<hr>
+{exposureForm:h}
+{if:numberedSet}
+    <div class="results">{getResults(#Found %s Businesses in %s page(s)#):h}</div>
+{getPaging():h}
+<div flexy:if="letters" class="business-first-letter">
+       <div>Narrow result by letter:</div>
+       <a flexy:foreach="letters,k,v" class="{v[class]:h}" href="{v[url]:h}">{k}</a>
+</div>
+<p>Showing records {firstRecord} to {lastRecord}</p>
+    <table id="exposure-list">
+        <tr>
+            <th> Member Name </th>
+            <th> Listed </th>
+            <th> Details </th>
+            <th> Clicks </th>
+      </tr>
+        <tr flexy:foreach="recordSet,k,row">
+            <td>
+                               <a href="{row[directUrl]}">{row[member_name]:h}</a>
+            </td>
+            <td class="right"> {row[list]} </td>
+            <td class="right"> {row[detail]} </td>
+            <td class="right"> {row[click]} </td>
+      </tr>
+    </table>
+{getPaging():h}
+<div flexy:if="letters" class="business-first-letter">
+       <div>Narrow result by letter:</div>
+       <a flexy:foreach="letters,k,v" class="{v[class]:h}" href="{v[url]:h}">{k}</a>
+</div>
+{else:}
+       <div class="NoMembers">No Data For Found. Try another search.</div>
+{end:}
diff --git a/Toolkit/Members/templates/htmlEmailBody.tpl b/Toolkit/Members/templates/htmlEmailBody.tpl
new file mode 100644 (file)
index 0000000..36bdab2
--- /dev/null
@@ -0,0 +1,39 @@
+<table cellspacing="0" cellpadding="0" border="0" width="100%">
+       <tr>
+               <td align="center">
+                       <table cellspacing="0" cellpadding="0" border="0" width="550" bgcolor="#ffffff">
+                               <tr>
+                                       <td>
+                                               <a href="baseurl/"><img src="baseurl/assets/nHeader.jpg" width="550" height="114" alt="" style="border: 0; display: block;"></a>
+                                       </td>
+                               </tr>
+                               <tr>
+                                       <td>
+                                               <table cellspacing="15" cellpadding="0" border="0">
+                                                       <tr>
+                                                               <td align="left">
+                                                                       <font face="arial, helvetica, sans-serif" size="2">
+                                                                               {response:h}
+                                                                       </font>
+                                                               </td>
+                                                       </tr>
+                                                       <tr>
+                                                               <td>
+                                                                       <font face="arial, helvetica, sans-serif" size="1">
+                                                                               <hr>
+                                                                               You are receiving this message because you have expressed an interest in
+                                                                               receiving specials and information from {sitename}. If you do not
+                                                                               wish to receive future items of this nature, please reply to this e-mail
+                                                                               with the word "CANCEL" on the subject line. You will then be removed
+                                                                               from future mailings.<br>
+                                                                               <a href="mailto:{membersEnewsEmail}?subject=CANCEL">{membersEnewsEmail}</a><br>
+                                                                       </font>
+                                                               </td>
+                                                       </tr>
+                                               </table>
+                                       </td>
+                               </tr>
+                       </table>
+               </td>
+       </tr>
+</table>
diff --git a/Toolkit/Members/templates/listAmenities.tpl b/Toolkit/Members/templates/listAmenities.tpl
new file mode 100644 (file)
index 0000000..416ffef
--- /dev/null
@@ -0,0 +1,19 @@
+<table class="member-admin-table">
+       <thead>
+               <tr>
+                       <th></th>
+                       <th>Amenity Name</th>
+               </tr>
+       </thead>
+       <tr flexy:foreach="amenities,k,v">
+               <td>
+                       <div class="buttons">
+                               <a href="members.php?rt=Amenities&amp;ac=editAmenity&amp;id={k:h}">
+                                       <img alt="edit" src="glmappbaseurl/assets/icons/note_edit.png">
+                                       Edit
+                               </a>
+                       </div>
+               </td>
+               <td>{v:h}</td>
+       </tr>
+</table>
diff --git a/Toolkit/Members/templates/listCategories.tpl b/Toolkit/Members/templates/listCategories.tpl
new file mode 100644 (file)
index 0000000..4a357c5
--- /dev/null
@@ -0,0 +1,3 @@
+<div id="categoryTree">
+       {tree:h}
+</div>
diff --git a/Toolkit/Members/templates/listCities.tpl b/Toolkit/Members/templates/listCities.tpl
new file mode 100644 (file)
index 0000000..2785f6a
--- /dev/null
@@ -0,0 +1,21 @@
+<table class="member-admin-table">
+       <thead>
+               <tr>
+                       <th></th>
+                       <th>City Name</th>
+               </tr>
+       </thead>
+       <tbody>
+               <tr flexy:foreach="cities,k,v">
+                       <td>
+                               <div class="buttons">
+                                       <a href="members.php?rt=Cities&ac=editCity&id={k:h}">
+                                               <img src="glmappbaseurl/assets/icons/note_edit.png">
+                                               Edit
+                                       </a>
+                               </div>
+                       </td>
+                       <td>{v:h}</td>
+               </tr>
+       </tbody>
+</table>
diff --git a/Toolkit/Members/templates/listContacts.html b/Toolkit/Members/templates/listContacts.html
new file mode 100644 (file)
index 0000000..d1c8913
--- /dev/null
@@ -0,0 +1,18 @@
+{if:numberedSet}
+       <div flexy:foreach="recordSet,r" class="contactList">
+               <a class="remove" href="{baseUrl:h}admin/members.php?rt=Members&ac=editMember&tab=contacts&id={member}&cid={r[id]}&d=t">
+                       <img title="Delete Contact" width="16" height="16" alt="delete contact" src="glmappbaseurl/assets/icons/user_delete.png">
+               </a>
+               <h3>
+                       <a href="{baseUrl:h}admin/members.php?rt=Members&ac=editMember&tab=contacts&id={member}&cid={r[id]}">{r[fname]:h} {r[lname]:h}</a>
+               </h3>
+               <div flexy:if="r[title]" class="title">{r[title]:h}</div>
+               <a flexy:if="r[email]" class="email" href="mailto:{r[email]:h}">{r[email]:h}</a>
+               <div flexy:if="r[phone]" class="phone">{r[phone]:h}</div>
+               {if:r[send_mail]}
+                       <img title="Receives newsletters" width="16" height="16" class="mail" alt="can mail" src="glmappbaseurl/assets/icons/email_add.png">
+               {else:}
+                       <img title="Does not receive newsletters" width="16" height="16" class="mail" alt="no mail" src="glmappbaseurl/assets/icons/email_delete.png">
+               {end:}
+       </div>
+{end:}
diff --git a/Toolkit/Members/templates/listCounties.tpl b/Toolkit/Members/templates/listCounties.tpl
new file mode 100644 (file)
index 0000000..4badcbb
--- /dev/null
@@ -0,0 +1,21 @@
+<table class="member-admin-table">
+       <thead>
+               <tr>
+                       <th></th>
+                       <th>County Name</th>
+               </tr>
+       </thead>
+       <tbody>
+               <tr flexy:foreach="counties,k,v">
+                       <td>
+                               <div class="buttons">
+                                       <a href="members.php?rt=Counties&ac=editCounty&id={k:h}">
+                                               <img src="glmappbaseurl/assets/icons/note_edit.png">
+                                               Edit
+                                       </a>
+                               </div>
+                       </td>
+                       <td>{v:h}</td>
+               </tr>
+       </tbody>
+</table>
diff --git a/Toolkit/Members/templates/listHtmlEmails.tpl b/Toolkit/Members/templates/listHtmlEmails.tpl
new file mode 100644 (file)
index 0000000..86e69d8
--- /dev/null
@@ -0,0 +1,36 @@
+{if:newsletters}
+<table class="member-admin-table" style="width:700px;">
+       <thead>
+               <tr>
+                       <th></th>
+                       <th></th>
+                       <th>Subject</th>
+                       <th>Last Updated</th>
+               </tr>
+       </thead>
+       <tbody>
+               <tr flexy:foreach="newsletters,v">
+                       <td style="width:50px;">
+                               <div class="buttons">
+                                       <a href="members.php?rt=Newsletter&ac=editHtmlEmail&id={v[id]:h}">
+                                               <img src="glmappbaseurl/assets/icons/page_edit.png">
+                                               Edit
+                                       </a>
+                               </div>
+                       </td>
+                       <td style="width:50px;">
+                               <div class="buttons">
+                                       <a href="members.php?rt=Newsletter&ac=editHtmlEmail&preview=1&news_id={v[id]:h}">
+                                               <img src="glmappbaseurl/assets/icons/photo.png">
+                                               Preview
+                                       </a>
+                               </div>
+                       </td>
+                       <td>{v[subject]:h}</td>
+                       <td>{v[last_update]:h}</td>
+               </tr>
+       </tbody>
+</table>
+{else:}
+<h3>No {title:h} found!</h3>
+{end:}
diff --git a/Toolkit/Members/templates/listMembers.tpl b/Toolkit/Members/templates/listMembers.tpl
new file mode 100644 (file)
index 0000000..790f963
--- /dev/null
@@ -0,0 +1,34 @@
+{if:numberedSet}
+       {showLetters():h}
+
+    <div flexy:if="letters" class="business-first-letter">
+               <div>Narrow result by letter:</div>
+        <a flexy:foreach="letters,k,v" class="{v[class]:h}" href="{v[url]:h}">{k}</a>
+    </div>
+
+    <div class="results">{getResults(#Found %s records in %s page(s)#):h}</div>
+       {getPaging():h}
+       <p>Showing records {firstRecord} to {lastRecord}</p>
+       <div class="searchResult" flexy:foreach="recordSet,k,row">
+               <div id="floating">
+                       <div>
+                               <div>
+                                       <a class="remove" href="{row[del_url]:h}">
+                                               <img width="16" height="16" title="Delete record"
+                                                       src="glmappbaseurl/assets/icons/user_delete.png" alt="remove">
+                                       </a>
+                               </div>
+                       </div>
+               </div>
+               <h3>
+                       <a href="{row[member_id]:h}">{row[member_name]:h}</a>
+               </h3>
+               <div flexy:if="row[phone]" class="phone">P: {row[phone]:h}</div>
+               <a flexy:if="row[member_contact_email]" class="email" href="mailto:{row[member_contact_email]:h}">
+                       {row[member_contact_email]:h}
+               </a>
+       </div>
+       {getPaging():h}
+{else:}
+       <div class="NoMembers">No Records Found!</div>
+{end:}
diff --git a/Toolkit/Members/templates/listNewMembers.tpl b/Toolkit/Members/templates/listNewMembers.tpl
new file mode 100644 (file)
index 0000000..caa0a50
--- /dev/null
@@ -0,0 +1,20 @@
+{if:numberedSet}
+       {showLetters():h}
+       <div class="results">
+               {getResults(#Found %s new requests listed in %s page(s)#):h}
+       </div>
+       {getPaging():h}
+       <p>Showing records {firstRecord} to {lastRecord}</p>
+       <div class="searchResult" flexy:foreach="recordSet,k,row">
+               <h3>
+                       <a href="{row[member_id]:h}">{row[member_name]:h}</a>
+               </h3>
+               <div flexy:if="row[phone]" class="phone">P: {row[phone]:h}</div>
+               <a flexy:if="row[member_contact_email]" class="email" href="mailto:{row[member_contact_email]:h}">
+                       {row[member_contact_email]:h}
+               </a>
+       </div>
+       {getPaging():h}
+{else:}
+       <div class="NoMembers">No New Members Found!</div>
+{end:}
diff --git a/Toolkit/Members/templates/listPendingMembers.tpl b/Toolkit/Members/templates/listPendingMembers.tpl
new file mode 100644 (file)
index 0000000..bd37491
--- /dev/null
@@ -0,0 +1,17 @@
+{if:numberedSet}
+       {showLetters():h}
+       <div class="results">
+               {getResults(#Found %s pending records in %s page(s)#):h}
+       </div>
+       {getPaging():h}
+       <p>Showing records {firstRecord} to {lastRecord}</p>
+       <div class="searchResult" flexy:foreach="recordSet,k,row">
+               <h3>
+                       <a href="{row[member_id]:h}">{row[member_name]:h}</a>
+               </h3>
+               <a flexy:if="row[member_contact_email]" class="email"
+            href="mailto:{row[member_contact_email]:h}">{row[member_contact_email]:h}</a>
+       </div>
+{else:}
+       <div class="NoMembers">No Approvals Needed!</div>
+{end:}
diff --git a/Toolkit/Members/templates/listRegions.tpl b/Toolkit/Members/templates/listRegions.tpl
new file mode 100644 (file)
index 0000000..7d1cef2
--- /dev/null
@@ -0,0 +1,21 @@
+<table class="member-admin-table">
+       <thead>
+               <tr>
+                       <th></th>
+                       <th>Region Name</th>
+               </tr>
+       </thead>
+       <tbody>
+               <tr flexy:foreach="regions,k,v">
+                       <td>
+                               <div class="buttons">
+                                       <a href="members.php?rt=Regions&ac=editRegion&id={k:h}">
+                                               <img src="glmappbaseurl/assets/icons/note_edit.png">
+                                               Edit
+                                       </a>
+                               </div>
+                       </td>
+                       <td>{v:h}</td>
+               </tr>
+       </tbody>
+</table>
diff --git a/Toolkit/Members/templates/memberContactsList.tpl b/Toolkit/Members/templates/memberContactsList.tpl
new file mode 100644 (file)
index 0000000..6becd04
--- /dev/null
@@ -0,0 +1,46 @@
+<div id="contact">
+{memberContactSearchForm:h}
+</div>
+{memberSendForm:h}
+{if:numberedSet}
+       <div class="results">{getResults(#Found %s Contacts in %s pages#):h}</div>
+    <div class="paging">
+       {getPaging():h}
+    </div>
+       <p>Showing records {firstRecord} to {lastRecord}</p>
+    <table id="admin-list-table">
+        <tr>
+            <th>
+                &nbsp;
+            </th>
+            <th>
+                Member Name
+            </th>
+            <th>
+                First Name
+            </th>
+            <th>
+                Last Name
+            </th>
+      </tr>
+        <tr flexy:foreach="recordSet,k,row">
+            <td>
+            <a href="{row[directUrl]}">[Edit]</a>
+            </td>
+            <td>
+            {row[member_name]:h}
+            </td>
+            <td>
+            {row[fname]}
+            </td>
+            <td>
+            {row[lname]}
+            </td>
+      </tr>
+    </table>
+    <div class="paging">
+       {getPaging():h}
+    </div>
+{else:}
+       <div class="NoMembers">No Members Found!</div>
+{end:}
diff --git a/Toolkit/Members/templates/memberDetail.tpl b/Toolkit/Members/templates/memberDetail.tpl
new file mode 100644 (file)
index 0000000..19a5830
--- /dev/null
@@ -0,0 +1,221 @@
+<flexy:toJavascript
+flexy:prefix="glm_"
+base_url="base_url"
+trip_planner_id="trip_planner_id"
+catid="catid"
+>
+</flexy:toJavascript>
+<div id="member-detail">
+       <div id="image-box" style="height: 1%; overflow: hidden;">
+               <div flexy:if="logo" id="logo-spot">
+                       <img id="member-img-1"
+                               alt="Member Logo Image"
+                               src="{image_path:h}{logo:h}">
+               </div>
+       </div>
+
+       {memberSince:h}
+
+       <div class="vcard">
+               <h1 class="fn org">{member_name:h}</h1>
+               <div class="adr">
+                       <div flexy:if="hasMailingAddy" class="type">Street Address</div>
+                       <div class="street-address">{street:h}</div>
+                       <div>
+                               <span class="locality">{city:h}</span>,
+                               <span class="region" title="{state_name:h}">
+                                       {state_abbr:h}
+                               </span>
+                               <span class="postal-code">{zip:h}</span>
+                       </div>
+               </div><!-- /.adr -->
+               <div flexy:if="hasMailingAddy" class="adr">
+                       <div class="type">Mailing Address</div>
+                       <div class="street-address">{mailing_address:h}</div>
+                       <div>
+                               <span class="locality">{mailing_city:h}</span>,
+                               <span class="region" title="{mailing_state_name:h}">
+                                       {mailing_state_abbr:h}
+                               </span>
+                               <span class="postal-code">{mailing_zip:h}</span>
+                       </div>
+               </div><!-- /.adr -->
+               <div flexy:if="phone" class="tel">
+                       <span class="type">Phone</span>:
+                       <span class="value">{phone:h}</span>
+               </div>
+               <div flexy:if="toll_free" class="tel">
+                       <span class="type">Toll Free</span>:
+                       <span class="value">{toll_free:h}</span>
+               </div>
+               <div flexy:if="fax" class="tel">
+                       <span class="type">Fax</span>:
+                       <span class="value">{fax:h}</span>
+               </div>
+               <a flexy:if="email" class="email member-button" title="Email" href="mailto:{email:h}">Email</a>
+               <a flexy:if="url" title="Website" href="{url:h}" class="external member-button member-website" rel="{member_id}">Website</a>
+               <div id="google-div">
+                       <div class="customDialog">
+                               <form id="GDirs" action="http://maps.google.com/maps" method="get" target="_blank">
+                                       <h3>Get Driving Directions:</h3>
+                                       <div class="hiddenElements">
+                                               <input id="toaddress" type="text" name="saddr" size="40" value="Your Address City, State Zip">
+                                               <input type="hidden" name="daddr" value="{daddr:h}">
+                                               <input type="submit" value="Get Directions">
+                                       </div>
+                               </form>
+                       </div><!--/.customDialog -->
+               </div><!-- /#google-div -->
+       </div><!-- /.vcard -->
+
+       <div flexy:if="show_attributes" id="mColumn">
+               <h2 flexy:if="has_accommodations">Accommodations Info</h2>
+               <ul flexy:if="has_accommodations" id="mColumnAcc">
+                       <li>
+                               <ul>
+                                       <li flexy:if="year_round"> Open Year Round </li>
+                                       <li flexy:if="lists_number_of_rooms">
+{num_rooms:h} Rooms
+                                       </li>
+{if:does_online_reservations}
+                                       <li flexy:if="reservation_id">
+                                               <a href="{base_url:h}index.php?catid=50&amp;set_property={reservation_id:h}">Reservations</a>
+                                       </li>
+                                       <li flexy:if="reservation_url">
+                                               <a class="external" href="{reservation_url:h}">Reservations</a>
+                                       </li>
+{end:}
+                               </ul>
+                       </li>
+               </ul>
+               <h2 flexy:if="has_social_media">Social Media Links</h2>
+               <ul flexy:if="has_social_media" id="mColumnSoc">
+                       <li flexy:if="facebook" class="mFacebook">
+                               <a class="external" href="{facebook:h}">Facebook</a>
+                       </li>
+                       <li flexy:if="twitter" class="mTwitter">
+                               <a class="external" href="{twitter:h}">Twitter</a>
+                       </li>
+                       <li flexy:if="pinterest" class="mPinterest">
+                               <a class="external" href="{pinterest:h}">Pinterest</a>
+                       </li>
+                       <li flexy:if="linkedin" class="mLinkedIn">
+                               <a class="external" href="{linkedin:h}">LinkedIn</a>
+                       </li>
+                       <li flexy:if="youtube" class="mYouTube">
+                               <a class="external" href="{youtube:h}">YouTube</a>
+                       </li>
+                       <li flexy:if="blog" class="mBlog">
+                               <a class="external" href="{blog:h}">Blog</a>
+                       </li>
+                       <li flexy:if="myspace" class="mMyspace">
+                               <a class="external" href="{myspace:h}">MySpace</a>
+                       </li>
+               </ul>
+               <h2 flexy:if="ccards">Payment Types Accepted</h2>
+               <ul flexy:if="ccards">
+                       <li>
+                               <ul>
+                                       <li flexy:foreach="ccards,v">{v:h}</li>
+                               </ul>
+                       </li>
+               </ul>
+       </div><!-- /#mColumn -->
+
+{if:addToLink}
+       <a id="add-{member_id}" class="list-add-link" rel="{member_id}" flexy:if="plink" href="{plink:h}">
+               <img alt="Add to Your Travel List" class="list-add-link" rel="{member_id}" title="Add to Your Travel List" src="{base_url:h}assets/addto.gif" style="float: right; margin: 10px;clear: right;">
+               <img id="loading-planner" style="display: none;" src="{glm_base_url:h}gallery/loadingAnimation.gif">
+       </a>
+{else:}
+       <a href="{plink:h}" flexy:if="plink" class="list-view-link">
+               <img alt="View Your Travel List" title="View Your Travel List" src="{base_url:h}assets/viewTravelPlanner.gif" style="float: right; margin: 10px;clear: right;">
+       </a>
+{end:}
+
+       <div style="clear: left; text-align: justify;">{description:h}</div>
+
+       <div flexy:if="amenities" class="business-list-amenities">
+               <ul>
+                       <li flexy:foreach="amenities,v">{v:h}</li>
+               </ul>
+       </div>
+
+       <div flexy:if="files" id="member-files">
+               <h2>Files Available for Download</h2>
+               <a flexy:foreach="files,k,v" class="file-download pdf external" href="{v[href]:h}">{v[name]:h}</a>
+       </div>
+
+       <div flexy:if="packages" class="member-travel-item">
+               <h2>Packages</h2>
+               {foreach:packages,v}
+                       <h3 flexy:if="v[title]">{v[title]:h}</h3>
+                       {if:v[image]}
+                               <img alt="{v[image]:h}" src="{v[image]:h}">
+                       {end:}
+
+                       {if:v[description]}
+                               {v[description]:h}
+                       {end:}
+               {end:}
+       </div>
+
+       <div flexy:if="photos" id="photo-gallery">
+               <h2>Photo Gallery</h2>
+               <div flexy:foreach="photos,v" class="thumb {v[class]:h}">
+                       <a class="thickbox" title="{v[alt]:h}" rel="gallery-photos" href="{v[id]:h}">
+                               <img alt="{v[alt]:h}" src="{v[src]:h}">
+                       </a>
+               </div>
+       </div>
+
+       <div flexy:if="golf_info" class="member-golf-result">
+               <h2>Course Information</h2>
+               <table class="member-golf-stats">
+                       <tbody>
+                               <tr>
+                                       <th flexy:if="par">Par</th>
+                                       <th flexy:if="yardage">Yardage</th>
+                                       <th flexy:if="course_rating">Course Rating</th>
+                                       <th flexy:if="slope_rating">Slope Rating</th>
+                    <th flexy:if="holes9">9 Holes</th>
+                    <th flexy:if="holes18">18 Holes</th>
+                               </tr>
+                               <tr>
+                                       <td flexy:if="par">{par:h}</td>
+                                       <td flexy:if="yardage">{yardage:h}</td>
+                                       <td flexy:if="course_rating">{course_rating:h}</td>
+                                       <td flexy:if="slope_rating">{slope_rating:h}</td>
+                    <td flexy:if="holes9">{holes9:h}</td>
+                    <td flexy:if="holes18">{holes18:h}</td>
+                               </tr>
+                       </tbody>
+               </table>
+               <div class="member-golf-walking">
+                       <strong>Walking Course:</strong>
+                       {walking_course:h}
+               </div>
+       </div>
+
+       <div flexy:if="restaurant_info" class="member-restaurant-item">
+               <h2>Restaurant Information</h2>
+               <table>
+                       <tbody>
+                               <tr>
+                                       <th>Breakfast</th>
+                                       <th>Brunch</th>
+                                       <th>Lunch</th>
+                                       <th>Dinner</th>
+                                       <th>Alcohol</th>
+                               </tr>
+                               <tr>
+                                       <td>{breakfast:h}</td>
+                                       <td>{brunch:h}</td>
+                                       <td>{lunch:h}</td>
+                                       <td>{dinner:h}</td>
+                                       <td>{alcohol:h}</td>
+                               </tr>
+                       </tbody>
+               </table>
+       </div>
+</div>
diff --git a/Toolkit/Members/templates/memberNewsletter.tpl b/Toolkit/Members/templates/memberNewsletter.tpl
new file mode 100755 (executable)
index 0000000..7158eb9
--- /dev/null
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" 
+    content="text/html;charset=utf-8">
+</head>
+<body>
+<table cellspacing="0" cellpadding="0" border="0" width="100%">
+       <tr>
+               <td align="center">
+      <table cellspacing="0" cellpadding="0" 
+      border="0" width="550" bgcolor="#ffffff">
+       <tr>
+               <td>
+<a href="baseurl"><img src="baseurl/assets/nHeader.jpg" 
+      width="550" height="114" alt="" 
+      style="border: 0; display: block;"></a>
+         </td>
+       </tr>
+       <tr>
+        <td>
+<table cellspacing="15" cellpadding="0" border="0">
+                <tr>
+                    <td>
+<font face="arial, helvetica, sans-serif" size="2">
+                        {response}
+                        </font>
+                    </td>
+                </tr>
+                <tr>
+                 <td>
+<font face="arial, helvetica, sans-serif" size="1">
+                 <hr>
+                     {bailout}
+                     </font>
+                 </td>
+             </tr>
+            </table>
+        </td>
+    </tr>
+                       </table>
+               </td>
+       </tr>
+</table>                                                                       
+</body>
+</html>
diff --git a/Toolkit/Members/templates/memberSearchForm.tpl b/Toolkit/Members/templates/memberSearchForm.tpl
new file mode 100644 (file)
index 0000000..26f8eaa
--- /dev/null
@@ -0,0 +1,48 @@
+<div id="category-search" class="category-search-accommodations">
+       {form.javascript:h}
+    <flexy:toJSON RegionCats="regionCategories" />
+    <flexy:toJSON mainCats="mainCats" />
+       {form.outputHeader():h}
+       {form.hidden:h}
+               <fieldset>
+                       <legend>Search</legend>
+                       <ol>
+                               {foreach:form.sections,sec}
+                                       {foreach:sec.elements,elem}
+                                               {if:elem.isType(#group#)}
+                                                       {if:elem.isName(#amenities#)}
+                                                               <li id="amenities">
+                                                               {foreach:elem.elements,gitem}
+                                                                       <label class="amenity-label">
+                                                                               {gitem.html:h}{gitem.label:h}
+                                                                       </label>
+                                                               {end:}
+                                                               </li>
+                                                       {end:}
+                                               {else:}
+                                                       {if:elem.isName(#search_all_amenity#)}
+                                                               <li id="amenitySearchAll">
+                                                                       {elem.html:h}{elem.label:h}
+                                                               </li>
+                                                       {else:}
+                                                               <li>
+                                                                       <label for="{elem.name:h}">{elem.label:h}</label>
+                                                                       {elem.html:h}
+                                                               </li>
+                                                       {end:}
+                                               {end:}
+                                       {end:}
+                               {end:}
+                               <li flexy:if="businessAmenities" id="amenities">
+                                       <label flexy:foreach="businessAmenities,k,v" class="amenity-label">
+                                               <input type="checkbox" value="{v:h}" name="amenities[]">
+                                               {k:h}
+                                       </label>
+                               </li>
+                               <li>
+                                       <input class="submit" type="submit" value="Search">
+                               </li>
+                       </ol>
+               </fieldset>
+       </form>
+</div>
diff --git a/Toolkit/Members/templates/membersList.tpl b/Toolkit/Members/templates/membersList.tpl
new file mode 100644 (file)
index 0000000..a3d0a31
--- /dev/null
@@ -0,0 +1,90 @@
+<div flexy:if="member_search_form">{member_search_form:h}</div>
+       <flexy:toJavascript
+       flexy:prefix="glm_"
+       base_url="base_url"
+       trip_planner_id="trip_planner_id"
+       catid="catid"
+    searchMapIconActive="searchMapIconActive"
+       >
+</flexy:toJavascript>
+<div flexy:if="letters" class="business-first-letter">
+       <div>Narrow result by letter:</div>
+       <a flexy:foreach="letters,k,v" class="{v[class]:h}" href="{v[url]:h}">{k}</a>
+</div>
+
+{if:numberedSet}
+<div class="results">{getResults(#Found %s Businesses in %s page(s)#):h}</div>
+{getPaging():h}
+<p>Showing records {firstRecord} to {lastRecord}</p>
+
+<div flexy:foreach="recordSet,k,row" class="search-result-item vcard">
+
+       <div class="memberSR">
+
+{if:row[addToLink]}
+               <a id="add-{row[member_id]}" class="list-add-link" rel="{row[member_id]}" flexy:if="row[plink]" title="Add to Your Travel List" href="{row[plink]:h}">
+                       <img alt="Add to Your Travel List" src="baseurl/assets/addto.gif">
+               </a>
+{else:}
+               <a class="list-view-link" flexy:if="row[plink]" title="View Your Travel List" href="{row[plink]:h}">
+                       <img alt="View Your Travel List" src="baseurl/assets/viewTravelPlanner.gif">
+               </a>
+{end:}
+{if:row[logo]}
+               <img class="search-result-img" alt="{row[logo]}" src="{row[logo]}">
+{end:}
+       </div><!-- /.memberSR -->
+               <h2 class="fn org"><a title="More Info" href="{row[url]:h}">{row[member_name]:h}</a></h2>
+               <div class="search-result-item-info">
+    {if:row[map_icon]}
+        <div class="map-link" rel="{row[map_icon][id]}">
+                       <img class="search-result-map-img" src="{row[map_icon][icon]:h}">
+        </div>
+    {end:}
+                       <div class="search-result-location adr">
+                               <div class="street-address">{row[street]:h}</div>
+                               <span class="locality">{row[city]:h}</span>,
+                               <span class="region" title="{row[state]:h}">{row[state_abbr]:h}</span>
+                               <span class="postal-code">{row[zip]:h}</span>
+                               <div flexy:if="row[phone]" class="search-result-phones">
+                                       <div class="tel">Phone: {row[phone]:h}</div>
+                               </div>
+                               <div style="height: 1%; overflow: hidden; margin-top: 0.5em;">
+                                       <div flexy:if="row[member_contact_email]" class="search-result-email" style="float: left; margin-right: 15px;">
+                                               <a title="Email" href="mailto:{row[member_contact_email]:h}">Email</a>
+                                       </div>
+                                       <div flexy:if="row[website]" class="search-result-website" style="float: left; margin-right: 15px;">
+                                               <a target="_blank" title="Website" href="{row[website]:h}" rel="{row[member_id]}" class="member-website">Website</a>
+                                       </div>
+                                       <div flexy:if="row[address]" class="search-result-directions" style="float: left; margin-right: 15px;">
+                                               <a target="_blank" title="Driving Directions" href="{row[address]:h}">Driving Directions</a>
+                                       </div>
+                               </div>
+                       </div>
+
+
+
+
+                       <div flexy:if="row[has_hotel_info]" class="member-hotel-result">
+                               <a flexy:if="row[reservation_id]"
+                                       href="{base_url:h}index.php?catid=50&set_property={row[reservation_id]:h}">
+                                       <img alt="Online Reservations"
+                                               src="baseurl/assets/buttons/reservations.gif">
+                               </a>
+                               {if:row[num_rooms]}
+                                       Number of Rooms: {row[num_rooms]:h}
+                               {end:}
+                               <br>
+                               Open Year Round: {row[year_round]:h}
+                       </div>
+               </div>
+       </div>
+
+{getPaging():h}
+<div flexy:if="letters" class="business-first-letter">
+       <div>Narrow result by letter:</div>
+       <a flexy:foreach="letters,k,v" class="{v[class]:h}" href="{v[url]:h}">{k}</a>
+</div>
+{else:}
+<div class="NoMembers">No Members matched your search criteria!</div>
+{end:}
diff --git a/Toolkit/Members/templates/newMemberApproval.tpl b/Toolkit/Members/templates/newMemberApproval.tpl
new file mode 100755 (executable)
index 0000000..e05ca6d
--- /dev/null
@@ -0,0 +1,40 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+       <title>Registration Complete - {client_name:h}</title>
+</head>
+<body>
+<center>
+<table cellspacing="0" cellpadding="0" bgcolor="#ffffff" border="0">
+               <tr>
+                       <td>
+                               <table cellspacing="1" cellpadding="15" border="0" bgcolor="#cccccc" width="450">
+                                       <tr bgcolor="#cccccc">
+                                               <td bgcolor="#ffffff">
+                                                       <font size="3" face="arial, sans-serif">
+                               <b>Your registration is complete</b>
+               </font>
+                                                       <br><br>
+               <font size="2" face="arial, sans-serif">
+                                                               Dear {first_name:h},<br>
+                                                               Your registration is approved. Below is the username and password you selected.
+                                                               <br><br>
+                                                               Username: {member_login:h}
+                                                               <br>
+                                                               Password: {member_passwd:h}
+                                                               <br><br>
+                                                               Use this to <a href="{base_url:h}index.php?catid={member_category}" target="_blank">log into your members area</a>.
+                                                               <br><br>
+                                                               Sincerely,<br>
+                                                               {client_name:h}
+                                                       </font>
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>                           
+       </table>
+</center>
+</body>
+</html>
diff --git a/Toolkit/Members/templates/newMemberDenial.tpl b/Toolkit/Members/templates/newMemberDenial.tpl
new file mode 100755 (executable)
index 0000000..fc060c8
--- /dev/null
@@ -0,0 +1,36 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+       <title>Registration not completed - {client_name:h}</title>
+</head>
+<body>
+<center>
+<table cellspacing="0" cellpadding="0" bgcolor="#ffffff" border="0">
+               <tr>
+                       <td>
+                               <table cellspacing="1" cellpadding="15" border="0" bgcolor="#cccccc" width="450">
+                                       <tr bgcolor="#cccccc">
+                                               <td bgcolor="#ffffff">
+                                                       <font size="3" face="arial, sans-serif">
+                               <b>We were unable to complete your registration</b>
+               </font>
+                                                       <br><br>
+               <font size="2" face="arial, sans-serif">
+                                                               Dear {first_name:h},<br>
+                                                               Unfortunately, we were not able to complete your registration.
+                                                               <br><br>
+                                                               If you think there has been an error, please contact us.
+                                                               <br><br>
+                                                               Sincerely,<br>
+                                                               {client_name:h}
+                                                       </font>
+                                               </td>
+                                       </tr>
+                               </table>
+                       </td>
+               </tr>                           
+       </table>
+</center>
+</body>
+</html>
diff --git a/Toolkit/Members/templates/previewHtmlEmail.tpl b/Toolkit/Members/templates/previewHtmlEmail.tpl
new file mode 100644 (file)
index 0000000..6cea562
--- /dev/null
@@ -0,0 +1,47 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+</head>
+<body>
+<table cellspacing="0" cellpadding="0" border="0" width="100%">
+       <tr>
+               <td align="center">
+                       <table cellspacing="0" cellpadding="0" border="0" width="550" bgcolor="#ffffff">
+                               <tr>
+                                       <td>
+                                               <a href="baseurl/"><img src="baseurl/assets/nHeader.jpg" width="550" height="114" alt="" style="border: 0; display: block;"></a>
+                                       </td>
+                               </tr>
+                               <tr>
+                                       <td>
+                                               <table cellspacing="15" cellpadding="0" border="0">
+                                                       <tr>
+                                                               <td>
+                                                                       <font face="arial, helvetica, sans-serif" size="2">
+                                                                               {response:h}
+                                                                       </font>
+                                                               </td>
+                                                       </tr>
+                                                       <tr>
+                                                               <td>
+                                                                       <font face="arial, helvetica, sans-serif" size="1">
+                                                                               <hr>
+                                                                               You are receiving this message because you have expressed an interest in
+                                                                               receiving specials and information from {sitename}. If you do not
+                                                                               wish to receive future items of this nature, please reply to this e-mail
+                                                                               with the word "CANCEL" on the subject line. You will then be removed
+                                                                               from future mailings.<br>
+                                                                               <a href="mailto:{membersEnewsEmail}?subject=CANCEL">{membersEnewsEmail}</a><br>
+                                                                       </font>
+                                                               </td>
+                                                       </tr>
+                                               </table>
+                                       </td>
+                               </tr>
+                       </table>
+               </td>
+       </tr>
+</table>
+</body>
+</html>
diff --git a/Toolkit/Members/templates/previewNewsletterWrapper.html b/Toolkit/Members/templates/previewNewsletterWrapper.html
new file mode 100644 (file)
index 0000000..9f3d9e8
--- /dev/null
@@ -0,0 +1,2 @@
+<iframe height="600px" width="730px" src="{src:h}">
+</iframe>
diff --git a/Toolkit/Members/templates/settings.html b/Toolkit/Members/templates/settings.html
new file mode 100644 (file)
index 0000000..d9e1245
--- /dev/null
@@ -0,0 +1 @@
+{nav:h}
diff --git a/Toolkit/Members/templates/tripPlannerList.tpl b/Toolkit/Members/templates/tripPlannerList.tpl
new file mode 100644 (file)
index 0000000..4f73af7
--- /dev/null
@@ -0,0 +1,62 @@
+{if:numberedSet}
+<div id="accountBox" class="tpBox">
+  
+       <p flexy:if="isLoggedIn" id="loggedInAs">
+           Logged in as {username}
+               <a href="{logoutUrl:h}" style="display: block; margin-top: 6px;">Log Out</a>
+       </p>
+       
+       <form id="plannerLogin" action="{loginUrl}" method="post" flexy:if="!isLoggedIn">
+               <h2>Sign In</h2>
+               <p id="plannerUser">Email: <input name="username" type="text"></p>
+               <p id="plannerP">Password: <input name="password" type="password"></p>
+               <p id="plannerSubmit"><input type="submit" class="submit" value="Log In"></p>
+         <p flexy:if="loginStat">{loginStat}</p>
+               <p id="plannerForgot"><a href="{forgotUrl:h}">Forgot your Password?</a></p>
+       </form>
+       
+       <div id="plannerAcc" flexy:if="!isLoggedIn">
+               <h2>If you do not have an account</h2>
+               <a href="{accountUrl:h}" id="plannerNew">Create an account</a>
+               <p>By creating an account, you'll be able to save your list for later.</p>
+       </div>
+               
+       
+<ul id="plannerNav">
+       <li id="pN1"><a href="{requestUrl:h}">Get more info</a></li>
+       <li id="pN2"><a href="#" onclick="window.print()">Print this list</a></li>
+       <li id="pN3"><a class="thickbox" href="baseurl/Toolkit/Members/TripPlanner/tripPlannerMap.php?TB_iframe=true&height=550&width=800">View Map</a></li>
+       <li id="pN4"><a class="thickbox" href="baseurl/Toolkit/Members/TripPlanner/helpme.html?TB_iframe=true">Help</a></li>
+</ul></div>
+
+
+
+<div id="plannerList" style="padding: 6px 0;">
+
+<?php $i = 0;?>
+{foreach:recordSet,k,row}
+<div class="plannerItem">
+       <div id="tpBreadcrumbs">{row[breadCrumbs]:h}</div>
+       <h2>{row[member_name]:h}</h2>
+  <div class="plannerAddress">
+       <p>{row[street]:h}</p>
+    <p>{row[city]:h}, {row[state_abbr]:h} {row[zip]:h}</p>
+    <p flexy:if="row[time_allocated]" class="plannerTime">Time you should plan to spend here: {row[time_allocated]}</p>
+       </div><!-- /.plannerAddress -->
+  <div class="plannerInfo">
+       <p flexy:if="row[phone]">Phone: {row[phone]:h}</p>
+    <p flexy:if="row[member_contact_email]">Email: <a href="mailto:{row[member_contact_email]:h}">{row[member_contact_email]:h}</a></p>
+    <p flexy:if="row[url]"><a href="{row[url]:h}">Website</a></p>
+               <a href="{row[deleteUrl]:h}" class="plannerRemove" title="Remove from list">Remove</a>
+  </div><!-- /.planenrInfo -->
+</div><!-- /.plannerItem -->
+<?php
+if (++$i == 8) {
+$i = 0;
+echo '<div class="page-break"></div>';
+}
+?>
+{end:}
+
+</div><!-- /#plannerList -->
+{end:}
diff --git a/Toolkit/Members/templates/tripPlannerNoList.tpl b/Toolkit/Members/templates/tripPlannerNoList.tpl
new file mode 100644 (file)
index 0000000..a768739
--- /dev/null
@@ -0,0 +1,48 @@
+<p>
+This section lets you create your own online itinerary. As you find items on this website that may be of interest to you, simply click the "Add to 
+Travel Planner" icon. Each item will then get added to your list. Once you have 
+completed adding items to your planner list, you may take the following actions:</p>
+
+<ol>
+       <li><strong>Request Info</strong><br>
+This will send an email directly to each individual business using our "Send Me More Information" 
+form. For the items you have added to your list that do not have an 
+email, we will give you their phone number. </li>
+
+<li><strong>Print This List</strong><br>
+Prints the list to your printer, if you have one.</li>
+
+<li><strong>View Map</strong><br>
+This will display your itinerary on a Map, also allowing you to retrieve driving directions.
+</li>
+
+<li>
+<strong>Save your Trip Planner</strong><br>
+Creates an account with this website so you can access your itinerary later.
+</li>
+
+</ol>
+
+<div id="accountBox" class="tpBox tpBoxNoList">
+
+       <p flexy:if="isLoggedIn" id="loggedInAs">
+           Logged in as {username}
+               <a href="{logoutUrl:h}" style="display: block; margin-top: 6px;">Log Out</a>
+       </p>
+       
+       <form id="plannerLogin" action="{loginUrl}" method="post" flexy:if="!isLoggedIn">
+               <h2>Sign In</h2>
+               <p id="plannerUser">Email: <input name="username" type="text"></p>
+               <p id="plannerP">Password: <input name="password" type="password"></p>
+               <p id="plannerSubmit"><input type="submit" class="submit" value="Log In"></p>
+         <p flexy:if="loginStat">{loginStat}</p>
+               <p id="plannerForgot"><a href="{forgotUrl:h}">Forgot your Password?</a></p>
+       </form>
+
+       
+       <div id="plannerAcc" flexy:if="!isLoggedIn">
+               <h2>If you do not have an account</h2>
+               <a href="{accountUrl:h}" id="plannerNew">Create an account</a>
+               <p>By creating an account, you'll be able to save your list for later.</p>
+       </div>
+</div>
diff --git a/Toolkit/Members/templates/userSearchForm.html b/Toolkit/Members/templates/userSearchForm.html
new file mode 100644 (file)
index 0000000..cb4e47e
--- /dev/null
@@ -0,0 +1,100 @@
+<style>
+    fieldset #glm-member-search {width:100%;}
+    fieldset #glm-member-search label {width:25%;text-align: right;}
+    .fieldcontain {display:block;width:100%;clear:both;}
+    .glm-chbx-label {width:250px;text-align: left;float:left;display:inline;}
+    .glm-chbx {width:580px;text-align: left;display:block;clear:right;float:right;}
+    .fieldHdr {width: 120px;float: left;display: block;text-align: right;}
+</style>
+<div
+    id="category-search"
+    class="category-search-accommodations">
+    <form
+        flexy:ignore="yes"
+        action="{formURL:h}"
+        method="post">
+        <input type="hidden" name="search" value="1">
+               <fieldset id="glm-member-search">
+                       <legend>Search for Trails</legend>
+            <div class="fieldcontain">
+                <label class="fieldHdr">Trail Name</label>
+                <input
+                    type="search"
+                    name="member_name"
+                    placeholder="trail name"
+                    value="{_POST[member_name]}">
+            </div>
+            <div flexy:if="activities" class="fieldcontain">
+                <label class="fieldHdr">Activities</label>
+                <div class="glm-chbx">
+                {foreach:activities,id,name}
+                <label for="chbx-{id:h}" class="glm-chbx-label">
+                  <?php
+                  echo '<input
+                    id="chbx-'.$id.'"
+                    type="checkbox"
+                    name="activity[]"
+                    value="'.$id.'"
+                    '.((isset($_POST['activity'])
+                    && is_array($_POST['activity'])
+                    && in_array($id, $_POST['activity']))?'checked':'').'
+                  >';
+                  ?>
+                  {name}
+                </label>
+                {end:}
+                </div>
+            </div>
+            <div flexy:if="parks" class="fieldcontain">
+                <label class="fieldHdr">Parks</label>
+                <div class="glm-chbx">
+                {foreach:parks,id,name}
+                <label for="chbx-{id:h}" class="glm-chbx-label">
+                  <?php
+                  echo '<input
+                    id="chbx-'.$id.'"
+                    type="checkbox"
+                    name="park[]"
+                    value="'.$id.'"
+                    '.((isset($_POST['park'])
+                    && is_array($_POST['park'])
+                    && in_array($id, $_POST['park']))?'checked':'').'
+                  >';
+                  ?>
+                  {name}
+                </label>
+                {end:}
+                </div>
+            </div>
+            <div flexy:if="regions" class="fieldcontain">
+                <label class="fieldHdr">Regions</label>
+                <select name="region">
+                    <option value="">-- Select --</option>
+                    {foreach:regions,id,name}
+                    <?php
+                    echo '<option value="'.$id.'"
+                        '.(($id == $_POST['region'])?'selected':'')
+                        .'>'.$name.'</option>';
+                    ?>
+                    {end:}
+                </select>
+            </div>
+            <div flexy:if="counties" class="fieldcontain">
+                <label class="fieldHdr">Counties</label>
+                <select name="county">
+                    <option value="">-- Select --</option>
+                    {foreach:counties,id,name}
+                    <?php
+                    echo '<option value="'.$id.'"
+                        '.(($id == $_POST['county'])?'selected':'')
+                        .'>'.$name.'</option>';
+                    ?>
+                    {end:}
+                </select>
+            </div>
+            <div class="fieldcontain">
+                <input class="submit" type="submit" value="Search">
+            </div>
+               </fieldset>
+       </form>
+</div>
\ No newline at end of file
diff --git a/Toolkit/Membersonly.php b/Toolkit/Membersonly.php
new file mode 100644 (file)
index 0000000..01cb174
--- /dev/null
@@ -0,0 +1,398 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category MembersDB
+ * @package  Toolkit_Members
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: Membersonly.php,v 1.39 2010/08/15 19:32:01 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+define('MEMBERS_ONLY_AREA_ON', true);
+
+/**
+ * Base class for the memberdb
+ *
+ * @category  MembersDB
+ * @package   Toolkit_Members
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ */
+class Toolkit_Membersonly
+{
+       //      {{{     properties
+
+    /**
+     * Strict pending for member updates
+     */
+       const STRICT_PENDING = true;
+
+    /**
+     * Table that holds the member update requests
+     */
+       const PENDING_TABLE = 'member_updates';
+
+       //      }}}
+
+       //      {{{     __construct()
+
+       /**
+        * Constructor
+        *
+        * @access      public
+        */
+       public function __construct()
+       {
+       }
+
+       //      }}}
+
+    public static function checkMemberExists(PDO $dbh, $memberId)
+    {
+        try {
+            $sql = "
+            SELECT count(member_id)
+              FROM member
+             WHERE member_id = :member_id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(
+                ':member_id',
+                $memberId,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+       //      {{{ toHtml()
+
+       /**
+        * Determine which form to show to the user
+        *
+        * When editing a member the (a)ction in the URL controls
+        * which form is displayed to the user. Member Id's from
+        * the database should be passed along as the ID in the $_GET array.
+        *
+        * @param PDO     $dbh Database handler
+        * @param integer $mid member id to use for controller
+        *
+        * @return string HTML page of members only control forms
+        * @access public
+        */
+       public function toHtml(PDO $dbh, $mid)
+       {
+               if (!ctype_digit((string)$mid)) {
+                       throw new InvalidArgumentException(
+                               "\$mid must be an integer - `$mid` given"
+                       );
+               }
+
+               $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Members/css/member-admin.css';
+
+        //  application configuration
+        $conf = new Config;
+        $root = $conf->parseConfig(
+                       BASE . 'Toolkit/Members/config.ini', 'IniFile'
+               );
+
+               $nav = new Toolkit_Members_RecordNavigation($root);
+               $nav->setupUserNavStructure();
+
+        $tplOpts =  Toolkit_Members::getFlexyOptions();
+        $tEngine = new HTML_Template_Flexy($tplOpts);
+
+               switch ($_GET['tab']) {
+               case 'contacts' :
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-contacts.js';
+
+                       $mc = new Toolkit_Members_EditMemberOnlyContacts(
+                               $dbh,
+                'edit_contacts',
+                'post',
+                null,
+                null,
+                null,
+                true
+                       );
+                       if (   isset($_GET['d'])
+                               && $_GET['d'] == 't'
+                               && $contactId = filter_input(INPUT_GET, 'cid', FILTER_VALIDATE_INT)
+                       ) {
+                $mc->removeContact($contactId, $_GET['id']);
+            }
+            $mc->setConfig($root);
+            $mc->configureForm();
+                       $out = $mc->toHtml();
+                       break;
+
+               case 'files' :
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-files.js';
+                       $mf = new Toolkit_Members_EditMemberOnlyFile($dbh, 'edit_files');
+            $mf->setConfig($root);
+            $mf->configureForm();
+                       $out = $mf->toHtml();
+                       break;
+
+               case 'amenities' :
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-amenities.js';
+
+                       $ma = new Toolkit_Members_EditMemberOnlyAmenities(
+                               $dbh,
+                'edit_amenities',
+                'post',
+                null,
+                null,
+                null,
+                true
+                       );
+            $ma->setConfig($root);
+            $ma->configureForm();
+                       $out = $ma->toHtml();
+                       break;
+
+               case 'packages' :
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-packages.js';
+
+            $mp = new Toolkit_Members_EditPackages($dbh, $tEngine);
+            $mp->setupPage($root);
+            $out = $mp->getPage($nav);
+                       break;
+
+               case 'photos' :
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member-photos.js';
+
+            //  Object to use when rendering the page template
+            $page = new stdClass();
+            //  Page navigation
+            $page->nav = $nav->getPageNav();
+
+            //  Linked List of member photos
+            $linkedList = new Toolkit_Members_Photos(null, $mid);
+            $linkedList->createMemberList(
+                               $dbh,
+                               $root
+                       );
+            //  Member Object to get calculate attributes about a member
+            $member = new Toolkit_Members_Member(
+                               $dbh,
+                               $root
+                       );
+            //  Server side caching
+            $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+            //  Image server for processing uploaded images
+            $is = new Toolkit_Image_Server();
+
+            if ($member->canAddPhotos($linkedList, $root)) {
+                $aForm = new Toolkit_Members_AddPhoto(
+                                       $dbh,
+                    'new_member_photo',
+                    'post',
+                    BASE_URL . "members-only-area/?rt=EditProfile&tab=photos",
+                    '',
+                    null,
+                    true
+                );
+                $aForm->configureForm($root);
+                $page->uploadForm = $aForm->toHtml(
+                    $tEngine,
+                    $cache,
+                    $root,
+                    $is,
+                    $linkedList
+                );
+            }
+
+            if ($member->hasUploadedPhotos($linkedList)) {
+                $editForms = array();
+                $linkedList->rewind();
+
+                foreach ($linkedList as $i) {
+                    $id = $i->getId();
+                    $eForm = new Toolkit_Members_EditPhoto(
+                                               $dbh,
+                        $linkedList,
+                        "edit_member_photo_$id",
+                        'post',
+                        null,
+                        null,
+                        array('id' => $id),
+                        true
+                    );
+                    $eForm->configureForm($root);
+                    $page->editForms[$id] = $eForm->toHtml(
+                        $tEngine,
+                        $cache,
+                        $is,
+                        $root
+                    );
+                }
+            }
+
+            //  get reference to [photos] section of config file
+            $config = $root->getItem('section', 'photos');
+            $template = $config->getItem('directive', 'editGalleryTemplate');
+
+            $tEngine->compile($template->getContent());
+            $out = $tEngine->bufferedOutputObject($page);
+                       break;
+
+               case 'info' :
+               default :
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+                       $GLOBALS['bottomScripts'][]
+                               = BASE_URL . 'Toolkit/Members/libjs/edit-member.js';
+                       $GLOBALS['bottomScripts'][]
+                               = GLM_APP_BASE_URL . 'gallery/thickbox-3.1.1.js';
+                       $GLOBALS['styleSheets'][]
+                               = GLM_APP_BASE_URL . 'gallery/thickbox.css';
+
+                       $mr = new Toolkit_Members_EditMemberOnlyInfo(
+                               $dbh,
+                'edit_member',
+                'post',
+                null,
+                null,
+                null,
+                true
+                       );
+
+            $mr->setStates(
+                               Toolkit_Common::getStates($dbh)
+                       );
+            $mr->setCities(
+                               Toolkit_Common::getCities($dbh)
+                       );
+            $mr->setConfig($root);
+            $mr->configureForm();
+                       $mr->useCluetip();
+                       $out = $mr->toHtml();
+                       break;
+               }
+
+               return $out;
+       }
+
+       //      }}}
+
+       //      {{{     show()
+
+    /**
+        * Call the toHtml function and echo out the results
+        *
+        * @param PDO     $dbh Database handler
+        * @param integer $mid member id to use for controller
+     *
+     * @return void
+     * @access public
+     */
+       public function show(PDO $dbh, $mid)
+       {
+               echo $this->toHtml($dbh, $mid);
+       }
+
+       //      }}}
+
+       //      {{{     updateNotificationEmail()
+
+       /**
+        * Emails the owner and anyone else who wants to be advised of updates
+        *
+        * A false value in the MEMBER_RECORD_UPDATES_ADVISOR will cause no email
+        * to be sent. all secondary advisees listed in the constructor are carbon
+        * copied in the email.
+        *
+        * Emails are sent out in both HTML and TXT forms.
+     *
+     * @param Config_Container    $c       Configuration object
+     * @param HTML_Template_Flexy $tEngine Flexy Templating Engine
+     * @param Mail                $mail    Mail object
+        *
+     * @return boolean result of mailing
+        * @access protected
+        * @since  Method available since Release 1.5
+        */
+       static public function updateNotificationEmail(
+        Config_Container $c,
+        HTML_Template_Flexy $tEngine,
+        Mail $mail
+    ) {
+               if (MEMBER_RECORD_UPDATES_ADVISOR === false) {
+                       return;
+               } else {
+                       try {
+                               $sql = "
+                    SELECT member_name
+                      FROM member
+                     WHERE member_id = :member_id";
+                               $dbh = Toolkit_Database::getInstance();
+                               $stmt = $dbh->prepare($sql);
+                               $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT);
+                               $stmt->execute();
+                               $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                               $memberName = $row['member_name'];
+                       } catch (PDOException $e) {
+                               return Toolkit_Common::handleError($e);
+                       }
+                       $page     = new StdClass;
+
+                       $page->member   = $memberName;
+                       $page->url      = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : BASE_URL;
+                       $page->email    = DO_NOT_REPLY_EMAIL;
+                       $page->siteName = SITENAME;
+                       $page->link     = '<a target="_blank"  href="'.BASE_URL.'pending-member/'.$_GET['id'].'/">link</a>';
+
+                       $tEngine->compile('emailOwner.tpl');
+                       //      Merge the compiled template with the $page object.
+                       $htmlMsg = $tEngine->bufferedOutputObject($page);
+
+                       $msg = "
+                               <h3>$memberName</h3>
+                               <p>
+                                       Has updated thier business record and is now in a pending
+                                       state. To approve / reject thier changes you can either log
+                                       into your {$page->siteName} admin area or follow this
+                                       {$page->link}
+                               </p>";
+                       $crlf     = "\n";
+                       $mimeMail = new Mail_mime($crlf);
+            $from = ereg_replace("[^A-Za-z ]", "", SITENAME) . ' <' . DO_NOT_REPLY_EMAIL . '>';
+                       $mimeMail->setFrom($from);
+                       $mimeMail->setSubject(Toolkit_Members_Admin_Controller::$listingType['singular'] . 'Record Update');
+                       $mimeMail->setHTMLBody($htmlMsg);
+                       $mimeMail->setTXTBody($msg);
+
+                       $body    = $mimeMail->get();
+                       $headers = $mimeMail->headers($hdrs);
+
+                       $res = $mail->send(MEMBER_RECORD_UPDATES_ADVISOR, $headers, $body);
+                       if (PEAR::isError($res)) {
+                               return Toolkit_Common::handleError($res);
+                       } else {
+                               return $res;
+                       }
+               }
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/Tree.php b/Toolkit/Tree.php
new file mode 100644 (file)
index 0000000..5af1553
--- /dev/null
@@ -0,0 +1,145 @@
+<?php
+//     vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * DB tree structures
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Toolkit_Tree
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license     http://www.gaslightmedia.com Gaslightmedia
+ * @release     CVS: $Id: Tree.php,v 1.4 2009/06/18 14:12:50 jamie Exp $
+ * @link        http://demo.gaslightmedia.com
+ */
+
+/**
+ * Create tree structures of database entries
+ *
+ * Base class used to setup tree objects that will render
+ * database structures into iterable PHP objects.
+ *
+ * @category  Toolkit
+ * @package      Toolkit_Tree
+ * @author       Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2008 Gaslight Media
+ * @license      http://www.gaslightmedia.com Gaslightmedia
+ * @link         http://demo.gaslightmedia.com
+ */
+abstract class Toolkit_Tree
+{
+       //      {{{ properties
+
+       /**
+        * Database ID of tuple
+        *
+        * @var int
+        * @access public
+        */
+       public $catid = 0;
+
+       /**
+        * Name of object
+        *
+        * @var string
+        * @access public
+        */
+       public $category;
+
+       /**
+        * Children of object
+        *
+        * @var array
+        * @access public
+        */
+    public $children = array();
+
+       /**
+        * Parent of this category
+        *
+        * @var array
+        * @access public
+        */
+    public $parentId;
+
+       /**
+        * Database connection handle
+        *
+        * @var PDO Object
+        * @access protected
+        */
+       protected $dbh;
+
+       //      }}}
+       //      {{{ __construct()
+
+       /**
+        * Setup the objects properties and call to setup children
+        *
+        * @param integer $catid    ID of the Database object
+        * @param string  $name     Name of the Database object
+        * @param PDO     $dbh      Database handler object
+        * @param integer $parentId Id of parent node
+        *
+        * @author      Jamie Kahgee <jamie.kahgee@gmail.com>
+        * @access      public
+        */
+    public function __construct($catid, $name, PDO $dbh, $parentId = 0)
+    {
+               $this->parentId = $parentId;
+        $this->catid    = $catid;
+        $this->category = $name;
+               $this->dbh      = $dbh;
+        $this->addChildren();
+    }
+
+       //      }}}
+       //      {{{ __get()
+
+    /**
+     * utilized for reading data from inaccessible members
+     * 
+     * @param string $name property name
+     *                      
+     * @return mixed  void
+     * @access public
+     */
+       public function __get($name)
+       {
+               return $this->$name;
+       }
+
+       //      }}}
+       //      {{{ __set()
+
+
+    /**
+     * Run when writing data to inaccessible members
+     * 
+     * @param string $name  property
+     * @param string $value new value
+     *                       
+     * @return void  
+     * @access public
+     */
+       public function __set($name, $value)
+       {
+               $this->$name = $value;
+       }
+
+       //      }}}
+       //      {{{ addChildren()
+
+       /**
+        * Attaches children to tree object
+        *
+        * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+     * @return void
+        * @access protected
+        */
+    abstract protected function addChildren();
+
+       //      }}}
+}
+?>
diff --git a/admin/members.php b/admin/members.php
new file mode 100755 (executable)
index 0000000..3842ffc
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+require_once '../setup.phtml';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start('MemberDB');
+
+$GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Members/css/member-admin.css';
+$GLOBALS['topScripts'][] = GLM_APP_BASE_URL
+    . 'libjs/jqueryui/1.8.13/js/jquery-1.5.1.min.js';
+
+$controllerObject = new stdClass();
+$dbh = Toolkit_Database::getInstance();
+$membersConf = new Config;
+$membersRoot =& $membersConf->parseConfig(
+       BASE . 'Toolkit/Members/config.ini',
+       'IniFile'
+);
+
+$navigation = new Toolkit_Members_Admin_Navigation(
+       new HTML_Menu(),
+       new HTML_Menu_DirectRenderer()
+);
+$navArray = $navigation->getNavStructure($dbh, $membersRoot);
+$controllerObject->nav = $navigation->renderPageNav($navArray, 'rows');
+
+$registry = new Toolkit_Registry;
+$registry->dbh = $dbh;
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->controllerObject = $controllerObject;
+$registry->tEngine = new HTML_Template_Flexy(Toolkit_Members::getFlexyOptions());
+$registry->config = $membersRoot;
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/Members/Admin');
+$registry->router->setApplication('Members/Admin');
+
+$html = $registry->router->loader();
+
+echo $navHtml;
+echo $html;