From de8d62e2cf92c10b0c02774ffd70cf68b04eb9f2 Mon Sep 17 00:00:00 2001 From: Steve Sutton Date: Tue, 1 Jul 2014 13:36:43 -0400 Subject: [PATCH] Add site into git New sources for Apple Tree Inn --- .htaccess | 132 + Toolkit/BaseControllerAbstract.php | 50 + Toolkit/BreadCrumbsFactory.php | 85 + Toolkit/CKImages/Connector.php | 400 +++ Toolkit/CKImages/Database/Import.php | 145 + Toolkit/CKImages/Database/application.sql | 21 + .../Database/data/applicationData.sql | 2 + Toolkit/CKImages/Database/importHtImages.php | 10 + .../Database/phpImageEditorUpdates.sql | 2 + .../CKImages/Database/removeApplication.sql | 9 + .../Database/tables/ckeditor_folders.sql | 10 + .../Database/tables/ckeditor_images.sql | 19 + Toolkit/CKImages/Exception.php | 3 + Toolkit/CKImages/Factory.php | 83 + Toolkit/CKImages/Folders.php | 243 ++ Toolkit/CKImages/ImageUpdater.php | 95 + Toolkit/CKImages/assets/.keepme | 0 Toolkit/CKImages/assets/night-fate-stock2.jpg | Bin 0 -> 10337 bytes Toolkit/CKImages/browser.php | 34 + Toolkit/CKImages/controller.php | 53 + Toolkit/CKImages/imageFetch.php | 44 + Toolkit/CKImages/libjs/image_selector.js | 142 + Toolkit/CKImages/styles.css | 153 + Toolkit/CKImages/templates/thumbnails.html | 70 + Toolkit/Common.php | 1397 ++++++++ Toolkit/Contacts/Admin/EditContact.php | 1040 ++++++ Toolkit/Contacts/ContactUs.php | 1126 +++++++ Toolkit/Contacts/Database/application.sql | 15 + .../Contacts/Database/removeApplication.sql | 8 + Toolkit/Contacts/Database/tables/contact.sql | 45 + .../Contacts/Database/tables/contact_inq.sql | 13 + .../Contacts/Database/tables/inq_group.sql | 11 + .../Database/tables/news_response.sql | 20 + Toolkit/Contacts/Database/tables/query_db.sql | 12 + Toolkit/Contacts/ENewsSignup.php | 214 ++ Toolkit/Contacts/MeetingRequest.php | 337 ++ Toolkit/Contacts/SaveTripPlanner.php | 619 ++++ Toolkit/Contacts/SendTripPlanner.php | 742 ++++ Toolkit/Contacts/StreamSend.php | 212 ++ Toolkit/Contacts/VisitorGuide.php | 308 ++ Toolkit/Contacts/assets/.keepme | 0 Toolkit/Contacts/config.ini | 15 + Toolkit/Contacts/database-table-modifiers.sql | 46 + Toolkit/Contacts/database-tables.sql | 45 + Toolkit/Contacts/templates/brochurePage.html | 9 + .../templates/currentTables/Element.tpl | 14 + .../Contacts/templates/currentTables/Form.tpl | 8 + .../templates/currentTables/Group.tpl | 5 + .../templates/currentTables/GroupElement.tpl | 9 + .../templates/currentTables/Header.tpl | 5 + .../templates/currentTables/RequiredNote.tpl | 1 + Toolkit/Contacts/templates/direct-list.html | 29 + Toolkit/Contacts/templates/emailOwner.tpl | 61 + Toolkit/Contacts/templates/friendEmail.html | 49 + .../Contacts/templates/pdfDownloadEmail.html | 19 + Toolkit/DataGridBuilder.php | 285 ++ Toolkit/Database.php | 262 ++ Toolkit/FileServer/AdapterAbstract.php | 405 +++ Toolkit/FileServer/Exception.php | 5 + Toolkit/FileServer/FileAdapter.php | 101 + Toolkit/FileServer/ImageAdapter.php | 248 ++ Toolkit/FileServer/Mock/ImageAdapter.php | 125 + Toolkit/FlexyDataGridBuilder.php | 223 ++ Toolkit/Form.php | 143 + Toolkit/FormBuilder.php | 1263 +++++++ Toolkit/Forms/Rules/Date.php | 93 + Toolkit/Forms/Rules/Image.php | 209 ++ Toolkit/Forms/Rules/ShortUrl.php | 81 + Toolkit/Forms/Rules/Url.php | 80 + Toolkit/Forms/templates/tables/Element.tpl | 14 + Toolkit/Forms/templates/tables/Form.tpl | 11 + Toolkit/Forms/templates/tables/Group.tpl | 5 + .../Forms/templates/tables/GroupElement.tpl | 9 + Toolkit/Forms/templates/tables/Header.tpl | 5 + .../Forms/templates/tables/RequiredNote.tpl | 1 + Toolkit/IController.php | 36 + Toolkit/IMapper.php | 36 + Toolkit/INavigation.php | 52 + Toolkit/ITable.php | 57 + Toolkit/Image/Converter.php | 262 ++ Toolkit/Image/Server.php | 373 +++ .../Affiliates/ConstantContact.php | 1095 ++++++ Toolkit/LeadManager/Affiliates/StreamSend.php | 212 ++ Toolkit/LeadManager/ConstantContact.php | 92 + Toolkit/LeadManager/Contact.php | 292 ++ Toolkit/LeadManager/Customer.php | 461 +++ Toolkit/LeadManager/Lead.php | 659 ++++ Toolkit/LeadManager/Observer.php | 57 + Toolkit/LeadManager/StreamSend.php | 69 + Toolkit/LeadManager/Subject.php | 80 + Toolkit/Logger.php | 168 + Toolkit/NavigationAbstract.php | 89 + Toolkit/NavigationFactoryAbstract.php | 48 + .../PHPImageEditor/classes/phpimageeditor.php | 843 +++++ Toolkit/PHPImageEditor/config.php | 33 + Toolkit/PHPImageEditor/css/jquery.jcrop.css | 45 + Toolkit/PHPImageEditor/css/style.css | 228 ++ Toolkit/PHPImageEditor/css/ui.resizable.css | 13 + Toolkit/PHPImageEditor/css/ui.slider.css | 19 + Toolkit/PHPImageEditor/images/crop_view.png | Bin 0 -> 931 bytes Toolkit/PHPImageEditor/images/edit.gif | Bin 0 -> 417 bytes Toolkit/PHPImageEditor/images/empty.gif | Bin 0 -> 43 bytes Toolkit/PHPImageEditor/images/jcrop.gif | Bin 0 -> 329 bytes .../PHPImageEditor/images/slider_pointer.gif | Bin 0 -> 347 bytes .../PHPImageEditor/images/slider_track.gif | Bin 0 -> 176 bytes Toolkit/PHPImageEditor/images/tab_body.png | Bin 0 -> 198 bytes .../images/tab_not_selected.png | Bin 0 -> 172 bytes .../PHPImageEditor/images/tab_selected.png | Bin 0 -> 150 bytes Toolkit/PHPImageEditor/includes/constants.php | 49 + Toolkit/PHPImageEditor/includes/functions.php | 50 + Toolkit/PHPImageEditor/index.php | 250 ++ .../PHPImageEditor/javascript/effects.core.js | 543 +++ .../javascript/joomla_editimagelink.js | 167 + .../javascript/jquery-1.3.2.min.js | 19 + .../PHPImageEditor/javascript/jquery.jcrop.js | 1197 +++++++ .../javascript/jquery.numeric.js | 127 + .../javascript/phpimageeditor.js | 711 ++++ Toolkit/PHPImageEditor/javascript/ui.core.js | 519 +++ .../PHPImageEditor/javascript/ui.resizable.js | 800 +++++ .../PHPImageEditor/javascript/ui.slider.js | 511 +++ .../language/en-GB/en-GB.com_admin.ini | 37 + Toolkit/Page.php | 690 ++++ Toolkit/Photos/Admin/FileUploader.php | 423 +++ Toolkit/Photos/Database/application.sql | 9 + Toolkit/Photos/Database/removeApplication.sql | 8 + Toolkit/Photos/Database/tables/photo.sql | 16 + .../Photos/Database/tables/photo_category.sql | 11 + .../Database/tables/photo_category_bus.sql | 20 + .../Photos/Database/tables/photo_default.sql | 10 + Toolkit/Photos/Display.php | 271 ++ Toolkit/Photos/Exception.php | 30 + Toolkit/Photos/Factory.php | 47 + Toolkit/Photos/Gallery.php | 136 + Toolkit/Photos/Photo.php | 81 + Toolkit/Photos/assets/.keepme | 0 Toolkit/Photos/templates/photoCats.html | 8 + Toolkit/Photos/templates/photos.html | 11 + Toolkit/Registry.php | 82 + .../RotatingImages/ActiveImagesDataGrid.php | 67 + .../RotatingImages/Database/application.sql | 15 + .../Database/removeApplication.sql | 8 + .../Database/tables/rotating_images.sql | 18 + .../tables/rotating_images_transitions.sql | 9 + Toolkit/RotatingImages/Decorator/Admin.php | 136 + Toolkit/RotatingImages/Decorator/Anchor.php | 86 + .../Decorator/DecoratorAbstract.php | 55 + .../Decorator/IDecoratorsIterator.php | 48 + Toolkit/RotatingImages/Decorator/Image.php | 72 + .../RotatingImages/Decorator/Thumbnail.php | 72 + Toolkit/RotatingImages/Decorator/User.php | 139 + .../RotatingImages/EditImageController.php | 94 + Toolkit/RotatingImages/Forms/EditImage.php | 381 +++ .../Forms/TransitionSettings.php | 296 ++ Toolkit/RotatingImages/Gateway.php | 300 ++ Toolkit/RotatingImages/IImagesDataGrid.php | 39 + Toolkit/RotatingImages/Image.php | 396 +++ .../RotatingImages/ImagesDataGridAbstract.php | 214 ++ .../RotatingImages/InactiveImagesDataGrid.php | 67 + Toolkit/RotatingImages/IndexController.php | 147 + Toolkit/RotatingImages/Navigation.php | 126 + Toolkit/RotatingImages/NodesIterator.php | 131 + Toolkit/RotatingImages/PreviewIframe.php | 90 + Toolkit/RotatingImages/PreviewJavascript.php | 81 + Toolkit/RotatingImages/TransitionGateway.php | 100 + Toolkit/RotatingImages/ajax.php | 52 + Toolkit/RotatingImages/assets/.keepme | 0 Toolkit/RotatingImages/config.ini | 27 + Toolkit/RotatingImages/libjs/sortable.js | 56 + Toolkit/RotatingImages/libjs/user.php | 36 + Toolkit/RotatingImages/styles.css | 119 + .../templates/currentTables/Element.tpl | 14 + .../templates/currentTables/Form.tpl | 7 + .../templates/currentTables/Group.tpl | 5 + .../templates/currentTables/GroupElement.tpl | 9 + .../templates/currentTables/Header.tpl | 5 + .../templates/currentTables/RequiredNote.tpl | 1 + .../templates/imagesDataGrid.html | 22 + .../templates/instructions.html | 10 + Toolkit/Router.php | 195 ++ Toolkit/ShortURL.php | 163 + Toolkit/SiteMap.php | 158 + Toolkit/SiteMapXml.php | 183 + Toolkit/Table.php | 300 ++ Toolkit/Template/BreadCrumbs.php | 144 + Toolkit/Template/DraftBreadCrumbs.php | 110 + Toolkit/Template/DraftController.php | 82 + Toolkit/Template/Exception.php | 31 + Toolkit/Template/Image/Factory.php | 91 + Toolkit/Template/Image/ImageAbstract.php | 114 + Toolkit/Template/Image/Left.php | 62 + Toolkit/Template/Image/Null.php | 56 + Toolkit/Template/Image/Right.php | 62 + Toolkit/Template/IndexController.php | 82 + Toolkit/Template/KeywordReplacement.php | 86 + Toolkit/Template/Navigation/Factory.php | 116 + .../Navigation/MainNavigationAbstract.php | 103 + .../Navigation/MainNavigationAllInOne.php | 123 + .../Navigation/MainNavigationDynamic.php | 104 + .../Navigation/MainNavigationStatic.php | 71 + .../Navigation/Renderer/DirectTreeLastLi.php | 97 + .../Navigation/Renderer/DirectTreeLiId.php | 121 + .../Renderer/DirectTreeSideNavTitle.php | 84 + .../Navigation/Renderer/DirectTreeUlId.php | 125 + .../Template/Navigation/SideNavigation.php | 156 + Toolkit/Template/Page.php | 138 + Toolkit/Template/Page/Bad.php | 42 + Toolkit/Template/Page/BodyFactory.php | 216 ++ Toolkit/Template/Page/FileLink/Abstract.php | 151 + Toolkit/Template/Page/FileLink/Factory.php | 50 + Toolkit/Template/Page/FileLink/File.php | 57 + Toolkit/Template/Page/FileLink/Image.php | 58 + Toolkit/Template/Page/GoogleSearch.php | 42 + Toolkit/Template/Page/IBody.php | 39 + Toolkit/Template/Page/Member.php | 361 ++ Toolkit/Template/Page/SiteMap.php | 146 + Toolkit/Template/Page/Toolbox.php | 452 +++ Toolkit/Template/PageControllerAbstract.php | 115 + Toolkit/Toolbox/BreadCrumbsAbstract.php | 119 + .../Toolbox/Database/addIncludeCoupons.sql | 19 + .../Toolbox/Database/addIncludeMembers.sql | 19 + Toolkit/Toolbox/Database/application.sql | 33 + .../Toolbox/Database/data/applicationData.sql | 32 + .../check_pages_pos_consistency.sql | 38 + .../check_paragraph_pos_consistency.sql | 38 + .../Database/procedures/delete_subtree.sql | 67 + .../Toolbox/Database/procedures/files_pos.sql | 28 + .../Database/procedures/files_update.sql | 20 + .../Toolbox/Database/procedures/pages_pos.sql | 28 + .../Database/procedures/pages_update.sql | 30 + .../procedures/paragraphs_draft_pos.sql | 28 + .../Database/procedures/paragraphs_pos.sql | 48 + .../Database/procedures/paragraphs_update.sql | 21 + .../Toolbox/Database/removeApplication.sql | 8 + Toolkit/Toolbox/Database/tables/files.sql | 17 + .../Toolbox/Database/tables/files_draft.sql | 12 + .../Toolbox/Database/tables/files_history.sql | 10 + Toolkit/Toolbox/Database/tables/pages.sql | 36 + .../Toolbox/Database/tables/pages_draft.sql | 14 + .../Toolbox/Database/tables/pages_history.sql | 12 + .../Toolbox/Database/tables/pages_mobile.sql | 15 + .../Toolbox/Database/tables/pages_preview.sql | 7 + .../Toolbox/Database/tables/paragraphs.sql | 23 + .../Database/tables/paragraphs_draft.sql | 12 + .../Database/tables/paragraphs_history.sql | 10 + .../Database/tables/paragraphs_preview.sql | 6 + Toolkit/Toolbox/DraftPagesTree.php | 42 + Toolkit/Toolbox/EditDraftController.php | 200 ++ Toolkit/Toolbox/EditPageController.php | 148 + Toolkit/Toolbox/Exception.php | 3 + Toolkit/Toolbox/FileExtension.php | 133 + Toolkit/Toolbox/FormControllerAbstract.php | 118 + Toolkit/Toolbox/Forms/EditPage.php | 1157 +++++++ Toolkit/Toolbox/Forms/EditParagraph.php | 503 +++ Toolkit/Toolbox/Forms/SearchForm.php | 174 + Toolkit/Toolbox/GatewayAbstract.php | 32 + Toolkit/Toolbox/GatewayFactoryAbstract.php | 12 + Toolkit/Toolbox/IndexController.php | 36 + Toolkit/Toolbox/ListDraftsController.php | 26 + Toolkit/Toolbox/Navigation.php | 105 + Toolkit/Toolbox/Page.php | 322 ++ Toolkit/Toolbox/PageBreadCrumbs.php | 12 + Toolkit/Toolbox/PageDraftBreadCrumbs.php | 72 + Toolkit/Toolbox/PageGatewayAbstract.php | 280 ++ Toolkit/Toolbox/PageGatewayDraft.php | 553 +++ Toolkit/Toolbox/PageGatewayDraftFactory.php | 10 + Toolkit/Toolbox/PageGatewayPublish.php | 611 ++++ Toolkit/Toolbox/PageGatewayPublishFactory.php | 9 + Toolkit/Toolbox/PagesTree.php | 289 ++ Toolkit/Toolbox/ParagraphBreadCrumbs.php | 46 + Toolkit/Toolbox/ParagraphDraftBreadCrumbs.php | 80 + Toolkit/Toolbox/ParagraphGatewayAbstract.php | 49 + Toolkit/Toolbox/ParagraphGatewayDraft.php | 225 ++ .../Toolbox/ParagraphGatewayDraftFactory.php | 10 + Toolkit/Toolbox/ParagraphGatewayPublish.php | 293 ++ .../ParagraphGatewayPublishFactory.php | 10 + Toolkit/Toolbox/ParagraphsController.php | 315 ++ Toolkit/Toolbox/ParagraphsDraftController.php | 154 + Toolkit/Toolbox/ParagraphsDraftTree.php | 86 + Toolkit/Toolbox/ParagraphsTree.php | 120 + Toolkit/Toolbox/SearchController.php | 50 + Toolkit/Toolbox/SearchTree.php | 35 + Toolkit/Toolbox/TreeAbstract.php | 230 ++ Toolkit/Toolbox/assets/.keepme | 0 Toolkit/Toolbox/assets/arrow.png | Bin 0 -> 502 bytes Toolkit/Toolbox/assets/arrowClosed.png | Bin 0 -> 368 bytes Toolkit/Toolbox/assets/arrowOpen.png | Bin 0 -> 269 bytes Toolkit/Toolbox/assets/collapse.png | Bin 0 -> 182 bytes Toolkit/Toolbox/assets/expand.png | Bin 0 -> 180 bytes Toolkit/Toolbox/assets/grnball.gif | Bin 0 -> 883 bytes Toolkit/Toolbox/assets/mobilemgreen.jpg | Bin 0 -> 464 bytes Toolkit/Toolbox/assets/mobilemred.jpg | Bin 0 -> 481 bytes Toolkit/Toolbox/assets/redball.gif | Bin 0 -> 881 bytes Toolkit/Toolbox/assets/template1.gif | Bin 0 -> 1511 bytes Toolkit/Toolbox/assets/template2.gif | Bin 0 -> 1504 bytes Toolkit/Toolbox/assets/template3.gif | Bin 0 -> 1503 bytes Toolkit/Toolbox/assets/template4.gif | Bin 0 -> 1500 bytes Toolkit/Toolbox/assets/template5.gif | Bin 0 -> 1501 bytes Toolkit/Toolbox/assets/template6.gif | Bin 0 -> 1501 bytes Toolkit/Toolbox/config.ini | 3 + Toolkit/Toolbox/fixPageNoContent.php | 48 + Toolkit/Toolbox/fixPagePos.php | 70 + Toolkit/Toolbox/libjs/edit-page.js | 239 ++ Toolkit/Toolbox/libjs/edit-paragraph.js | 149 + Toolkit/Toolbox/libjs/pagesTree.js | 242 ++ Toolkit/Toolbox/libjs/paragraph-tree.js | 143 + Toolkit/Toolbox/moveBySelect.php | 126 + Toolkit/Toolbox/moveBySelectPara.php | 119 + Toolkit/Toolbox/pageChangeState.php | 32 + Toolkit/Toolbox/pageMobileChangeState.php | 31 + Toolkit/Toolbox/pageMove.php | 96 + Toolkit/Toolbox/paragraphChangeState.php | 44 + Toolkit/Toolbox/paragraphFileUpload.php | 14 + Toolkit/Toolbox/paragraphMove.php | 51 + Toolkit/Toolbox/styles.css | 132 + Toolkit/qfcaptcha.php | 39 + admin/.htaccess | 1 + admin/Contact/contact_inquiry.phtml | 125 + admin/Contact/contact_setup.inc | 475 +++ admin/Contact/del_query.phtml | 20 + admin/Contact/download.phtml | 224 ++ admin/Contact/edit_autoresponse.phtml | 102 + admin/Contact/edit_contact.php | 25 + admin/Contact/edit_group.php | 99 + admin/Contact/edit_inquiry.phtml | 129 + admin/Contact/emails.php | 36 + admin/Contact/form.js | 42 + admin/Contact/help/contact.phtml | 146 + admin/Contact/htmlarea.css | 180 + admin/Contact/index.phtml | 315 ++ admin/Contact/list_contact.phtml | 285 ++ admin/Contact/list_groups.php | 56 + admin/Contact/list_query.phtml | 57 + admin/Contact/mailout.phtml | 160 + admin/Contact/main.css | 23 + admin/Contact/msg.js | 29 + admin/Contact/newsletter_template.html | 42 + admin/Contact/notes/ChangeLog | 327 ++ admin/Contact/notes/Contact | 4 + admin/Contact/notes/contact.sql | 100 + admin/Contact/preview.phtml | 14 + admin/Contact/query_contact.phtml | 413 +++ admin/Contact/query_db.phtml | 19 + admin/Contact/query_save.phtml | 18 + admin/Contact/update_autoresponse.phtml | 82 + admin/Contact/update_contact.phtml | 39 + admin/Contact/update_inquiry.phtml | 118 + admin/Contact/verify.js | 72 + admin/Contact/view_newsletter.phtml | 22 + admin/Contact/wm.js | 13 + admin/Photos/assets/uploader.swf | Bin 0 -> 7101 bytes admin/Photos/checkBrowserSupport.js | 17 + admin/Photos/debug.js | 12 + admin/Photos/edit-default.php | 35 + admin/Photos/edit_display.phtml | 20 + admin/Photos/edit_photo.phtml | 148 + admin/Photos/edit_photo_category.phtml | 151 + admin/Photos/export-images-is0.php | 53 + admin/Photos/flashUploader.html | 30 + admin/Photos/index.php | 3 + admin/Photos/list_photo.phtml | 100 + admin/Photos/list_photo_category.phtml | 129 + admin/Photos/multipleUpload.php | 25 + admin/Photos/photo-setup.inc | 316 ++ admin/Photos/photo.css | 1 + admin/Photos/update_display.php | 10 + admin/Photos/update_photo.phtml | 286 ++ admin/Photos/update_photo_category.phtml | 115 + admin/Photos/uploadFiles.php | 28 + admin/Photos/upload_simple.php | 10 + admin/Photos/uploadify.css | 53 + admin/Photos/yuiPhotoUploader.php | 167 + admin/index.phtml | 25 + admin/main.css | 132 + admin/nav.phtml | 137 + admin/rotatingImages.php | 42 + admin/splash.phtml | 21 + admin/toolbox.php | 37 + assets/IHG_Rewards_Club.jpg | Bin 0 -> 24031 bytes assets/bg.jpg | Bin 0 -> 411523 bytes assets/header_bg.png | Bin 0 -> 1302 bytes assets/leftcol_bg.jpg | Bin 0 -> 3384 bytes assets/logo.jpg | Bin 0 -> 6872 bytes assets/main_bg.jpg | Bin 0 -> 307 bytes assets/nHeader.jpg | Bin 0 -> 15522 bytes assets/nav.png | Bin 0 -> 1023 bytes assets/priority_club.jpg | Bin 0 -> 6160 bytes assets/reservation.jpg | Bin 0 -> 4748 bytes assets/sister.png | Bin 0 -> 16917 bytes assets/social.jpg | Bin 0 -> 4010 bytes assets/title.jpg | Bin 0 -> 3509 bytes assets/tripadv.jpg | Bin 0 -> 13387 bytes calendar_icon.png | Bin 0 -> 334 bytes classes/class_db.inc | 846 +++++ classes/class_template.inc | 2983 +++++++++++++++++ classes/class_toolbox.inc | 1661 +++++++++ combine.php | 197 ++ config/application.ini | 136 + config/server.ini | 288 ++ config/site.ini | 31 + css/contactform.css | 108 + css/dev/email.css | 42 + css/dev/gsearch.css | 851 +++++ css/dev/ie7.css | 9 + css/email.css | 42 + css/gsearch.css | 851 +++++ css/ie7.css | 9 + css/prod/email.css | 1 + css/prod/gsearch.css | 1 + css/prod/ie7.css | 1 + css/prod/styles.css | 1 + css/siteMap.css | 49 + images/add.png | Bin 0 -> 733 bytes images/amenities/1182867688waterfront.gif | Bin 0 -> 379 bytes images/amenities/1182867790sauna.gif | Bin 0 -> 1235 bytes images/amenities/barrierfree.gif | Bin 0 -> 450 bytes images/amenities/beachaccess.gif | Bin 0 -> 411 bytes images/amenities/breakfast.gif | Bin 0 -> 1175 bytes images/amenities/cable.gif | Bin 0 -> 740 bytes images/amenities/conference.gif | Bin 0 -> 703 bytes images/amenities/cont_break.gif | Bin 0 -> 1307 bytes images/amenities/eff.gif | Bin 0 -> 731 bytes images/amenities/excersize.gif | Bin 0 -> 375 bytes images/amenities/free_internet.gif | Bin 0 -> 348 bytes images/amenities/guest_laundry.gif | Bin 0 -> 666 bytes images/amenities/internet.gif | Bin 0 -> 330 bytes images/amenities/kidfriendly.gif | Bin 0 -> 396 bytes images/amenities/meeting.gif | Bin 0 -> 1321 bytes images/amenities/pets.gif | Bin 0 -> 375 bytes images/amenities/pool-out.gif | Bin 0 -> 1396 bytes images/amenities/pool.gif | Bin 0 -> 1271 bytes images/amenities/restaurant.gif | Bin 0 -> 262 bytes images/amenities/restnear.gif | Bin 0 -> 276 bytes images/amenities/sauna.gif | Bin 0 -> 1235 bytes images/amenities/smokefree.gif | Bin 0 -> 364 bytes images/amenities/snowmobile.gif | Bin 0 -> 1116 bytes images/amenities/waterfront.gif | Bin 0 -> 379 bytes images/amenities/waterview.gif | Bin 0 -> 1154 bytes images/amenities/wireless.gif | Bin 0 -> 1548 bytes images/application_edit.png | Bin 0 -> 703 bytes images/cross.png | Bin 0 -> 655 bytes images/delete.png | Bin 0 -> 715 bytes images/error.gif | Bin 0 -> 375 bytes images/file-ext/cad.gif | Bin 0 -> 630 bytes images/file-ext/doc.gif | Bin 0 -> 363 bytes images/file-ext/download.gif | Bin 0 -> 211 bytes images/file-ext/gif.gif | Bin 0 -> 376 bytes images/file-ext/html.gif | Bin 0 -> 261 bytes images/file-ext/jpg.gif | Bin 0 -> 376 bytes images/file-ext/movie.gif | Bin 0 -> 550 bytes images/file-ext/mp3.gif | Bin 0 -> 98 bytes images/file-ext/pdf.png | Bin 0 -> 734 bytes images/file-ext/ppt.gif | Bin 0 -> 374 bytes images/file-ext/rar.gif | Bin 0 -> 312 bytes images/file-ext/rm.gif | Bin 0 -> 550 bytes images/file-ext/txt.png | Bin 0 -> 513 bytes images/file-ext/xls.gif | Bin 0 -> 270 bytes images/file-ext/zip.png | Bin 0 -> 222 bytes images/find.png | Bin 0 -> 659 bytes images/flag_green.png | Bin 0 -> 672 bytes images/folder.png | Bin 0 -> 537 bytes images/folder_add.png | Bin 0 -> 668 bytes images/folder_delete.png | Bin 0 -> 666 bytes images/grnball.gif | Bin 0 -> 883 bytes images/help.gif | Bin 0 -> 142 bytes images/html.gif | Bin 0 -> 232 bytes images/img.gif | Bin 0 -> 223 bytes images/left.gif | Bin 0 -> 210 bytes images/loadingAnimation.gif | Bin 0 -> 7347 bytes images/logo.gif | Bin 0 -> 14041 bytes images/magnifier.png | Bin 0 -> 615 bytes images/members/add.png | Bin 0 -> 733 bytes images/members/application_edit.png | Bin 0 -> 703 bytes images/members/cancel.png | Bin 0 -> 587 bytes images/members/cardamex.gif | Bin 0 -> 2145 bytes images/members/carddinner.gif | Bin 0 -> 1956 bytes images/members/carddiscover.gif | Bin 0 -> 2589 bytes images/members/cardmaster.gif | Bin 0 -> 2049 bytes images/members/cardvisa.gif | Bin 0 -> 2303 bytes images/members/cross.png | Bin 0 -> 655 bytes images/members/delete.png | Bin 0 -> 715 bytes images/members/find.png | Bin 0 -> 659 bytes images/members/img.gif | Bin 0 -> 223 bytes images/members/lock.png | Bin 0 -> 749 bytes images/members/note_edit.png | Bin 0 -> 731 bytes images/members/page_edit.png | Bin 0 -> 807 bytes images/members/tick.png | Bin 0 -> 537 bytes images/members/user_add.png | Bin 0 -> 746 bytes images/members/user_edit.png | Bin 0 -> 833 bytes images/note_edit.png | Bin 0 -> 731 bytes images/page_edit.png | Bin 0 -> 807 bytes images/redball.gif | Bin 0 -> 881 bytes images/right.gif | Bin 0 -> 210 bytes images/shadowb.gif | Bin 0 -> 432 bytes images/shadowr.gif | Bin 0 -> 177 bytes images/size.sh | 13 + images/tick.png | Bin 0 -> 537 bytes images/top2.jpg | Bin 0 -> 26353 bytes images/user_add.png | Bin 0 -> 746 bytes images/user_edit.png | Bin 0 -> 833 bytes index.php | 134 + libjs/datepicker.js | 17 + libjs/dev/newsletterSignup.js | 49 + libjs/pagefunctions.js | 25 + libjs/prod/newsletterSignup.js | 1 + setup.phtml | 1131 +++++++ setup_functions.phtml | 1223 +++++++ static/1.phtml | 0 static/2.phtml | 0 static/3.phtml | 0 static/4.phtml | 0 static/5.phtml | 0 static/6.phtml | 12 + static/8.phtml | 12 + styles.css | 483 +++ templates/siteMap.html | 26 + templates/template.html | 83 + 516 files changed, 58504 insertions(+) create mode 100644 .htaccess create mode 100644 Toolkit/BaseControllerAbstract.php create mode 100644 Toolkit/BreadCrumbsFactory.php create mode 100644 Toolkit/CKImages/Connector.php create mode 100755 Toolkit/CKImages/Database/Import.php create mode 100644 Toolkit/CKImages/Database/application.sql create mode 100644 Toolkit/CKImages/Database/data/applicationData.sql create mode 100755 Toolkit/CKImages/Database/importHtImages.php create mode 100644 Toolkit/CKImages/Database/phpImageEditorUpdates.sql create mode 100644 Toolkit/CKImages/Database/removeApplication.sql create mode 100644 Toolkit/CKImages/Database/tables/ckeditor_folders.sql create mode 100644 Toolkit/CKImages/Database/tables/ckeditor_images.sql create mode 100644 Toolkit/CKImages/Exception.php create mode 100644 Toolkit/CKImages/Factory.php create mode 100644 Toolkit/CKImages/Folders.php create mode 100644 Toolkit/CKImages/ImageUpdater.php create mode 100644 Toolkit/CKImages/assets/.keepme create mode 100755 Toolkit/CKImages/assets/night-fate-stock2.jpg create mode 100644 Toolkit/CKImages/browser.php create mode 100644 Toolkit/CKImages/controller.php create mode 100644 Toolkit/CKImages/imageFetch.php create mode 100644 Toolkit/CKImages/libjs/image_selector.js create mode 100755 Toolkit/CKImages/styles.css create mode 100755 Toolkit/CKImages/templates/thumbnails.html create mode 100644 Toolkit/Common.php create mode 100644 Toolkit/Contacts/Admin/EditContact.php create mode 100755 Toolkit/Contacts/ContactUs.php create mode 100644 Toolkit/Contacts/Database/application.sql create mode 100644 Toolkit/Contacts/Database/removeApplication.sql create mode 100644 Toolkit/Contacts/Database/tables/contact.sql create mode 100644 Toolkit/Contacts/Database/tables/contact_inq.sql create mode 100644 Toolkit/Contacts/Database/tables/inq_group.sql create mode 100644 Toolkit/Contacts/Database/tables/news_response.sql create mode 100644 Toolkit/Contacts/Database/tables/query_db.sql create mode 100755 Toolkit/Contacts/ENewsSignup.php create mode 100755 Toolkit/Contacts/MeetingRequest.php create mode 100755 Toolkit/Contacts/SaveTripPlanner.php create mode 100755 Toolkit/Contacts/SendTripPlanner.php create mode 100755 Toolkit/Contacts/StreamSend.php create mode 100755 Toolkit/Contacts/VisitorGuide.php create mode 100644 Toolkit/Contacts/assets/.keepme create mode 100644 Toolkit/Contacts/config.ini create mode 100644 Toolkit/Contacts/database-table-modifiers.sql create mode 100644 Toolkit/Contacts/database-tables.sql create mode 100755 Toolkit/Contacts/templates/brochurePage.html create mode 100755 Toolkit/Contacts/templates/currentTables/Element.tpl create mode 100755 Toolkit/Contacts/templates/currentTables/Form.tpl create mode 100755 Toolkit/Contacts/templates/currentTables/Group.tpl create mode 100755 Toolkit/Contacts/templates/currentTables/GroupElement.tpl create mode 100755 Toolkit/Contacts/templates/currentTables/Header.tpl create mode 100755 Toolkit/Contacts/templates/currentTables/RequiredNote.tpl create mode 100755 Toolkit/Contacts/templates/direct-list.html create mode 100755 Toolkit/Contacts/templates/emailOwner.tpl create mode 100644 Toolkit/Contacts/templates/friendEmail.html create mode 100755 Toolkit/Contacts/templates/pdfDownloadEmail.html create mode 100644 Toolkit/DataGridBuilder.php create mode 100644 Toolkit/Database.php create mode 100644 Toolkit/FileServer/AdapterAbstract.php create mode 100644 Toolkit/FileServer/Exception.php create mode 100644 Toolkit/FileServer/FileAdapter.php create mode 100644 Toolkit/FileServer/ImageAdapter.php create mode 100644 Toolkit/FileServer/Mock/ImageAdapter.php create mode 100644 Toolkit/FlexyDataGridBuilder.php create mode 100644 Toolkit/Form.php create mode 100644 Toolkit/FormBuilder.php create mode 100644 Toolkit/Forms/Rules/Date.php create mode 100644 Toolkit/Forms/Rules/Image.php create mode 100644 Toolkit/Forms/Rules/ShortUrl.php create mode 100644 Toolkit/Forms/Rules/Url.php create mode 100644 Toolkit/Forms/templates/tables/Element.tpl create mode 100644 Toolkit/Forms/templates/tables/Form.tpl create mode 100644 Toolkit/Forms/templates/tables/Group.tpl create mode 100644 Toolkit/Forms/templates/tables/GroupElement.tpl create mode 100644 Toolkit/Forms/templates/tables/Header.tpl create mode 100644 Toolkit/Forms/templates/tables/RequiredNote.tpl create mode 100644 Toolkit/IController.php create mode 100644 Toolkit/IMapper.php create mode 100644 Toolkit/INavigation.php create mode 100644 Toolkit/ITable.php create mode 100644 Toolkit/Image/Converter.php create mode 100755 Toolkit/Image/Server.php create mode 100644 Toolkit/LeadManager/Affiliates/ConstantContact.php create mode 100755 Toolkit/LeadManager/Affiliates/StreamSend.php create mode 100644 Toolkit/LeadManager/ConstantContact.php create mode 100644 Toolkit/LeadManager/Contact.php create mode 100644 Toolkit/LeadManager/Customer.php create mode 100644 Toolkit/LeadManager/Lead.php create mode 100644 Toolkit/LeadManager/Observer.php create mode 100644 Toolkit/LeadManager/StreamSend.php create mode 100644 Toolkit/LeadManager/Subject.php create mode 100644 Toolkit/Logger.php create mode 100644 Toolkit/NavigationAbstract.php create mode 100644 Toolkit/NavigationFactoryAbstract.php create mode 100644 Toolkit/PHPImageEditor/classes/phpimageeditor.php create mode 100644 Toolkit/PHPImageEditor/config.php create mode 100644 Toolkit/PHPImageEditor/css/jquery.jcrop.css create mode 100644 Toolkit/PHPImageEditor/css/style.css create mode 100644 Toolkit/PHPImageEditor/css/ui.resizable.css create mode 100644 Toolkit/PHPImageEditor/css/ui.slider.css create mode 100644 Toolkit/PHPImageEditor/images/crop_view.png create mode 100644 Toolkit/PHPImageEditor/images/edit.gif create mode 100644 Toolkit/PHPImageEditor/images/empty.gif create mode 100644 Toolkit/PHPImageEditor/images/jcrop.gif create mode 100644 Toolkit/PHPImageEditor/images/slider_pointer.gif create mode 100644 Toolkit/PHPImageEditor/images/slider_track.gif create mode 100644 Toolkit/PHPImageEditor/images/tab_body.png create mode 100644 Toolkit/PHPImageEditor/images/tab_not_selected.png create mode 100644 Toolkit/PHPImageEditor/images/tab_selected.png create mode 100644 Toolkit/PHPImageEditor/includes/constants.php create mode 100644 Toolkit/PHPImageEditor/includes/functions.php create mode 100644 Toolkit/PHPImageEditor/index.php create mode 100644 Toolkit/PHPImageEditor/javascript/effects.core.js create mode 100644 Toolkit/PHPImageEditor/javascript/joomla_editimagelink.js create mode 100644 Toolkit/PHPImageEditor/javascript/jquery-1.3.2.min.js create mode 100644 Toolkit/PHPImageEditor/javascript/jquery.jcrop.js create mode 100644 Toolkit/PHPImageEditor/javascript/jquery.numeric.js create mode 100644 Toolkit/PHPImageEditor/javascript/phpimageeditor.js create mode 100644 Toolkit/PHPImageEditor/javascript/ui.core.js create mode 100644 Toolkit/PHPImageEditor/javascript/ui.resizable.js create mode 100644 Toolkit/PHPImageEditor/javascript/ui.slider.js create mode 100644 Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini create mode 100755 Toolkit/Page.php create mode 100644 Toolkit/Photos/Admin/FileUploader.php create mode 100644 Toolkit/Photos/Database/application.sql create mode 100644 Toolkit/Photos/Database/removeApplication.sql create mode 100755 Toolkit/Photos/Database/tables/photo.sql create mode 100755 Toolkit/Photos/Database/tables/photo_category.sql create mode 100755 Toolkit/Photos/Database/tables/photo_category_bus.sql create mode 100755 Toolkit/Photos/Database/tables/photo_default.sql create mode 100755 Toolkit/Photos/Display.php create mode 100644 Toolkit/Photos/Exception.php create mode 100644 Toolkit/Photos/Factory.php create mode 100644 Toolkit/Photos/Gallery.php create mode 100644 Toolkit/Photos/Photo.php create mode 100644 Toolkit/Photos/assets/.keepme create mode 100755 Toolkit/Photos/templates/photoCats.html create mode 100755 Toolkit/Photos/templates/photos.html create mode 100644 Toolkit/Registry.php create mode 100644 Toolkit/RotatingImages/ActiveImagesDataGrid.php create mode 100644 Toolkit/RotatingImages/Database/application.sql create mode 100644 Toolkit/RotatingImages/Database/removeApplication.sql create mode 100644 Toolkit/RotatingImages/Database/tables/rotating_images.sql create mode 100644 Toolkit/RotatingImages/Database/tables/rotating_images_transitions.sql create mode 100644 Toolkit/RotatingImages/Decorator/Admin.php create mode 100644 Toolkit/RotatingImages/Decorator/Anchor.php create mode 100644 Toolkit/RotatingImages/Decorator/DecoratorAbstract.php create mode 100644 Toolkit/RotatingImages/Decorator/IDecoratorsIterator.php create mode 100644 Toolkit/RotatingImages/Decorator/Image.php create mode 100644 Toolkit/RotatingImages/Decorator/Thumbnail.php create mode 100644 Toolkit/RotatingImages/Decorator/User.php create mode 100644 Toolkit/RotatingImages/EditImageController.php create mode 100644 Toolkit/RotatingImages/Forms/EditImage.php create mode 100644 Toolkit/RotatingImages/Forms/TransitionSettings.php create mode 100644 Toolkit/RotatingImages/Gateway.php create mode 100644 Toolkit/RotatingImages/IImagesDataGrid.php create mode 100644 Toolkit/RotatingImages/Image.php create mode 100644 Toolkit/RotatingImages/ImagesDataGridAbstract.php create mode 100644 Toolkit/RotatingImages/InactiveImagesDataGrid.php create mode 100644 Toolkit/RotatingImages/IndexController.php create mode 100644 Toolkit/RotatingImages/Navigation.php create mode 100644 Toolkit/RotatingImages/NodesIterator.php create mode 100644 Toolkit/RotatingImages/PreviewIframe.php create mode 100644 Toolkit/RotatingImages/PreviewJavascript.php create mode 100644 Toolkit/RotatingImages/TransitionGateway.php create mode 100644 Toolkit/RotatingImages/ajax.php create mode 100644 Toolkit/RotatingImages/assets/.keepme create mode 100644 Toolkit/RotatingImages/config.ini create mode 100644 Toolkit/RotatingImages/libjs/sortable.js create mode 100644 Toolkit/RotatingImages/libjs/user.php create mode 100644 Toolkit/RotatingImages/styles.css create mode 100755 Toolkit/RotatingImages/templates/currentTables/Element.tpl create mode 100755 Toolkit/RotatingImages/templates/currentTables/Form.tpl create mode 100755 Toolkit/RotatingImages/templates/currentTables/Group.tpl create mode 100755 Toolkit/RotatingImages/templates/currentTables/GroupElement.tpl create mode 100755 Toolkit/RotatingImages/templates/currentTables/Header.tpl create mode 100755 Toolkit/RotatingImages/templates/currentTables/RequiredNote.tpl create mode 100644 Toolkit/RotatingImages/templates/imagesDataGrid.html create mode 100644 Toolkit/RotatingImages/templates/instructions.html create mode 100644 Toolkit/Router.php create mode 100755 Toolkit/ShortURL.php create mode 100755 Toolkit/SiteMap.php create mode 100644 Toolkit/SiteMapXml.php create mode 100644 Toolkit/Table.php create mode 100644 Toolkit/Template/BreadCrumbs.php create mode 100644 Toolkit/Template/DraftBreadCrumbs.php create mode 100644 Toolkit/Template/DraftController.php create mode 100644 Toolkit/Template/Exception.php create mode 100644 Toolkit/Template/Image/Factory.php create mode 100644 Toolkit/Template/Image/ImageAbstract.php create mode 100644 Toolkit/Template/Image/Left.php create mode 100644 Toolkit/Template/Image/Null.php create mode 100644 Toolkit/Template/Image/Right.php create mode 100644 Toolkit/Template/IndexController.php create mode 100644 Toolkit/Template/KeywordReplacement.php create mode 100644 Toolkit/Template/Navigation/Factory.php create mode 100644 Toolkit/Template/Navigation/MainNavigationAbstract.php create mode 100644 Toolkit/Template/Navigation/MainNavigationAllInOne.php create mode 100644 Toolkit/Template/Navigation/MainNavigationDynamic.php create mode 100644 Toolkit/Template/Navigation/MainNavigationStatic.php create mode 100644 Toolkit/Template/Navigation/Renderer/DirectTreeLastLi.php create mode 100644 Toolkit/Template/Navigation/Renderer/DirectTreeLiId.php create mode 100644 Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php create mode 100644 Toolkit/Template/Navigation/Renderer/DirectTreeUlId.php create mode 100644 Toolkit/Template/Navigation/SideNavigation.php create mode 100644 Toolkit/Template/Page.php create mode 100644 Toolkit/Template/Page/Bad.php create mode 100644 Toolkit/Template/Page/BodyFactory.php create mode 100644 Toolkit/Template/Page/FileLink/Abstract.php create mode 100644 Toolkit/Template/Page/FileLink/Factory.php create mode 100644 Toolkit/Template/Page/FileLink/File.php create mode 100644 Toolkit/Template/Page/FileLink/Image.php create mode 100644 Toolkit/Template/Page/GoogleSearch.php create mode 100644 Toolkit/Template/Page/IBody.php create mode 100644 Toolkit/Template/Page/Member.php create mode 100644 Toolkit/Template/Page/SiteMap.php create mode 100644 Toolkit/Template/Page/Toolbox.php create mode 100644 Toolkit/Template/PageControllerAbstract.php create mode 100644 Toolkit/Toolbox/BreadCrumbsAbstract.php create mode 100644 Toolkit/Toolbox/Database/addIncludeCoupons.sql create mode 100644 Toolkit/Toolbox/Database/addIncludeMembers.sql create mode 100644 Toolkit/Toolbox/Database/application.sql create mode 100644 Toolkit/Toolbox/Database/data/applicationData.sql create mode 100644 Toolkit/Toolbox/Database/procedures/check_pages_pos_consistency.sql create mode 100644 Toolkit/Toolbox/Database/procedures/check_paragraph_pos_consistency.sql create mode 100644 Toolkit/Toolbox/Database/procedures/delete_subtree.sql create mode 100644 Toolkit/Toolbox/Database/procedures/files_pos.sql create mode 100644 Toolkit/Toolbox/Database/procedures/files_update.sql create mode 100644 Toolkit/Toolbox/Database/procedures/pages_pos.sql create mode 100644 Toolkit/Toolbox/Database/procedures/pages_update.sql create mode 100644 Toolkit/Toolbox/Database/procedures/paragraphs_draft_pos.sql create mode 100644 Toolkit/Toolbox/Database/procedures/paragraphs_pos.sql create mode 100644 Toolkit/Toolbox/Database/procedures/paragraphs_update.sql create mode 100644 Toolkit/Toolbox/Database/removeApplication.sql create mode 100644 Toolkit/Toolbox/Database/tables/files.sql create mode 100644 Toolkit/Toolbox/Database/tables/files_draft.sql create mode 100644 Toolkit/Toolbox/Database/tables/files_history.sql create mode 100644 Toolkit/Toolbox/Database/tables/pages.sql create mode 100644 Toolkit/Toolbox/Database/tables/pages_draft.sql create mode 100644 Toolkit/Toolbox/Database/tables/pages_history.sql create mode 100644 Toolkit/Toolbox/Database/tables/pages_mobile.sql create mode 100644 Toolkit/Toolbox/Database/tables/pages_preview.sql create mode 100644 Toolkit/Toolbox/Database/tables/paragraphs.sql create mode 100644 Toolkit/Toolbox/Database/tables/paragraphs_draft.sql create mode 100644 Toolkit/Toolbox/Database/tables/paragraphs_history.sql create mode 100644 Toolkit/Toolbox/Database/tables/paragraphs_preview.sql create mode 100644 Toolkit/Toolbox/DraftPagesTree.php create mode 100644 Toolkit/Toolbox/EditDraftController.php create mode 100644 Toolkit/Toolbox/EditPageController.php create mode 100644 Toolkit/Toolbox/Exception.php create mode 100644 Toolkit/Toolbox/FileExtension.php create mode 100644 Toolkit/Toolbox/FormControllerAbstract.php create mode 100644 Toolkit/Toolbox/Forms/EditPage.php create mode 100644 Toolkit/Toolbox/Forms/EditParagraph.php create mode 100644 Toolkit/Toolbox/Forms/SearchForm.php create mode 100644 Toolkit/Toolbox/GatewayAbstract.php create mode 100644 Toolkit/Toolbox/GatewayFactoryAbstract.php create mode 100644 Toolkit/Toolbox/IndexController.php create mode 100644 Toolkit/Toolbox/ListDraftsController.php create mode 100644 Toolkit/Toolbox/Navigation.php create mode 100644 Toolkit/Toolbox/Page.php create mode 100644 Toolkit/Toolbox/PageBreadCrumbs.php create mode 100644 Toolkit/Toolbox/PageDraftBreadCrumbs.php create mode 100644 Toolkit/Toolbox/PageGatewayAbstract.php create mode 100644 Toolkit/Toolbox/PageGatewayDraft.php create mode 100644 Toolkit/Toolbox/PageGatewayDraftFactory.php create mode 100644 Toolkit/Toolbox/PageGatewayPublish.php create mode 100644 Toolkit/Toolbox/PageGatewayPublishFactory.php create mode 100644 Toolkit/Toolbox/PagesTree.php create mode 100644 Toolkit/Toolbox/ParagraphBreadCrumbs.php create mode 100644 Toolkit/Toolbox/ParagraphDraftBreadCrumbs.php create mode 100644 Toolkit/Toolbox/ParagraphGatewayAbstract.php create mode 100644 Toolkit/Toolbox/ParagraphGatewayDraft.php create mode 100644 Toolkit/Toolbox/ParagraphGatewayDraftFactory.php create mode 100644 Toolkit/Toolbox/ParagraphGatewayPublish.php create mode 100644 Toolkit/Toolbox/ParagraphGatewayPublishFactory.php create mode 100644 Toolkit/Toolbox/ParagraphsController.php create mode 100644 Toolkit/Toolbox/ParagraphsDraftController.php create mode 100644 Toolkit/Toolbox/ParagraphsDraftTree.php create mode 100644 Toolkit/Toolbox/ParagraphsTree.php create mode 100644 Toolkit/Toolbox/SearchController.php create mode 100644 Toolkit/Toolbox/SearchTree.php create mode 100644 Toolkit/Toolbox/TreeAbstract.php create mode 100644 Toolkit/Toolbox/assets/.keepme create mode 100755 Toolkit/Toolbox/assets/arrow.png create mode 100755 Toolkit/Toolbox/assets/arrowClosed.png create mode 100755 Toolkit/Toolbox/assets/arrowOpen.png create mode 100755 Toolkit/Toolbox/assets/collapse.png create mode 100755 Toolkit/Toolbox/assets/expand.png create mode 100755 Toolkit/Toolbox/assets/grnball.gif create mode 100644 Toolkit/Toolbox/assets/mobilemgreen.jpg create mode 100644 Toolkit/Toolbox/assets/mobilemred.jpg create mode 100755 Toolkit/Toolbox/assets/redball.gif create mode 100755 Toolkit/Toolbox/assets/template1.gif create mode 100755 Toolkit/Toolbox/assets/template2.gif create mode 100755 Toolkit/Toolbox/assets/template3.gif create mode 100755 Toolkit/Toolbox/assets/template4.gif create mode 100755 Toolkit/Toolbox/assets/template5.gif create mode 100644 Toolkit/Toolbox/assets/template6.gif create mode 100644 Toolkit/Toolbox/config.ini create mode 100644 Toolkit/Toolbox/fixPageNoContent.php create mode 100644 Toolkit/Toolbox/fixPagePos.php create mode 100644 Toolkit/Toolbox/libjs/edit-page.js create mode 100644 Toolkit/Toolbox/libjs/edit-paragraph.js create mode 100644 Toolkit/Toolbox/libjs/pagesTree.js create mode 100644 Toolkit/Toolbox/libjs/paragraph-tree.js create mode 100644 Toolkit/Toolbox/moveBySelect.php create mode 100644 Toolkit/Toolbox/moveBySelectPara.php create mode 100644 Toolkit/Toolbox/pageChangeState.php create mode 100644 Toolkit/Toolbox/pageMobileChangeState.php create mode 100644 Toolkit/Toolbox/pageMove.php create mode 100644 Toolkit/Toolbox/paragraphChangeState.php create mode 100644 Toolkit/Toolbox/paragraphFileUpload.php create mode 100644 Toolkit/Toolbox/paragraphMove.php create mode 100644 Toolkit/Toolbox/styles.css create mode 100755 Toolkit/qfcaptcha.php create mode 100644 admin/.htaccess create mode 100755 admin/Contact/contact_inquiry.phtml create mode 100755 admin/Contact/contact_setup.inc create mode 100755 admin/Contact/del_query.phtml create mode 100755 admin/Contact/download.phtml create mode 100755 admin/Contact/edit_autoresponse.phtml create mode 100644 admin/Contact/edit_contact.php create mode 100644 admin/Contact/edit_group.php create mode 100755 admin/Contact/edit_inquiry.phtml create mode 100644 admin/Contact/emails.php create mode 100755 admin/Contact/form.js create mode 100755 admin/Contact/help/contact.phtml create mode 100644 admin/Contact/htmlarea.css create mode 100755 admin/Contact/index.phtml create mode 100755 admin/Contact/list_contact.phtml create mode 100644 admin/Contact/list_groups.php create mode 100755 admin/Contact/list_query.phtml create mode 100644 admin/Contact/mailout.phtml create mode 100755 admin/Contact/main.css create mode 100755 admin/Contact/msg.js create mode 100755 admin/Contact/newsletter_template.html create mode 100755 admin/Contact/notes/ChangeLog create mode 100755 admin/Contact/notes/Contact create mode 100755 admin/Contact/notes/contact.sql create mode 100755 admin/Contact/preview.phtml create mode 100755 admin/Contact/query_contact.phtml create mode 100755 admin/Contact/query_db.phtml create mode 100755 admin/Contact/query_save.phtml create mode 100755 admin/Contact/update_autoresponse.phtml create mode 100755 admin/Contact/update_contact.phtml create mode 100755 admin/Contact/update_inquiry.phtml create mode 100755 admin/Contact/verify.js create mode 100755 admin/Contact/view_newsletter.phtml create mode 100755 admin/Contact/wm.js create mode 100644 admin/Photos/assets/uploader.swf create mode 100644 admin/Photos/checkBrowserSupport.js create mode 100644 admin/Photos/debug.js create mode 100644 admin/Photos/edit-default.php create mode 100644 admin/Photos/edit_display.phtml create mode 100644 admin/Photos/edit_photo.phtml create mode 100755 admin/Photos/edit_photo_category.phtml create mode 100755 admin/Photos/export-images-is0.php create mode 100644 admin/Photos/flashUploader.html create mode 100644 admin/Photos/index.php create mode 100755 admin/Photos/list_photo.phtml create mode 100755 admin/Photos/list_photo_category.phtml create mode 100644 admin/Photos/multipleUpload.php create mode 100644 admin/Photos/photo-setup.inc create mode 100644 admin/Photos/photo.css create mode 100644 admin/Photos/update_display.php create mode 100644 admin/Photos/update_photo.phtml create mode 100644 admin/Photos/update_photo_category.phtml create mode 100644 admin/Photos/uploadFiles.php create mode 100644 admin/Photos/upload_simple.php create mode 100644 admin/Photos/uploadify.css create mode 100644 admin/Photos/yuiPhotoUploader.php create mode 100755 admin/index.phtml create mode 100755 admin/main.css create mode 100644 admin/nav.phtml create mode 100644 admin/rotatingImages.php create mode 100755 admin/splash.phtml create mode 100644 admin/toolbox.php create mode 100755 assets/IHG_Rewards_Club.jpg create mode 100755 assets/bg.jpg create mode 100755 assets/header_bg.png create mode 100755 assets/leftcol_bg.jpg create mode 100755 assets/logo.jpg create mode 100755 assets/main_bg.jpg create mode 100755 assets/nHeader.jpg create mode 100755 assets/nav.png create mode 100755 assets/priority_club.jpg create mode 100755 assets/reservation.jpg create mode 100755 assets/sister.png create mode 100755 assets/social.jpg create mode 100755 assets/title.jpg create mode 100755 assets/tripadv.jpg create mode 100755 calendar_icon.png create mode 100755 classes/class_db.inc create mode 100644 classes/class_template.inc create mode 100755 classes/class_toolbox.inc create mode 100644 combine.php create mode 100644 config/application.ini create mode 100644 config/server.ini create mode 100644 config/site.ini create mode 100644 css/contactform.css create mode 100755 css/dev/email.css create mode 100755 css/dev/gsearch.css create mode 100755 css/dev/ie7.css create mode 100644 css/email.css create mode 100755 css/gsearch.css create mode 100644 css/ie7.css create mode 100644 css/prod/email.css create mode 100644 css/prod/gsearch.css create mode 100644 css/prod/ie7.css create mode 100644 css/prod/styles.css create mode 100644 css/siteMap.css create mode 100755 images/add.png create mode 100644 images/amenities/1182867688waterfront.gif create mode 100644 images/amenities/1182867790sauna.gif create mode 100644 images/amenities/barrierfree.gif create mode 100644 images/amenities/beachaccess.gif create mode 100644 images/amenities/breakfast.gif create mode 100644 images/amenities/cable.gif create mode 100644 images/amenities/conference.gif create mode 100644 images/amenities/cont_break.gif create mode 100644 images/amenities/eff.gif create mode 100644 images/amenities/excersize.gif create mode 100644 images/amenities/free_internet.gif create mode 100644 images/amenities/guest_laundry.gif create mode 100644 images/amenities/internet.gif create mode 100644 images/amenities/kidfriendly.gif create mode 100644 images/amenities/meeting.gif create mode 100644 images/amenities/pets.gif create mode 100644 images/amenities/pool-out.gif create mode 100644 images/amenities/pool.gif create mode 100644 images/amenities/restaurant.gif create mode 100644 images/amenities/restnear.gif create mode 100644 images/amenities/sauna.gif create mode 100644 images/amenities/smokefree.gif create mode 100644 images/amenities/snowmobile.gif create mode 100644 images/amenities/waterfront.gif create mode 100644 images/amenities/waterview.gif create mode 100644 images/amenities/wireless.gif create mode 100644 images/application_edit.png create mode 100644 images/cross.png create mode 100644 images/delete.png create mode 100644 images/error.gif create mode 100644 images/file-ext/cad.gif create mode 100644 images/file-ext/doc.gif create mode 100644 images/file-ext/download.gif create mode 100644 images/file-ext/gif.gif create mode 100644 images/file-ext/html.gif create mode 100644 images/file-ext/jpg.gif create mode 100755 images/file-ext/movie.gif create mode 100644 images/file-ext/mp3.gif create mode 100644 images/file-ext/pdf.png create mode 100644 images/file-ext/ppt.gif create mode 100644 images/file-ext/rar.gif create mode 100644 images/file-ext/rm.gif create mode 100644 images/file-ext/txt.png create mode 100644 images/file-ext/xls.gif create mode 100644 images/file-ext/zip.png create mode 100644 images/find.png create mode 100644 images/flag_green.png create mode 100755 images/folder.png create mode 100755 images/folder_add.png create mode 100755 images/folder_delete.png create mode 100755 images/grnball.gif create mode 100755 images/help.gif create mode 100755 images/html.gif create mode 100755 images/img.gif create mode 100644 images/left.gif create mode 100644 images/loadingAnimation.gif create mode 100755 images/logo.gif create mode 100755 images/magnifier.png create mode 100755 images/members/add.png create mode 100755 images/members/application_edit.png create mode 100755 images/members/cancel.png create mode 100644 images/members/cardamex.gif create mode 100644 images/members/carddinner.gif create mode 100644 images/members/carddiscover.gif create mode 100644 images/members/cardmaster.gif create mode 100644 images/members/cardvisa.gif create mode 100755 images/members/cross.png create mode 100755 images/members/delete.png create mode 100755 images/members/find.png create mode 100644 images/members/img.gif create mode 100755 images/members/lock.png create mode 100755 images/members/note_edit.png create mode 100755 images/members/page_edit.png create mode 100755 images/members/tick.png create mode 100755 images/members/user_add.png create mode 100755 images/members/user_edit.png create mode 100644 images/note_edit.png create mode 100644 images/page_edit.png create mode 100755 images/redball.gif create mode 100644 images/right.gif create mode 100644 images/shadowb.gif create mode 100644 images/shadowr.gif create mode 100755 images/size.sh create mode 100644 images/tick.png create mode 100755 images/top2.jpg create mode 100644 images/user_add.png create mode 100644 images/user_edit.png create mode 100644 index.php create mode 100755 libjs/datepicker.js create mode 100644 libjs/dev/newsletterSignup.js create mode 100755 libjs/pagefunctions.js create mode 100644 libjs/prod/newsletterSignup.js create mode 100644 setup.phtml create mode 100644 setup_functions.phtml create mode 100755 static/1.phtml create mode 100755 static/2.phtml create mode 100755 static/3.phtml create mode 100755 static/4.phtml create mode 100755 static/5.phtml create mode 100755 static/6.phtml create mode 100755 static/8.phtml create mode 100755 styles.css create mode 100644 templates/siteMap.html create mode 100755 templates/template.html diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..30034b3 --- /dev/null +++ b/.htaccess @@ -0,0 +1,132 @@ + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + +ErrorDocument 404 /404.html +RewriteEngine On +AddDefaultCharset utf-8 + +RewriteBase /www.appletreeinn.com/ + +# Redirect non-www to www +RewriteCond %{ENV:GLM_HOST_ID} PRODUCTION +RewriteCond %{HTTP_HOST} !^www\. [NC] +RewriteCond %{HTTP_HOST} !^demo\. [NC] +RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] + +# CacheBusting +RewriteCond %{REQUEST_URI} v/[0-9\.]+/ +RewriteRule ^v/[0-9\.]+/(.*) $1 [L] + +RewriteRule ^events/([0-9]*)/([0-9]*)/$ index.php?catid=$1&eventid=$2 [QSA,L] +RewriteRule ^events/([0-9]*)/$ index.php?catid=$1 [QSA,L] + +RewriteRule ^VisitorGuide/(.*)/$ pdf-download.php?uidpdf=$1&pdf_file=VisitorGuide [L] +RewriteRule ^.*-([0-9]*)/([0-9]*)/$ index.php?catid=$1&photo_catid=$2 [L] +# rewrites for the toolbox pages +RewriteRule ^.*-([0-9]*)/index.php index\.php?%{QUERY_STRING} +RewriteRule ^.*-([0-9]*)/$ index\.php?catid=$1 [QSA,L] + +# trailing slash +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_URI} ^.*-([0-9]*)$ +RewriteRule ^(.*)$ %{REQUEST_URI}/ [L,R=301] + +############## +## MemberDB ## +############## +# Members only area +RewriteRule ^members-only-area/$ Toolkit/Members/MembersOnly/index.php [QSA,L] +RewriteRule ^member-area-google-map/$ Toolkit/Members/memberDBGoogleAreaMap.php [QSA,L] +RewriteRule ^member-city-google-map/$ Toolkit/Members/memberDBGoogleAreaMapCity.php [QSA,L] +# Ajax call for google map +RewriteRule ^member-db-google-map/$ Toolkit/Members/memberDBGoogleMap.php [QSA,L] +# Ajax call for google maps w/ SEO urls - extract catid from url to pass +# along w/ the query string. +RewriteRule ^.*-([0-9]*)/member-db-google-map/$ Toolkit/Members/memberDBGoogleMap.php?catid=$1 [QSA,L] +# short urls w/ google maps +RewriteRule ^([A-Za-z0-9_-]*)/member-db-google-map/$ Toolkit/Members/memberDBGoogleMap.php?glmPage=$1 [L] +# Downloading member files from profile pages +RewriteRule ^member-file/([0-9]*)/([0-9]*)/$ Toolkit/Members/memberFileDownload.php?mid=$1&fid=$2 [L] +# Ajax call for saving photo repositioning +RewriteRule ^member-save-photos/$ Toolkit/Members/sortPhotos.php [QSA,L] +RewriteRule ^memberdb-site-map index.php?catid=0&memberDbSiteMap=1 [L] + +RewriteRule ^map/([0-9A-F]{6})/([0-9]*).png Toolkit/Maps/marker.php?color=$1&text=$2 [L] +RewriteRule ^areamap/([0-9A-F]{6}).png Toolkit/Maps/marker2.php?color=$1 [L] + +# Trip planner +RewriteRule ^trip-planner-map.js$ Toolkit/Members/libjs/trip-planner-map.js [L] +RewriteRule ^trip-planner-members/$ Toolkit/Members/TripPlanner/googleMapData.php [L] +RewriteRule ^trip-planner-wish-list/([0-9]*)/([0-9]*)/$ Toolkit/Members/TripPlanner/wish-list.php?catid=$1&member_id=$2&detail=1 [L] +# This is the rewrite rule for the pending member emails that get sent +# out when a user updates their member record from the members only area. +RewriteRule ^pending-member/([0-9]*)/$ admin/members.php?page=memberUpdates&module=authorizeUpdates&id=$1 [L] +# Profile pages +RewriteRule ^member-profile/([0-9]*)/([0-9]*)/$ index.php?catid=$1&member_id=$2 [L] + +# trip planner list (member sessions) +RewriteRule ^trip-planner-list/([0-9]*)/([0-9]*)/ Toolkit/Members/TripPlanner/memberList.php?member_id=$1&catid=$2 [L] + +############# +## Banners ## +############# +# Ajax call for incrementing rotating banner impressions +RewriteRule ^rotating-banner/([0-9]*)/([0-9]*)/$ Toolkit/Banners/incrementRotatingBanner.php?banner=$1&catid=$2 [L] + +############ +## Blocks ## +############ +RewriteRule ^block-pos/ Toolkit/Blocks/positionBlock.php [QSA,L] + +############# +## Toolbox ## +############# +# Ajax call for changing state (active/inactive) +RewriteRule ^toolbox-change-state/([0-9]*)/ Toolkit/Toolbox/pageChangeState.php?kpass=&catid=$1 [L] +RewriteRule ^toolbox-change-state-mobile/([0-9]*)/ Toolkit/Toolbox/pageMobileChangeState.php?kpass=&catid=$1 [L] +RewriteRule ^toolbox-paragraph-change-state/([0-9]*)/ Toolkit/Toolbox/paragraphChangeState.php?kpass=¶graphId=$1 [L] +# Ajax call for changing position (move up / move down) +RewriteRule ^toolbox-page-move/cat_([0-9]*)/([a-z]*)/$ Toolkit/Toolbox/pageMove.php?id=$1&direction=$2&kpass= [L] +RewriteRule ^toolbox-page-move-sel/pos([0-9]*)/([0-9]*)/([0-9]*)/$ Toolkit/Toolbox/moveBySelect.php?id=$1&oldpos=$2&newpos=$3 [L] +RewriteRule ^toolbox-paragraph-move-sel/pos([0-9]*)/([0-9]*)/([0-9]*)/$ Toolkit/Toolbox/moveBySelectPara.php?id=$1&oldpos=$2&newpos=$3 [L] +RewriteRule ^toolbox-paragraph-move/cat_([0-9]*)/([a-z]*)/$ Toolkit/Toolbox/paragraphMove.php?id=$1&direction=$2&kpass= [L] +# Ajax call for uploading a file +RewriteRule ^toolbox-paragraph-upload/$ Toolkit/Toolbox/paragraphFileUpload.php?kpass= [L] + +################ +## short urls ## +################ +#RewriteCond %{REQUEST_URI} !(^.*-([0-9]*)/$) +#RewriteRule ^([A-Za-z0-9_-]*)/$ index.php?glmPage=$1 [L] + +RewriteRule site-map index.php?catid=1&sitemap=1 + +############### +## Templates ## +############### +# View flexy templates as php files +AddType application/x-httpd-php .tpl + +############### +## Videos ## +############### +# call for changing position on videos +RewriteRule ^video-move/([0-9]*)/([0-9]*)/$ Toolkit/Videos/moveVideo.php?kpass=&id=$1&newpos=$2 +# Toggle active on / off +RewriteRule ^video-active-toggle/([0-9]*)/ Toolkit/Videos/toggleActive.php?kpass=&id=$1 +# Toggle featured on /off +RewriteRule ^video-featured-toggle/([0-9]*)/ Toolkit/Videos/toggleFeatured.php?kpass=&id=$1 + +############### +## REDIRECTS ## +############### + diff --git a/Toolkit/BaseControllerAbstract.php b/Toolkit/BaseControllerAbstract.php new file mode 100644 index 0000000..edda16e --- /dev/null +++ b/Toolkit/BaseControllerAbstract.php @@ -0,0 +1,50 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +/** + * Toolkit_BaseControllerAbstract + * + * Creates object of toolkit registry + * + * @category Toolkit + * @package Toolkit_BaseControllerAbstract + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_BaseControllerAbstract +{ + /** + * Description of $registry + * @var Toolkit_Registry + * @access protected + */ + protected $registry; + + /** + * Class constructor + * + * Creates object of Toolkit Registry + * + * @param Toolkit_Registry $registry Toolkit Registry + */ + public function __construct(Toolkit_Registry $registry) + { + $this->registry = $registry; + } +} +?> diff --git a/Toolkit/BreadCrumbsFactory.php b/Toolkit/BreadCrumbsFactory.php new file mode 100644 index 0000000..7f194a2 --- /dev/null +++ b/Toolkit/BreadCrumbsFactory.php @@ -0,0 +1,85 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_BreadCrumbsFactory + * + * Description of Toolkit_BreadCrumbsFactory + * + * @category Toolkit + * @package Members_MembersOnly + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_BreadCrumbsFactory +{ + /** + * Description of $_gatewayFactory + * @var Toolkit_Toolbox_GatewayFactoryAbstract + * @access private + */ + private $_gatewayFactory; + + /** + * Class constructor + * + * @param Toolkit_Toolbox_GatewayFactoryAbstract $factory Gateway Factory + * + * @return void + * @access public + */ + public function __construct( + Toolkit_Toolbox_GatewayFactoryAbstract $factory + ) { + $this->_gatewayFactory = $factory; + } + + /** + * Description for createBreadCrumbsHelper + * + * @return \Toolkit_Template_BreadCrumbs + * @access public + */ + public function createBreadCrumbsHelper() + { + $gateway = $this->_gatewayFactory->createGateway(); + if (isset($_GET['member_id']) + && ctype_digit((string)$_GET['member_id']) + ) { + $breadCrumbs = new Toolkit_Members_BreadCrumbs( + $gateway, + Toolkit_Database::getInstance() + ); + } elseif ($gateway instanceof Toolkit_Toolbox_PageGatewayDraft) { + // Need to have a publish gateway so we can get parent pages + $publishGateway = new Toolkit_Toolbox_PageGatewayPublish( + Toolkit_Database::getInstance() + ); + + $breadCrumbs = new Toolkit_Template_DraftBreadCrumbs( + $publishGateway, + $gateway + ); + } else { + $breadCrumbs = new Toolkit_Template_BreadCrumbs($gateway); + } + + return $breadCrumbs; + } +} +?> diff --git a/Toolkit/CKImages/Connector.php b/Toolkit/CKImages/Connector.php new file mode 100644 index 0000000..2af9354 --- /dev/null +++ b/Toolkit/CKImages/Connector.php @@ -0,0 +1,400 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Connector.php,v 1.15 2010/07/20 01:19:50 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + + +/** + * Connects the CKImage browser to the server for image manipulation + * + * @category CKImages + * @package Toolkit_CKImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + */ +class Toolkit_CKImages_Connector +{ + // {{{ setDbh() + + /** + * Sets the database handler for the object to use + * + * @param PDO $pdo PHP Data Object + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ createFolder() + + /** + * Creates a new folder + * + * @return void + * @access public + */ + public function createFolder() + { + // get the folder id + $folder = filter_var( + $_GET['name'], + FILTER_SANITIZE_STRING, + FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH + ); + if ($parent = filter_var($_GET['folder'], FILTER_VALIDATE_INT)) { + // do nothing, $parent set and validated + // from the $_GET['folder'] variable + } else { + $parent = 1; + } + + // if the parentFolder variable is set and valid, then override the + // existing parent folder value + if ($newParent = filter_var($_GET['parentFolder'], FILTER_VALIDATE_INT)) { + $parent = $newParent; + } + + // unset unneeded param values + unset($_GET['command'], $_GET['name'], $_GET['parentFolder']); + + try { + $sql = " + INSERT INTO ckeditor_folders(name, parent) + VALUES (:name, :parent)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $folder, PDO::PARAM_INT); + $stmt->bindParam(':parent', $parent, PDO::PARAM_INT); + $stmt->execute(); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ deleteFile() + + /** + * Deletes a file from the image server for client + * + * @param Toolkit_FileServer_ImageAdapter $ia Image Server Object + * + * @return void + * @access public + */ + public function deleteFile(Toolkit_FileServer_ImageAdapter $ia) + { + $getImg = filter_input(INPUT_GET, 'img'); + // Get offset where target img starts at + $start = strrpos($getImg, '/') + 1; + // get the image name + $img = substr($getImg, $start); + // unset unneeded param values + unset($_GET['command'], $_GET['img']); + + $ia->delete($img); + + try { + $sql = " + DELETE FROM ckeditor_images + WHERE name_on_disk = :nod"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':nod', $img, PDO::PARAM_STR); + $stmt->execute(); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ deleteFolder() + + /** + * Deletes a folder and any sub folders + * + * Moves all containing images to home folder so they are not + * inadvertently deleted + * + * @return void + * @access public + */ + public function deleteFolder() + { + // get the folder id + $folder = $_GET['folder']; + if ($folder == 1) { + unset($_COOKIE['glm_image_browser_open'], $_COOKIE['glm_image_browser_selected']); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + exit(); + } + // unset unneeded param values + unset($_GET['command'], $_GET['tgt']); + $_GET['folder'] = 1; + + try { + $tree = Toolkit_Common::getHierarchicalTreeStructure( + $this->dbh, + 'ckeditor_folders', + 'id', + 'parent', + 'id', + $folder, + 0, + false + ); + + $sql = " + UPDATE ckeditor_images + SET folder = 1 + WHERE folder = :folder"; + + $imgStmt = $this->dbh->prepare($sql); + + $sql = " + DELETE FROM ckeditor_folders + WHERE id = :folder"; + $fldrStmt = $this->dbh->prepare($sql); + while (list($tgt) = each($tree)) { + $imgStmt->bindParam(':folder', $tgt, PDO::PARAM_INT); + $imgStmt->execute(); + + $fldrStmt->bindParam(':folder', $tgt, PDO::PARAM_INT); + $fldrStmt->execute(); + } + // These cookies are defined in the libjs/image_selector.js file + // when the tree is created. + unset($_COOKIE['glm_image_browser_open'], $_COOKIE['glm_image_browser_selected']); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ browseImages() + + /** + * Creates the browser window + * + * @param HTML_Template_Flexy $tEngine Flexy Rendering Engine Object + * + * @return string HTML page to browse images + * @access public + */ + public function browseImages(HTMl_Template_Flexy $tEngine) + { + $page = new stdClass(); + $page->baseUrl = BASE_URL; + $page->glmAppBaseUrl = GLM_APP_BASE_URL; + $page->originalPath = CKIMAGE; + $page->imageManager = IMAGE_MANAGER; + + if ($folderId = filter_input(INPUT_GET, 'folder', FILTER_VALIDATE_INT)) { + $folder = "&folder=$folderId"; + } else { + $folder = ''; + } + + $ckEditorFuncNum + = filter_input(INPUT_GET, 'CKEditorFuncNum', FILTER_VALIDATE_INT); + $ckEditor = filter_input(INPUT_GET, 'CKEditor'); + $langCode = filter_input(INPUT_GET, 'langCode'); + + $form = new HTML_QuickForm( + 'quick_upload', + 'post', + BASE_URL . "Toolkit/CKImages/controller.php?CKEditor=$ckEditor&CKEditorFuncNum=$ckEditorFuncNum&langCode=$langCode&command=UploadFile$folder" + ); + $form->addElement('file', 'upload'); + $page->quickUploadForm = $form->toHtml(); + + $folders = new Toolkit_CKImages_Folders($this->dbh); + $page->folders = $folders->getFolders(0); + + try { + $ckEditorFolderId = $folderId ? $folderId : 1; + $sql = " + SELECT * + FROM ckeditor_images + WHERE folder = :folder + ORDER BY id ASC"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':folder', $ckEditorFolderId, PDO::PARAM_INT); + $stmt->execute(); + + $images = $stmt->fetchAll(PDO::FETCH_ASSOC); + // loop thru images and reset their sizes + $isa = new Toolkit_FileServer_ImageAdapter(); + if (is_array($images) && !empty($images)) { + foreach ($images as &$img) { + if ( $img['original_width'] > 700 + || $img['original_height'] > 500 + ) { + // get real size for the CKImage Style + $imgData = $isa->getImageSize(CKIMAGE . $img['name_on_disk']); + $img['original_width'] = $imgData[0]; + $img['original_height'] = $imgData[1]; + } + } + } + $page->images = $images; + $page->CKEditorFuncNum = $ckEditorFuncNum; + + $tEngine->compile('thumbnails.html'); + $tEngine->outputObject($page); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ handleUpload() + + + /** + * Handles inserting the upload into the database + * + * @param string $imageName image to insert + * @param array $dimensions dimensions of the image + * + * @return object Return description (if any) ... + * @access protected + */ + protected function handleUpload($imageName, array $dimensions) + { + if ( !$dimensions['oWidth'] + || !$dimensions['oHeight'] + ) { + return false; + } + try { + if ($folder = filter_input(INPUT_GET, 'folder', FILTER_VALIDATE_INT)) { + // do nothing, $folder is already set and validated + } else { + $folder = 1; + } + $sql = " + INSERT INTO ckeditor_images (file_name, name_on_disk, folder, + original_width, original_height) + VALUES (:fname, :nod, :folder, :width, :height)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':fname', + $_FILES['upload']['name'], + PDO::PARAM_STR + ); + $stmt->bindParam(':nod', $imageName, PDO::PARAM_STR); + $stmt->bindValue(':folder', $folder, PDO::PARAM_INT); + $stmt->bindValue(':width', $dimensions['oWidth'], PDO::PARAM_INT); + $stmt->bindValue(':height', $dimensions['oHeight'], PDO::PARAM_INT); + + + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ quickUpload() + + + /** + * send uploaded image to image server + * + * @param Toolkit_FileServer_ImageAdapter $ia Image Server + * + * @return void + * @access public + */ + public function quickUpload(Toolkit_FileServer_ImageAdapter $ia) + { + try { + ob_start(); + $image = $ia->upload('upload'); + ob_end_clean(); + } catch (RangeException $e) { + Toolkit_Logger::logException('Runtime Error', $e); + throw new Toolkit_CKImages_Exception('Error uploading image'); + } + + $dimensions = $ia->getImageSize(CKIMAGE . $image['name']); + list($i['oWidth'], $i['oHeight'],) = $dimensions; + $this->handleUpload($image['name'], $i); + + unset($_GET['command']); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } + + // }}} + + // {{{ uploadFile() + + + /** + * send uploaded image to image server and select that file to be used + * + * @param Toolkit_FileServer_ImageAdapter $ia Image server object + * + * @return void + * @access public + */ + public function uploadFile(Toolkit_FileServer_ImageAdapter $ia) + { + if ($ckEditorFuncNum = filter_input(INPUT_GET, 'CKEditorFuncNum', FILTER_VALIDATE_INT)) { + // Do nothing, $ckEditorFuncNum set and validated + } else { + $ckEditorFuncNum = 1; + } + echo ''; + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/Database/Import.php b/Toolkit/CKImages/Database/Import.php new file mode 100755 index 0000000..6b871ea --- /dev/null +++ b/Toolkit/CKImages/Database/Import.php @@ -0,0 +1,145 @@ +dbh = $pdo; + $this->pathToImages = BASE . 'images/ht_images/'; + $this->urlPathToImages = HT_IMAGES_URL; + $this->is = new Toolkit_Image_Server(); + } + // }}} + // {{{ addFolderToDatabase() + function addFolderToDatabase($folder, $parent) + { + static $stmt; + if (!$stmt) { + $sql = " + INSERT INTO ckeditor_folders + (name, parent) + VALUES + (:name, :parent) + RETURNING id"; + $stmt = $this->dbh->prepare($sql); + } + try { + $stmt->bindParam(":name", $folder, PDO::PARAM_STR); + $stmt->bindParam(":parent", $parent, PDO::PARAM_STR); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + // }}} + // {{{ addImageToDatabase() + function addImageToDatabase($file, $folder) + { + static $stmt; + if (!$stmt) { + $sql = " + INSERT INTO ckeditor_images + (file_name, name_on_disk, original_width, original_height, folder) + VALUES + (:file_name, :name_on_disk, :original_width, :original_height, :folder)"; + $stmt = $this->dbh->prepare($sql); + } + try { + $stmt->bindParam(":file_name", $file['file_name'], PDO::PARAM_STR); + $stmt->bindParam(":name_on_disk", $file['name_on_disk'], PDO::PARAM_STR); + $stmt->bindParam(":original_width", $file['original_width'], PDO::PARAM_STR); + $stmt->bindParam(":original_height", $file['original_height'], PDO::PARAM_STR); + $stmt->bindParam(":folder", $folder, PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + }// }}} + // {{{ processFilesArray + function processFilesArray($files, $parent = 1) + { + //echo '
'.print_r($files, true).'
'; + foreach ($files as $folderName => $file) { + if (is_array($file)) { + $fKey = key($file); + $folderToAdd = ereg_replace("/$", "", $fKey); + //echo '
'.print_r($folderToAdd, true).'
'; + $folder = $this->addFolderToDatabase($folderToAdd, $parent); + //echo '
'.print_r($folder, true).'
'; + //var_dump($files[$folderName][$fKey]); + // echo '
'.print_r($file[$folderName][$fKey], true).'
'; + $processedFile[] = $this->processFilesArray($files[$folderName][$fKey], $folder); + } else { + $processedFile[] = $this->sendToImageServer($file, $parent); + } + } + return $processedFile; + } + // }}} + // {{{ readImageDir() + function readImageDir($path = '') + { + $dirName = $this->pathToImages . ereg_replace("/$", "", $path); + //var_dump($dirName);echo '
'; + $d = dir($dirName); + while (false !== ($entry = $d->read())) { + if (!ereg("^\.|^CVS", $entry)) { + $entryPath = $this->pathToImages . $path . $entry; + //var_dump($entryPath); echo '
'; + if ($dirCheck = is_dir($entryPath)) { + $files[$path][] = $this->readImageDir($path . $entry . '/'); + } else if ($fileCheck = is_file($entryPath)) { + $files[$path][] = $path . $entry; + } + } + } + return $files; + } + // }}} + //{{{ runImport() + function runImport() + { + $files = $this->readImageDir(); + echo '
'.print_r($files, true).'
'; + $processedFiles = $this->processFilesArray($files['']); +// echo '
'.print_r($processedFiles, true).'
'; + } + //}}} + // {{{ sendToImageServer() + function sendToImageServer($file, $folder) + { + $file_name = basename($file); + $size = getImageSize($this->pathToImages . $file); + try { + $urlToImage = $this->urlPathToImages . '/' . str_replace(' ', '%20', $file); + $name_on_disk = $this->is->imageUpload( + $urlToImage + ); +// var_dump($name_on_disk); +// var_dump($this->urlPathToImages); +// exit; + } catch(PEAR_Exception $e) { + var_dump($file); + var_dump($urlToImage); + var_dump($e); + exit; + } + $image = array( + 'name_on_disk' => $name_on_disk, + 'file_name' => $file_name, + 'original_width' => $size[0], + 'original_height' => $size[1], + ); + $this->addImageToDatabase($image, $folder); + } + // }}} +} +?> diff --git a/Toolkit/CKImages/Database/application.sql b/Toolkit/CKImages/Database/application.sql new file mode 100644 index 0000000..d3abc1e --- /dev/null +++ b/Toolkit/CKImages/Database/application.sql @@ -0,0 +1,21 @@ +CREATE SCHEMA ckimages; +GRANT ALL ON SCHEMA ckimages TO nobody; + +-- +-- Tables +-- +\i ./tables/ckeditor_folders.sql +\i ./tables/ckeditor_images.sql + +-- +-- Procedures +-- + +-- +-- Modules +-- + +-- +-- Data +-- +\i ./data/applicationData.sql diff --git a/Toolkit/CKImages/Database/data/applicationData.sql b/Toolkit/CKImages/Database/data/applicationData.sql new file mode 100644 index 0000000..e4159a5 --- /dev/null +++ b/Toolkit/CKImages/Database/data/applicationData.sql @@ -0,0 +1,2 @@ +INSERT INTO ckimages.ckeditor_folders(id, name, parent) VALUES(1, 'Home', 0); +SELECT setval('"ckimages".ckeditor_folders_id_seq', 2, false); diff --git a/Toolkit/CKImages/Database/importHtImages.php b/Toolkit/CKImages/Database/importHtImages.php new file mode 100755 index 0000000..5aaa481 --- /dev/null +++ b/Toolkit/CKImages/Database/importHtImages.php @@ -0,0 +1,10 @@ +runImport(); +?> diff --git a/Toolkit/CKImages/Database/phpImageEditorUpdates.sql b/Toolkit/CKImages/Database/phpImageEditorUpdates.sql new file mode 100644 index 0000000..28b86c2 --- /dev/null +++ b/Toolkit/CKImages/Database/phpImageEditorUpdates.sql @@ -0,0 +1,2 @@ +ALTER TABLE ckimages.ckeditor_images + ADD COLUMN original_image TEXT; diff --git a/Toolkit/CKImages/Database/removeApplication.sql b/Toolkit/CKImages/Database/removeApplication.sql new file mode 100644 index 0000000..4cd6978 --- /dev/null +++ b/Toolkit/CKImages/Database/removeApplication.sql @@ -0,0 +1,9 @@ +-- +-- This will drop everything in the ckimages schema +-- Nothing better be in here except ckeditor related object +-- or it will be dropp +-- +-- The force is strong w/ this one, use it wisely. +-- + +DROP SCHEMA IF EXISTS ckimages CASCADE; diff --git a/Toolkit/CKImages/Database/tables/ckeditor_folders.sql b/Toolkit/CKImages/Database/tables/ckeditor_folders.sql new file mode 100644 index 0000000..1331175 --- /dev/null +++ b/Toolkit/CKImages/Database/tables/ckeditor_folders.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS ckimage.ckeditor_folders CASCADE; + +CREATE TABLE ckimages.ckeditor_folders +(id SERIAL, + name TEXT NOT NULL, + parent INTEGER DEFAULT 1 NOT NULL, + PRIMARY KEY (id)); + +GRANT ALL ON ckimages.ckeditor_folders_id_seq TO nobody; +GRANT ALL ON ckimages.ckeditor_folders TO nobody; diff --git a/Toolkit/CKImages/Database/tables/ckeditor_images.sql b/Toolkit/CKImages/Database/tables/ckeditor_images.sql new file mode 100644 index 0000000..a693799 --- /dev/null +++ b/Toolkit/CKImages/Database/tables/ckeditor_images.sql @@ -0,0 +1,19 @@ +DROP TABLE IF EXISTS ckimages.ckeditor_images CASCADE; + +CREATE TABLE ckimages.ckeditor_images +(id SERIAL, + create_date DATE DEFAULT CURRENT_DATE, + file_name text NOT NULL, + name_on_disk text NOT NULL, + original_width TEXT NOT NULL, + original_height TEXT NOT NULL, + original_image TEXT, + folder INTEGER DEFAULT 1 + REFERENCES ckimages.ckeditor_folders (id) + ON UPDATE CASCADE + ON DELETE SET DEFAULT, + PRIMARY KEY (id) +); + +GRANT ALL ON ckimages.ckeditor_images_id_seq TO nobody; +GRANT ALL ON ckimages.ckeditor_images TO nobody; diff --git a/Toolkit/CKImages/Exception.php b/Toolkit/CKImages/Exception.php new file mode 100644 index 0000000..3ea1bbd --- /dev/null +++ b/Toolkit/CKImages/Exception.php @@ -0,0 +1,3 @@ + diff --git a/Toolkit/CKImages/Factory.php b/Toolkit/CKImages/Factory.php new file mode 100644 index 0000000..a693896 --- /dev/null +++ b/Toolkit/CKImages/Factory.php @@ -0,0 +1,83 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Factory.php,v 1.1 2009/09/24 14:43:02 jamie Exp $ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ + + +/** + * CKImage Factory + * + * @category CKImages + * @package Toolkit_CKImages + * @author Jamie Kahgee + * @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_CKImages_Factory +{ + // {{{ properties + + /** + * array of instances + * @var array + * @access public + * @static + */ + public static $instances = array(); + + // }}} + // {{{ init() + + /** + * initialize the factory + * + * @return void + * @access public + * @static + */ + public static function init() + { + } + + // }}} + // {{{ &instance() + + /** + * Get a single instance of an object + * + * @param string $class Class name to create + * + * @return mixed instantiated object + * @access public + * @static + */ + public static function &instance($class) + { + $class = "Toolkit_CKImages_$class"; + + if (empty(Toolkit_CKImages_Factory::$instances)) { + Toolkit_CKImages_Factory::$instances[$class] = new $class; + } + + return Toolkit_CKImages_Factory::$instances[$class]; + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/Folders.php b/Toolkit/CKImages/Folders.php new file mode 100644 index 0000000..2858948 --- /dev/null +++ b/Toolkit/CKImages/Folders.php @@ -0,0 +1,243 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Folders.php,v 1.6 2009/10/27 14:39:27 jamie Exp $ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ + +/** + * Handles create a UL list to simulate a folder hierarchy + * + * @category CKImages + * @package Toolkit_CKImages + * @author Jamie Kahgee + * @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_CKImages_Folders +{ + // {{{ properties + + + /** + * Levels deep we are into the hierarchy + * @var integer + * @access private + */ + private $_lvlsOpen = 0; + + /** + * The previous level we were at + * @var integer + * @access private + */ + private $_prevLvl = 0; + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * + * @return void + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ closeFolder() + + + /** + * Closes a folder level + * + * @return string closing ul tag + * @access protected + */ + protected function closeFolder() + { + return "\n"; + } + + // }}} + // {{{ closeNode() + + + /** + * Closes a node + * + * @return string closing li tag + * @access protected + */ + protected function closeNode() + { + return "\n\t"; + } + + // }}} + // {{{ createFolder() + + + /** + * Creates a folder level + * + * @return string opening ul tag + * @access protected + */ + protected function createFolder() + { + return "\n
    "; + } + + // }}} + // {{{ createLink() + + + /** + * Creates a folder link so we can browse to each folder + * + * @param array $row Folder information + * + * @return string anchor link for folder + * @access protected + */ + protected function createLink(array $row) + { + $format = '%s'; + + $link = sprintf( + $format, + ($_GET['folder'] == $row['id']) ? 'clicked' : null, + $_GET['CKEditor'], + $_GET['CKEditorFuncNum'], + $_GET['langCode'], + $row['id'], + $row['name'] + ); + + return $link; + } + + // }}} + + // {{{ fetchFoldersArray() + + + /** + * Fetches a tree hierarchy of the folder structure into a linear array + * + * @param integer $start node to start at + * + * @return array folder structure with levels + * @access protected + */ + protected function fetchFoldersArray($start) + { + return Toolkit_Common::getHierarchicalTreeStructure( + $this->dbh, + 'ckeditor_folders', + 'id', + 'parent', + 'id', + $start + ); + } + + // }}} + + // {{{ getFolders() + + + /** + * Gets the folders ul list + * + * @param integer $parent start at a certain level + * + * @return string list of folders + * @access public + */ + public function getFolders($parent = 0) + { + $folders = $this->fetchFoldersArray($parent); + try { + $sql = " + SELECT * + FROM ckeditor_folders + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + foreach ($folders as $i => $j) { + $stmt->bindParam(':id', $i, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($j == $this->_prevLvl) { + $tree .= $this->openNode($row); + $tree .= $this->createLink($row); + $this->_prevLvl = $j; + } elseif ($j > $this->_prevLvl) { + ++$this->_lvlsOpen; + $tree .= $this->createFolder(); + $tree .= $this->openNode($row); + $tree .= $this->createLink($row); + $this->_prevLvl = $j; + } elseif ($j < $this->_prevLvl) { + do { + $tree .= $this->closeNode(); + $tree .= $this->closeFolder(); + } while (--$this->_lvlsOpen > $j); + $tree .= $this->closeNode(); + $tree .= $this->openNode($row); + $tree .= $this->createLink($row); + $this->_prevLvl = $this->_lvlsOpen; + } + } + $tree .= $this->closeFolder(); + return $tree; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ openNode() + + + /** + * Opens a branch or leaf node + * + * @param array $row Folder information + * + * @return string opening li tag + * @access protected + */ + protected function openNode(array $row) + { + return "\n\t
  • "; + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/ImageUpdater.php b/Toolkit/CKImages/ImageUpdater.php new file mode 100644 index 0000000..b0faaa4 --- /dev/null +++ b/Toolkit/CKImages/ImageUpdater.php @@ -0,0 +1,95 @@ +_dbh = $dbh; + } + + // }}} + + // {{{ load() + + public function load($image) + { + try { + $sql = " + SELECT * + FROM ckeditor_images + WHERE name_on_disk = :image"; + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':image', $image, PDO::PARAM_STR); + $stmt->setFetchMode(PDO::FETCH_INTO, $this); + $stmt->execute(); + $this->_imageData = $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_CKImages_Exception( + "Error fetching image row for image `$image`" + ); + } + } + + // }}} + // {{{ update() + + public function update(Toolkit_FileServer_ImageAdapter $ia) + { + if ( !is_array($this->_imageData) + || empty($this->_imageData) + ) { + throw new RuntimeException( + 'You must load an image first before trying to update' + ); + } + + $targetImage = $this->_imageData['name_on_disk']; + + $path = BASE . "Toolkit/CKImages/editedImages/$targetImage"; + $newImage = $ia->uploadImageFile($path); + list($w, $h, ) = $ia->getImageSize(CKIMAGE_ORIGINAL . $newImage['name']); + + try { + $sql = " + UPDATE ckeditor_images + SET original_image = COALESCE(original_image, name_on_disk), + file_name = :image_name, + name_on_disk = :newFileName, + original_width = :newWidth, + original_height = :newHeight + WHERE name_on_disk = :originalFileName + OR original_image = :originalFileName"; + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':newFileName', $newImage['name'], PDO::PARAM_STR); + $stmt->bindParam(':image_name', $_REQUEST['image_name'], PDO::PARAM_STR); + $stmt->bindParam(':newWidth', $w, PDO::PARAM_INT); + $stmt->bindParam(':newHeight', $h, PDO::PARAM_INT); + $stmt->bindParam(':originalFileName', $targetImage, PDO::PARAM_STR); + $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_CKImages_Exception( + "Error updating image `{$this->_imageData['name_on_disk']}`" + ); + } + + // If we have updated the file previously + // then remove the old update - b/c it will now be orphaned. + if ($targetImage == $this->_imageData['original_image']) { + $ia->delete($this->_imageData['name_on_disk']); + } + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/assets/.keepme b/Toolkit/CKImages/assets/.keepme new file mode 100644 index 0000000..e69de29 diff --git a/Toolkit/CKImages/assets/night-fate-stock2.jpg b/Toolkit/CKImages/assets/night-fate-stock2.jpg new file mode 100755 index 0000000000000000000000000000000000000000..93fc3757a9844c02b014491617d206e5d501dac1 GIT binary patch literal 10337 zcmY+qcT|&E)HQz75JQn*0wD^c! zGys7Da8&w$jjsS@A9o}&9zXyb0H7uf{S6dtkDdxS29CB!Ban^P-~vD?C@3f@C@U%| z<4{{rxE-p>%BnjEs{ajw<~9v=b&YMBn%X2ilD4L)>HhturndikK$KA^vB_mX`l}zU@W}K*>UVV0ajW0H7!c z3o%H3U_~ssr_yyPfTgRKnTp;AX)3y{YHG7OUJ>Ft5& zv(YcJ_MPi}uso$UQ=3j;9}5F>N=YAyh8L^#^549=Svbk}uV}bnnw$Hl|8y5=Dm-Mi zB53)@FPk@^GR-2?sN1s02CV!P=!!UJT4&*2_P^apAC6xCPQPw zb5^cl7yfy7j##|)$ib~a*~2e=qNvaTVVXg=ChB4!#-e`xuNvpI?LwT~fN*WgAo8{; zcN&Mh>**pEq4L&5(B^`R}8qc0jDzO40h`$VsZ&d8#v;^t5T#{ zrJv>kd2$jA$Z!SFeg{PC@Q#d`aJz<8sM~tt(U{rcl+9;$6PPKx z56CzQm@|5ei#0`S53I0p+cI{0>}(=N(2}OZ0Z;Pio%g4LpYT=!q|y~E39|F`CrycSqGeutr*f|5bjJX=Am-Memm z@T+X2L!X7P>_tEZ|H9Hh+#refc)Lgm=iDbLn>euAPD6`-W_Vq8qB0%P>^eQ>q+|n> z!j-?P5IP_*D8NqxyiYW?#q5c1Ly^KtIJWbCzivcq#3qjrkcQxA`Np}|=OcvYx?is7 zZRH;`w+T09DuiPzLrYUpf)GsnjVsbTY5^#DQ}^hp^pc*axqlWd&kyGoke+sUgy^}Z zhHyHLsVLWK6(y@-3n!PRCQ{>mxu@@r*a^@izcVU;lgH;O+C9z6hvs`AULaC%>xsyA zwT}jJ5ZF?BNEj)0EHK^pq`_11wE+5juBCv;hOs`=>|+tI1%xt#OASzC0z_iglB z&+<)7pC$)X_oxU9g-y}Yp4=lJN&&ZXzdZ|^e@Lu7)O@zNFRmXlnd+;5a&-etejTbmJ+}P2&4obg>L0ayjV(RHK|^lxtke_v znDpwgEj3MC+1xx5E+n7oYLQPC1z*?C*xQ!3HD1|34wpS94CgWmlGF(7P;-b@eRQ;T zG4sZck31=YDB0LYIv8d7D|o>BNVP@Fz`-UsfH>!~cMWr)Iq~0@Yh5~G&w5Uk*6#7z zH~&2%xITB+q>g7b+^EemVz;g(XuLN4q2K*JOWY^+%y-z)~YvoA7T3~8^sm=xv8&QvA zaxz3>5nq4}zx1@x$B^bbFS&H%6RErWr4Z)-ArVrl7wA87#wQ7*Qa#D@o{)T8`*V0K zQDgs^hw+zOvTDTReb+gtj+Pe=}sLBB?J5M+&yOzYNiK zs>xg7w3i28ms9gFv&B%@YMvzFl~Px+0?whE;h}#ZKTIBbJR@7~X{(1k8wRK$oMcEg zz2f|iJ02!;zmy+rfIWoj{+JpW*lzA=QTWgU=bo%2Lq<{B=k?LobuZV7iiV9AJ4qa=Bg|ceOMi;qqv1GuQ2Yb602StNY)E);(7=xQ$m6AI*Py^7j0d z!*zRzubU4IpPVp_yySlMRQ3kwVr@Y_D=bF&`V`}QI73R96wIa8GzDfXBS3X)go62$ zU+>ZF-DxruA+or;iX{_pI`Qx!?|;6`PvH%6L-*qB#hb(f@DuqLy}b~Xj{DSV z^6A;=z?WfM72|v#e-RhJnI0@xN)Ne%Op~3Kn>NygXQdJ@Y=XQX@GqkQww?LP=b;=# zMjKL9h%t-CLbAp`UCEj%`|J={)_r*I!aa!#B=|xH*Hr6SY7kQ+OF4qHv};uLZlJh1 z&~-Umn^09H6!R%ao+$5v6y1N2nG-0Q8VtrhVpNv%AY9J2u; zPHoxKe7A9}Z1IovvdACDJj6x3o!jD+{D|S6N?9&EF z!_1#q4?awYxMzUneEZ%@{@xQ}{u}?!Y(W5#V_tkP;fwU&O2W+kU>tw}I}R6_TswdvZORl6^}9L?TL@l|gNl^;;{%xI7LWX= z@Evl+IeT1MOy8P%Rwm})aC<`jRV!b*bTT^O=LSICJ$Ja`a`R2y@(r$@d6sy|$Wp7+%{04591?&hg;++gytW|}aL-rK)1sxNY99@`kGwQqnKo4N_}sQ{0? z)+>>o-p(HvCwkue{&W8G_kzEI8f7HUwdO zL@^8*42Ba2ChggdNKR&c6co#cf5f6gA~+eYkE*+fue-OYC>U?O!1r|2kcVzcQQBiu zyAn(O=hr4HO%Z(>vRlmG=63d*_i8rH4ENrmxPzUN_XCd7hJE&ftslL;wBP_EKQ%Pkx?ngTF^dG*=T77eD6oaY0c;~FQ zxAmn*8=xm^YGj_Pku8pn`ljPFb0IhBM7GV>zUJV_K=;5O{n)GvdSvYv3iq_I-ha#c)a*iH%_nU#^nz8A*z;A3TY9AZ$ElNIHgo-0ot ziUvW92Kl+O86(={b~52J#N4LaET|-Pg-#9qBj%UGDajTm?TQp(+S&rQWOA(Ee<3o_ z^7Aim%fyg8_|Y3X*{!OXzDvFP+&x3&oxFC*=BC2^g=U0S=LBu+AZ#ZOLG=q$Vne6A z^v|@nHqXf5Bz@N(@Fdsc8mwK90d8o!rXo4u?fFMO=>Oy#I(iIFuj#1u8%JQ^#b(NCl zE5jcAaqFu4kImy=J(qA((uJJ&_c}Y2iXLtaB3u&5?)Dd&+m4RE+y7|IS|e0-Lh}5N zj>z%;D{o4E-o8E%;w5rl+Zi|8?G<-u-REb5v?i1#_9i|yIl4ts7tDHqrojY6GK!@@ z9&pJ9@E{;7do)OPItYgSL+G5E4xyy+uL)XOA@Y>d@-09}BWmJJOGY9;({9!*W(19R zjzm$ss!9p91fv5f>#`%|K#h^2P`$mjO4a&&kM~5CJd>uO1G0Z+e?2L&&^|4gAcD_BCASwI+-w2JaVVn?9T{4Etctijhy|bQ%q=o^`ID1 zni+n?qTFLZ#2dZna;mS|F!Vr=(N!xf;^#kqb;Jg>~po6#C_ZPb16po~<=>1ij z9lzyz%Xtx@yVR+CRTjpc6k(BLXev9gm>pR?X#SP8b)v!Y>h?QRSNf~9Vo8VtoE$9@ z32mx#SaG@3LABaEU~KZ=vd$O9KgTP@(|e1<>K++%4USK@jXyj4@Q>Or64{q@ks8#= z3j@FPcSB9?dAAXHEB%o;uNhLRBU7kjebqBabIZI)!Prfn3{?vorjT=}j^q_DLN&4h zW7h9r*>q`mVX8j&?B|1?8mFCd)Y_+8eDsXzN5j-w6`=wKmJOo^k>Ta z`Xt4uYyAE(*B~py0vbQ<%mX{wh+T24NDVRHqPE6O3~9I=x=;OBY*(XoHPu7xDnL;c za8Nekpzx7?bxUo0nO=o;XqQh9B;*FZgbccD=_(Zs6{6W`VYU_4@AcsQZ(%wfaTYv0 znv}DjE|*5{C($VKz)VPQnWjY9<$j-ipDrJFKCmi5{Y-vXjCU^0XC_^Bs{)308D=Dl zTX8Yd@g$<4<=YwbK@-Gww-SV{y$&S!7Lc60SyNDP-eNet^b~;M@lr^% z+^A*HgNIgjFa1;EjA{uZd0nnzcnBr53U}KCuWHXQ#TskTlJ6LT7IxWhp_kYjbtq~n zJ#_(f!b=1FeYNIO&F-`i?Ft!<_OVUAOVnv%we=Xy^^Z!7RJXP(LzuRn)ZNhi_c4jv z*B@^HxYyxQ^6dbxGk1~)DtFf{|F}CTZ2RoZn#*`{u%e(~-;)#H3E_6S#&j0dmXygv z(WUjiyyzHtI5JTGW}{@PRuuABd!%jD=IWo@B1<{*Y{jIuR5TkvI?x_OBXXdL3zwK> zR%&ibX$m8e2%h~c5f0^|gn&S0j-hwTLOE=#lw)x*h|}-P#}kRV0FfdO0idfU?@;!y zFR0-alxc~x8k=ooNa+XRVR(0^lCj#c(OfS=sDk-~Z#r5xHQo!Z_KvZz&8HacFjMyT z#g{&!^q;Ogwi+;r8QDd+dzD%n>T~`UVyu|)XX?+);#kO!U}0~&&&YgnXZw*51EV{SsyZC@`Hx#n ze=kc@w-tmRPIVRU_|oji$C_M;Fpj8jwF)Iw${#K$Xvj5S$&Pl3XU8LLY}B+yq%|~q zq;XQ}eq99Hu_9mxK?CqCPib+=u@ZgK!YUMqJoX%O!XoVh1^IQ z7;pbo_i80@^-gv=p?bF}3KgPzBDcb$V%vWno!`*0_?U#4+)hgOJQ0n4Y;XET}mwbMGHX7$V=^OHo!u62L~zjJ1S^`JZ<6;xUr&|0wQea%aCVN zlL&|y(B%_toH4I_XRa1<*q%x;esz=A{dL(=XHiq}$)H8^PRg+gD#myw3?A2iyNtPY z_!w*0QC3oz`OnBX0yi_P7#=>c_|AOwt&)l`LwLpG1QVTR)Tm-Cs?*wg_z}Ccwur3+n)dJEkZVD)8^Nh%wl8LfX z2mi;`R1V%vS%l|shlGU73a~*vV^27M;>om4`d*Jl6wJh4lbI}1xp+5S1u18*^P}s@ zO`RvrSNBx^UX$nX_++5b;CSCk-K0CueYInuW|KdSnN=uyAZ7Xc@T4di9j=%ll6 z9AzZ8drN-Ch=ntyByZzyF@vy*#ele7V^4oMEk18PIGDA#wC11s+@>eAee4}W&$r6c z`O-Bt0+*U4sH3URPt6=V^Uf#X^o{z2qQUl8!h#a7KO`BPL09h&F)X2QmCLQl%P4qu zx&NkCH}j+w{>h+&m9VMJ@8_R~7AI$3dvR_IajPRR&=Yj=UV+$$e{|&0y!k{l$P3AY zajUJ4Y`voHzeJkr+W+j$&)tT-!a|`o+p&t$zgH6mWFfccJS6+Y2blocfO-ebge0P?$?|j2X5fw~H2=p*KYPodlck`5qwe$7d5|Olr`s))sF=$#Zj)^c}yYX1cHss%UW; zcy_HWgPSpP;^fdVYK-qZW^~Mh4L0*$K>YNio|K**RD%n#?~gN9?O8dweSY=M{0 zE{ZNK1d>9I$i(M#tIFQL&zd$~JiiYevwr68!h*NP$(2d_A^QcJHcD7qgK0qggId?D ziu498^_Yte_1oW-5I=7k>huV!92)9X-EQIdHVmtJ7 z`Y6T4jC9PF_1+#i;dQCT*I8I-+<#fARe|BxCn--j_FL^{4=vgy<78?uR!z{-0*dgJ zkcJ(b{Z0alOk?XDh$#2FECNBF zF33YdA|&jB5@sSx3&!_}x@dZPoENU?=KD3!%6^-j`%K6w=al-a>u0X4)ZL%LZzgxM zTj2;->B5ifa67c;expO_Y~Rb3xiY<9Q=aB}h9)YetA|##R)!?l_1N{Ib;EsJd*x>1 z#IRkg#Bd)S3uhsZ)3n?-fSS3NdwAcoNCtZ2prirkhYDp@2KL@I zC&$am?z|aRxeV;%j1i(HzhWx0Ix$4^u=#Dw#ntbuyJbsL^Y5?k@=J)cSzcJ*de*$T zEvPWExM8;MW8eGKi>}QClR)$Y{>h!p{osoBP2+YBS;DxF4Lq6yf@}XFOQB~_` zM;`^uVJ&|CQ!=yqr$~jT*H0Tn%%?gl?5tuDDFDFb0g@!g)AO%A$(-Kgu2Eo8+BsgT ze@3UaL^4>j&cEXx;P~v9(d^)mbF+KkC-XYVT_=Gf89*T(u|g;gjR%MYl=WB(bJ)JBM$@`+D3Xofs)SSBiBsR_*A|f zCFN7JO{z-Kyc>R?GiTcmZCq>wvgwIL%;5lbJHRox@Ny|9CccS4G+^O zo5r&evljEp-(|3|5GBqv=_ex5quneGB{h*B z{tS*h{Jl+%;uk$`g$w&qsvkR9AdX|H?``}Qv)=WOV%ga8OeE*$$C&Tu>9^*N{583% zoqq99_sM#TrdHf^8s)MbT-DA&ny<3TWgqjH&p!OvkXtv@cRQ*joV$JOm4w7%VQAKk zeF5kC()E5Zomr0F!R-+hgbavdEdzf!1yr5RLDA7w5GSbcg=`&;vV|%r(*A-+`r9-4 zSR7~p(PE|oqbkQ<+)t+R9_tL+P=)FOpq9@A&^#k383Xae<7JU4coLT>R752un<(n< z9d_P*a^?NywuOg=URv4HI~W+mcB$wu506OrPS8$>o69!-Hs%9fkVu|GIj|wg?iA}v zcNhhqgb+>3pT-IdW7U2!X7O#+s91Lx9`yd*}XK zi+xWPU-8RLShhL|!JXWSsD1F@Tx<>tV~UkI*SC7#;@6qq=en{QZf95J3B)tZ+9eO( zEw>^Wnxm2qrCPxvOrys4%Ya|_t+gFrRI75VPzffgf_JImf=m`M4PYEdyP4uFsiND9 zM>tN0q;IkH+f*r%ptoyMy0ZbWOWTU%O%>qduq2cOy_)&z1m|-W?rb%p9Yf2ui zWGQFmd*YjiSyQ}IL!rTmo&O{iRQ;3tfZtI6*C7GQW&P5b3`jV%X;%biv!vfRR`9;k zcIy39b>+mYZv4UV*Y)Qw^?2XfpT(V6*#MEN52T*wt)6wCb=NcDH>V`Us|`ywT^MG- z@8-pkTLQn%wf~BLvH@PtKAcO$O_i!2-T-3-pX*Qkavqm%$;8>(?8o~1bIvm+j&>!nyqVjvie4z8pOqH&P|c1Ex%3kTBtLhFHf{g^#K5Kpf6- z%c0WoAY4gj@w@N^a=X-Ab_IEQ=RLMM+^J4Jp0Ke7RaG7KcFVBeHyA}N- z`~GO}k6W0vDJT>9?-h&QxSg9w* z4#C1W&iph$kzUGpAup;HCtFZiu5`8@{b_6%$J`^R&YW(Hi#X~2MY)t;Im)40G0@aQei3X(AYlPD~R zib4sb>FQ-(&$w}o30E-oBn&ofVT2#P%!@P4apj%KM^Nkza5%Ia+wcnKew=8&d!iku zb#cHCE=Lpc{7f*-HV1}c646hmONddYC6>zA%tlj#E%OxyUDl7*1AKDtGrE>_PsLL| zV_y~AA+&n#Wbe$|ZI_#Ct$F?2-N{wt2&=P~#Kgfn6F3!aIm&Ivrmb;%nwNYmH-OW8 z&)w?RT6q+y#j}}=-ju#G2_|4`f_x4r!Nx*@Iv@u@Ir`JM6_a->lfyo)prnR{8uy#n zw;|NRU`8N_t&aH8T8I-X&22R*~X3>+(wY)mCjyR#IB#Q9Mk z>l}0*aKnY%fS&YHfyRajkdh(ipx3=kF>}#(%XD9ns4x75QgaRD5!sw%Xk%%l@1p$A zqRwY4qDQsZW7v__6-JKM`yBJN#D*X8n!k~nSJ(PJxJ!@Oky)9S#E`Z@T+)}JFA^2w zD-Sn-2Up|m=k}l82Gy@|k_Vl4UbfJOWGImQq_&+x=}wmd7Qmp;Jlsj6R(pRJCW5Mk z)p7Sw@~y(E1z$j7fg-Aft_O^r?U?@6!Yi!_2`T+_w;ZL#h}bak(3pv7l9Wjan-Ge4F`EkdFvY)5-c z{bQR4l1DmOGf16-p5ioFq#iBeNs9`Gvs>+z`Q&i#nTM8^dnYR^Yz$_<_r%3abeFmA zG18X#z4QEqK*du(-i$iz2plPE(|B|u!RPwDD+8bZx-k3iTwmemW~5e*j_0Tk^6}@G zf8Py^x_t9DuA^Ewr^}}$C6i^K01(YU8bxYnwE(H-2N-C;ZbA2gWFCz>% literal 0 HcmV?d00001 diff --git a/Toolkit/CKImages/browser.php b/Toolkit/CKImages/browser.php new file mode 100644 index 0000000..a66590c --- /dev/null +++ b/Toolkit/CKImages/browser.php @@ -0,0 +1,34 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: browser.php,v 1.4 2010/06/04 10:48:50 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * bootstrap + */ +require_once '../../setup.phtml'; + +Toolkit_CKImages_Factory::init(); +$connector = Toolkit_CKImages_Factory::instance('Connector'); +$connector->setDbh(Toolkit_Database::getInstance()); +$flexyOpts = $GLOBALS['flexyOptions']; +$flexyOpts['templateDir'] = BASE . 'Toolkit/CKImages/templates/'; +$flexyOpts['compileDir'] = BASE . 'Toolkit/CKImages/templates/compiled/'; +$tEngine = new HTML_Template_Flexy($flexyOpts); + +$connector->browseImages($tEngine); +?> diff --git a/Toolkit/CKImages/controller.php b/Toolkit/CKImages/controller.php new file mode 100644 index 0000000..e99537e --- /dev/null +++ b/Toolkit/CKImages/controller.php @@ -0,0 +1,53 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: controller.php,v 1.3 2010/06/04 11:32:36 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * bootstrap + */ +require_once '../../setup.phtml'; + +Toolkit_CKImages_Factory::init(); +$controller = Toolkit_CKImages_Factory::instance('Connector'); +$controller->setDbh(Toolkit_Database::getInstance()); + +switch ($_GET['command']) { +case 'CreateFolder' : + $controller->createFolder(); + break; + +case 'DeleteFile' : + $controller->deleteFile(new Toolkit_FileServer_ImageAdapter()); + break; + +case 'DeleteFolder' : + $controller->deleteFolder(); + break; + +case 'Upload' : + $controller->uploadFile(new Toolkit_FileServer_ImageAdapter()); + break; + +case 'UploadFile' : + $controller->quickUpload(new Toolkit_FileServer_ImageAdapter()); + break; + +default : + die('not yet implemented'); + $controller->throwError(); + break; +} +?> diff --git a/Toolkit/CKImages/imageFetch.php b/Toolkit/CKImages/imageFetch.php new file mode 100644 index 0000000..55951bc --- /dev/null +++ b/Toolkit/CKImages/imageFetch.php @@ -0,0 +1,44 @@ +prepare($sql); + $stmt->bindParam(':id', $_GET['file'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + +// $fileToFetch = empty($row['original_image']) +// ? $row['name_on_disk'] +// : $row['original_image']; + $fileToFetch = $row['name_on_disk']; +} catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); +} +set_time_limit(0); + +// file to save the info +$fp = fopen(dirname(__FILE__) . "/editedImages/$fileToFetch", 'w+'); + +// file we are downloading +$ch = curl_init(CKIMAGE_ORIGINAL . $fileToFetch); +curl_setopt($ch, CURLOPT_TIMEOUT, 50); +curl_setopt($ch, CURLOPT_FILE, $fp); +curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); +curl_exec($ch); +curl_close($ch); +fclose($fp); + +$path = urlencode(BASE . "Toolkit/CKImages/editedImages/$fileToFetch"); +$image_name = urlencode($row['file_name']); +header('Location: ' . BASE_URL . "Toolkit/PHPImageEditor/index.php?imagesrc=$path&image_name=$image_name"); +?> diff --git a/Toolkit/CKImages/libjs/image_selector.js b/Toolkit/CKImages/libjs/image_selector.js new file mode 100644 index 0000000..930bce2 --- /dev/null +++ b/Toolkit/CKImages/libjs/image_selector.js @@ -0,0 +1,142 @@ +var IMAGE_SELECTOR = +{ + parentFolder: null, + + init: function() + { + $('.tLeft').tipsy({gravity: 'sw'}); + $('.tCenter').tipsy({gravity: 's'}); + $('.tRight').tipsy({gravity: 'se'}); + $('.tDelete').tipsy({gravity: 'se'}); + + $('a.CKImageEdit').click(function(event) { + var $newWindow = window.open( + $(this).attr('href'), + '', + 'width=775,height=775', + true + ); + + $newWindow.focus(); + return false; + }); + + tree1 = new tree_component(); + tree1.init($("#folders"), { + cookies : { + prefix : "glm_image_browser", + opts : { path : '/' } + }, + ui : { + animation : 500 + } + }); + + // Make the tree default to all opened + $('#folders li.closed') + .toggleClass('open') + .toggleClass('closed'); + + $('#folders a').click(IMAGE_SELECTOR.viewFolder); + + // Stop clicks on the LI elements, so the folders branches + // will not close. + $('#folders li').click(function(event) { + event.stopImmediatePropagation(); + }); + + $('div.thumb span.CKImageUse').click(function() { + var img = $(this).parent().siblings('img'); + var funcNum = $('#CKEditorFuncNum').text(); + + window.opener.CKEDITOR.tools.callFunction(funcNum, img.attr('rel')); + window.close(); + }); + + $('div.thumb span.CKImageDelete').click(function(event) { + event.preventDefault(); + if (confirm('Are you sure you want to delete this image?')) { + var img = $(this).parent().siblings('img').attr('rel'); + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=DeleteFile&img=' + img); + + window.location.href = href; + } + }); + + $('#imageDialog').dialog({ + bgiframe : true, + autoOpen : false, + resizable: false, + modal : true, + buttons : { + Cancel : function() { + $(this).dialog('close'); + }, + 'Upload Selected File' : function() { + if ($('#imageDialog form input[type=file]').val()) { + $('.ui-dialog-buttonpane button').attr('disabled', true); + $('#imageDialog form').trigger('submit'); + } else { + alert('You need to select a file first'); + } + } + } + }); + + $('#upload').click(function() { + $('#imageDialog').dialog('open'); + }); + + $('#newFolder').submit(IMAGE_SELECTOR.createFolder); + $('#folderDialog').dialog({ + bgiframe : true, + autoOpen : false, + resizable: false, + modal : true, + buttons: { + Cancel : function() { + $('#folderName').removeClass('ui-state-error'); + $(this).dialog('close'); + }, + 'Create' : IMAGE_SELECTOR.createFolder + } + }); + $('#folderNew').click(function() { + $('#folderDialog').dialog('open'); + }); + $('#folderDelete').click(function() { + if (confirm('Are you sure you want to delete this folder?')) { + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=DeleteFolder'); + + window.location.href = href; + } + }); + }, + + createFolder: function(event) + { + event.preventDefault(); + // don't submit empty folder + var folderName = $('#folderName'); + var val = folderName.val(); + if (val == '') { + alert('You need to type a folder name first'); + return false; + } else { + $('.ui-dialog-buttonpane button').attr('disabled', true); + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=CreateFolder&name=' + $('#folderName').val()); + if (IMAGE_SELECTOR.parentFolder != null) { + href += '&parentFolder=' + IMAGE_SELECTOR.parentFolder; + IMAGE_SELECTOR.parentFolder = null; + } + window.location.href = href; + } + }, + + viewFolder: function(event) + { + location.href = $(this).attr('href'); + } +}; + +$(document).ready(IMAGE_SELECTOR.init); diff --git a/Toolkit/CKImages/styles.css b/Toolkit/CKImages/styles.css new file mode 100755 index 0000000..50260c8 --- /dev/null +++ b/Toolkit/CKImages/styles.css @@ -0,0 +1,153 @@ +body { + font-family: arial, sans-serif; + font-size: 11px; + background: url(assets/night-fate-stock2.jpg) no-repeat fixed;/* #E3E3C7; */ + margin: 0; + padding: 0; +} +#wrapper { + width: 750px; + height: 1%; + overflow: hidden; + margin: 10px 0px 5px 10px; +} +h1 { + font-size: 24px; + margin: 0; + padding: 10px; + background: rgba(255, 255, 255, 0.8); + position: fixed; + } + +#toolbar { + background: #F1F1E3; + width: 140px; + border: 1px solid #D5D59D; + float: left; + padding: 8px; + margin-right: 20px; + margin-top: 60px; + position: fixed; + } +#toolbar > ul { + border-bottom: 1px solid #333; + padding: 0 0 6px 0; + margin: 0 0 6px 0; + } +#toolbar > ul, #toolbar > ul li { + list-style: none; + display: block; +} +#toolbar > ul li { + padding: 2px 2px 2px 26px; + line-height: 18px; + border: 1px solid #F1F1E3; + margin: 0; + background-position: 2px center; + background-repeat: no-repeat; + text-decoration: underline; + cursor: hand; + cursor: pointer; +} +#toolbar > ul li:hover { + border: 1px solid #D5D59D; + text-decoration: none; +} +#toolbar #upload { + background-image: url(http://app.gaslightmedia.com/assets/icons/add.png); +} +#toolbar #folderNew { + background-image: url(http://app.gaslightmedia.com/assets/icons/folder_add.png); +} +#toolbar #folderDelete { + background-image: url(http://app.gaslightmedia.com/assets/icons/folder_delete.png); +} +.tree ul { + margin: 0; + padding-top: 1px; +} +.tree li a { + background-image: url(http://app.gaslightmedia.com/assets/icons/folder.png); +} +.tree li.open { + background: none; + } +#pred_1 { + padding-left: 3px; + padding-top: 3px; +} +.tree li li.open { + background: transparent url(http://app.gaslightmedia.com/libjs/jsTree/source/images/li.gif) no-repeat scroll 7px 7px; +} +/* Main Section */ +#photo-gallery { + height: 1%; + overflow: hidden; + padding-top: 10px; + margin: 50px 0 0 180px; + } +.thumb { + width: 120px; + height: 160px; + float: left; + margin: 0 20px 20px 0; + background: #F1F1E3; + background: rgba(241, 241, 227, 0.5); + font-size: 10px; + border-radius:5px; + -moz-border-radius:5px; + -webkit-border-radius:5px; + border: 1px solid #D5D59D; + } +.rowTop { + height: 1%; + overflow: hidden; +} +.thumb img { + display: block; + margin: 0px 10px 2px 10px; + border: 1px dotted #ccc; + clear: left; +} + +.CKImageFunctions { + margin: 10px 5px; + } +.CKImageFunctions a, +.CKImageFunctions span { + display: block; + line-height: 16px; + margin: 0 5px 0 5px; + text-decoration: underline; + width: 16px; + height: 16px; + text-indent: -9000px; + float: left; + } + +/* cursor */ +.CKImageUse, .CKImageEdit, .CKImageDelete { + cursor: hand; + cursor: pointer; + } + +.CKImageUse {background: url(http://app.gaslightmedia.com/assets/icons/accept.png) no-repeat; } +.CKImageEdit {background: url(http://app.gaslightmedia.com/assets/icons/image_edit.png) no-repeat; } +.CKImageView {background: url(http://app.gaslightmedia.com/assets/icons/image.png) no-repeat;} +.CKImageDelete {background: url(http://app.gaslightmedia.com/assets/icons/image_delete.png) no-repeat;} + +.CKImageName { + display: none; +} + + +.CKImageProperties { + margin: 3px auto; + text-align: center; +} +.CKImageDate { + display: none; +} +#menuFolder, #menuImage, #column { + display: none; +} \ No newline at end of file diff --git a/Toolkit/CKImages/templates/thumbnails.html b/Toolkit/CKImages/templates/thumbnails.html new file mode 100755 index 0000000..3c35b36 --- /dev/null +++ b/Toolkit/CKImages/templates/thumbnails.html @@ -0,0 +1,70 @@ + + + +Thumbnail Images + + + + + + + + +

    GLM Image Browser

    +
    +
    +
      +
    • Upload New Image
    • +
    +
      +
    • Create New Folder
    • +
    • Delete This Folder
    • +
    +
    + Folders + {folders:h} +
    +
    + +
    + + + + + + + + + + + + + + + + + + + + diff --git a/Toolkit/Common.php b/Toolkit/Common.php new file mode 100644 index 0000000..d3cec0c --- /dev/null +++ b/Toolkit/Common.php @@ -0,0 +1,1397 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @release CVS: $Id: Common.php,v 1.68 2010/08/15 19:31:47 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Common collection of functions used throughout the GLM Toolkit + * + * @category Toolkit + * @package Common + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Common +{ + // {{{ properties + + /** + * Who to send email to when a problem occurs on a live site + * + * This property doesn't matter for the development servers b/c the + * script will display the error encountered and terminate immediately. + * On the live site, a notification will be displayed to the user that + * an unexpected error has occured and will inform them to try again later. + * It will then send an email to the admin alerting them of the email. + * + * @var string + * @access protected + * @see Toolkit_Common::handleError() + */ + protected static $admin = ERROR_EMAIL_ADDRESS; + + /** + * Who to set the mail from when emailing errors + * + * @var string + * @access protected + * @see Toolkit_Common::handleError() + */ + protected static $from = 'Gaslight Media Toolkit '; + + // }}} + + // {{{ arrayFlatten() + + /** + * Recursively reduces multi-dimensional arrays to single-dimensional arrays + * + * @param array $array The array to flatten. + * @param int $preserveKeys How to handle array keys + * 0 = Never + * 1 = Strings + * 2 = Always + * @param array &$newArray The new created from the flattening + * + * @return array Single dimensional array. + * @access public + */ + public function arrayFlatten( + $array, + $preserveKeys = 1, + &$newArray = Array() + ) { + foreach ($array as $key => $child) { + if (is_array($child)) { + $newArray =& Toolkit_Common::arrayFlatten( + $child, + $preserveKeys, + $newArray + ); + } elseif ((int) $preserveKeys + (int) is_string($key) > 1) { + $newArray[$key] = $child; + } else { + $newArray[] = $child; + } + } + return $newArray; + } + + // }}} + + // {{{ cleanArray() + + /** + * removes values from an array where the key ends in '_rmv' + * + * @param array &$values array to clean + * + * @return array array w/ unneeded elements removed + * @access public + * @static + */ + public static function cleanArray(&$values) + { + // 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]); + } + } + + return $values; + } + + // }}} + // {{{ createEmailBody() + + /** + * Convert the form into an acceptable table to include in email + * + * This function can be called from any form class to generate + * a HTML table that we can use in an email. Elements can be dynamically + * rendered to meet your needs if you wish. + * + * If you wish to have any element(s) rendered differently than what the + * form already rendered them as, you need to define a public method + * named "emailRenderElement" in the calling class that will accept an + * elements name and you can create the rendering template in that class. + * + * Example: + * This example will turn groups like radio buttons or checkboxes + * from lists like: + * [ ] element_one [x] element_two [x] element_three + * ( ) element_one (x) element_two ( ) element_three + * into lists like: + * [ ] element_one ( ) element_one + * [x] element_two (x) element_two + * [x] element_three ( ) element_three + * + * public function &emailRenderElement($e) + * { + * switch ($e) { + * case 'element_one' : + * case 'element_two' : + * case 'element_three' : + * $renderer =& $this->defaultRenderer(); + * $renderer->clearAllTemplates(); + * $renderer->setGroupTemplate('{content}', $e); + * $renderer->setGroupElementTemplate('{element}
    ', $e); + * break; + * + * default : + * $renderer = null; + * break; + * } + * + * return $renderer; + * } + *
    + * + * @param array $newLabels Assoc array of element names and new + * labels to be used in the email form. + * eg [$newLabels['element'] => 'Label'] + * @param array $excludeList Any element that needs to be removed + * from the form when creating the table + * eg [$list = array(e1, e2, e3, etc..)] + * + * @return mixed The table body for the email. + */ + public function createEmailBody( + array $newLabels = array(), + array $excludeList = array() + ) { + $this->freeze(); + // Get the values corresponding to the elements present in the form. + $formData = $this->exportValues(); + // The array keys holds all the names of the elements. + $elements = array_keys($formData); + // Remove any unwanted elements from our elements array. + foreach ($excludeList as $trgt) { + unset($elements[array_search($trgt, $elements)]); + } + + // Which row we are at. + $i = 0; + $table = new HTML_Table(array('class' => 'data')); + // Auto grow the table, since the forms will by dynamic in size. + $table->setAutoGrow(true); + // Get the labels and values of the elements. + foreach ($elements as $name) { + $e =& $this->getElement($name); + // Get the default HTML for each element. + $html = $e->toHtml(); + // If any elements need to have their html + // changed for an email, this function in the + // class should exist and will return a renderer + // object of how the element should be rendered. + if (method_exists($this, 'emailRenderElement')) { + $renderer =& $this->emailRenderElement($name); + // make sure we have an actual rendering object + // if the element doesn't need to be altered it should + // just return null. + if (is_object($renderer)) { + $e->accept($renderer); + $html = $renderer->toHtml($name); + // We have to reset the entire forms html + // otherwise we'll just keep adding to it everytime + // we render a new element. + // This is a bit of a hack to make this work (because + // the _html element is supposed to be a private + // property) + $renderer->_html = null; + } + } + // Get the label for the element. + $label = array_key_exists($name, $newLabels) ? + $newLabels[$name] : + $e->getLabel(); + + // Make the row and increment the row counter. + $table->setCellContents($i, 0, $label); + $table->setCellAttributes($i, 0, array('class' => 'label')); + $table->setCellAttributes($i, 1, array('class' => 'field')); + $table->setCellContents($i++, 1, $html); + } + return $table->toHtml();; + } + + // }}} + // {{{ createSQLInsert() + + /** + * Generates a properly formatted sql query to insert data into a table + * + * @param string $table Name of the table to insert into + * @param array $columns Array of column names you want to set in the + * insert statement and bind names + * + * + * Toolkit_Common::createSQLInsert('member', array('name', 'pos')); + * will create the sql statement + * INSERT INTO member (name, pos) VALUES(:name, :pos) + * + * + * @return string Formatted SQL string + * @access public + * @static + */ + public static function createSQLInsert($table, array $columns) + { + $params = implode(', ', $columns); + $bindParams = ':' . implode(', :', $columns); + + return "INSERT INTO $table ($params) VALUES ($bindParams)"; + } + + // }}} + // {{{ createSQLUpdate() + + /** + * Generates a properly formatted sql query to update data in a table + * + * + * Toolkit_Common::createSQLUpdate('member', + * array('name', 'pos'), + * array('id = :id'); + * will create the sql statement + * UPDATE member SET name = :name, pos = :pos WHERE id = :id + * + * + * @param string $table Name of the table to update + * @param array $columns Array of columns names you want to update + * @param array $constraints Constraints to apply to the table to prevent + * running the update on every row in the db + * + * @return string formatted query string + * @access public + * @static + */ + public static function createSQLUpdate( + $table, + array $columns, + array $constraints = null + ) { + $length = count($columns); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$columns[$i]} = :{$columns[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + $sql = "UPDATE $table SET $bindParams"; + + if (!empty($constraints)) { + $sql .= ' WHERE ' . implode(' AND ', $constraints); + } + + return $sql; + } + + // }}} + // {{{ createTables() + + /** + * Read file from parameter and use the PDO parameter to create process file + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $file full path of file to parse + * + * @return void + * @access public + * @static + */ + public static function createTables(PDO $pdo, $file) + { + $sql = file_get_contents($file); + // break multiple queries apart by ';' + $tok = strtok($sql, ';'); + try { + // while we have valid tokens, execute the query + // and grab the next token + while ($tok !== false) { + $pdo->query($tok); + $tok = strtok(';'); + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ dieGracefully() + + /** + * Gracefully exit from the script when an unrecoverable error is created + * + * @param string $msg Message to display to user + * @param mixed $e Error object + * @param boolean $moreInfo More debugging info when in development + * + * @return void + * @access public + */ + public function dieGracefully($msg = null, $e = null, $moreInfo = false) + { + if (is_null($e)) { + if (is_null($msg)) { + die('There was an error, please try again later!'); + } else { + die($msg); + } + } else { + echo $msg . '
    '; + echo 'Error Caught.
    '; + echo 'Error: ' . $e->getMessage() . '
    '; + if ($moreInfo) { + echo 'Code:
    ' . $e->getCode() . '

    '; + echo 'Debug Info:
    ' . $e->getDebugInfo() . '

    '; + } + } + } + + // }}} + + // {{{ errorException() + + /** + * Stops script on Exception error + * + * Stops the script when an Exception is raised inside a + * try/catch block. + * + * When a site is no longer in DEVELOPMENT, ie: its live on ws3. + * We don't show any error info, but let the user know an unexpected + * error has occured and then mail the error info the the admin. + * + * Example usage: + * + * try { + if ($foo != $bar) { + throw new Exception ("Foo Doesn't equal Bar"); + } + * } catch (Exception $e) { + * return Toolkit_Common::handleError($e); + * } + * + * + * @param Exception $e Exception Object + * @param Mail $mail What to use to send mail to admin + * + * @return false + * @access public + * @static + */ + public static function errorException(Exception $e, Mail $mail = null) + { + if (!is_null($mail)) { + $subject = 'Exception Error for ' . SITENAME; + self::mailError($mail, $subject, $e); + } else { + echo self::getErrorInfo($e); + } + + return false; + } + + // }}} + // {{{ errorHTMLQuickFormError() + + /** + * Handles PEAR Errors for our developers + * + * When a site is no longer in DEVELOPMENT, ie: its live on ws3. + * We don't show any error info, but let the user know an unexpected + * error has occured and then mail the error info the the admin. + * + * HTML_QuickForm Example usage: + * + * $e =& $this->getElement('elementName'); + * if (PEAR::isError($e)) { + * return Toolkit_Common::handleError($e); + * } + * + * + * @param HTML_QuickForm_Error $e QuickFormError Object + * @param Mail $mail What to use to send mail to admin + * + * @return false + * @access public + * @since Method available since Release 1.0.1 + * @static + */ + public static function errorHTMLQuickFormError( + HTML_QuickForm_Error $e, + Mail $mail = null + ) { + if (!is_null($mail)) { + $subject = 'PEAR Error for ' . SITENAME; + self::mailError($mail, $subject); + } else { + echo self::getErrorInfo($e); + } + + return false; + } + + // }}} + // {{{ errorPDOException() + + /** + * Stops script on database error + * + * Stops the script when a PDOException is raised inside a + * try/catch block. + * + * When a site is no longer in DEVELOPMENT, ie: its live on ws3. + * We don't show any error info, but let the user know an unexpected + * error has occured and then mail the error info the the admin. + * + * Example usage: + * + * try { + * $sql = " + * SELECT * + * FROM table_name + * 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); + * } + * + * + * @param PDOException $e PDO Error Object. + * @param Mail $mail Mail object used to send admin email + * + * @return false + * @access public + * @since Method available since Release 1.0.1 + */ + public function errorPDOException(PDOException $e, Mail $mail = null) + { + if (!is_null($mail)) { + $subject = 'SQL Error for ' . SITENAME; + self::mailError($mail, $subject, $e); + } else { + echo self::getErrorInfo($e); + } + + return false; + } + + // }}} + // {{{ errorPEARError() + + /** + * Handles PEAR Errors for our developers + * + * When a site is no longer in DEVELOPMENT, ie: its live on ws3. + * We don't show any error info, but let the user know an unexpected + * error has occured and then mail the error info the the admin. + * + * @param PEAR_Error $e PEARError Object + * @param Mail $mail Mail object used to send admin email + * + * @return false + * @access public + * @since Method available since Release 1.0.1 + */ + public function errorPEARError(PEAR_Error $e, Mail $mail = null) + { + if (!is_null($mail)) { + $subject = 'PEAR Error for ' . SITENAME; + self::mailError($mail, $subject); + } else { + echo self::getErrorInfo($e); + } + + return false; + } + + // }}} + // {{{ errorPEARException() + + /** + * Handles PEAR Exception for our developers + * + * When a site is no longer in DEVELOPMENT, ie: its live on ws3. + * We don't show any error info, but let the user know an unexpected + * error has occured and then mail the error info the the admin. + * + * @param PEAR_Exception $e PEARException Object + * @param Mail $mail Mail object used to send admin email + * + * @return false + * @access public + * @since Method available since Release 1.0.1 + */ + public function errorPEARException(PEAR_Exception $e, Mail $mail = null) + { + if (!is_null($mail)) { + $subject = 'SQL Error for ' . SITENAME; + self::mailError($mail, $subject, $e); + } else { + echo self::getErrorInfo($e); + } + + return false; + } + + // }}} + // {{{ errorRuntimeException() + + /** + * Stops script on runtime error + * + * Stops the script when a runtimeException is raised inside a + * try/catch block. + * + * When a site is no longer in DEVELOPMENT, ie: its live on ws3. + * We don't show any error info, but let the user know an unexpected + * error has occured and then mail the error info the the admin. + * + * @param RuntimeException $e PDO Error Object. + * @param Mail $mail Mail object used to send admin email + * + * @return false + * @access public + * @since Method available since Release 1.0.2 + */ + public function errorRuntimeException( + RuntimeException $e, + Mail $mail = null + ) { + if (!is_null($mail)) { + $subject = 'Runtime Exception for ' . SITENAME; + self::mailError($mail, $subject, $e); + } else { + echo self::getErrorInfo($e); + } + + return false; + } + + // }}} + // {{{ errorBadMethodCallException() + + /** + * Stops script on bad method call error + * + * Stops the script when a badMethodCallException is raised inside a + * try/catch block. + * + * When a site is no longer in DEVELOPMENT, ie: its live on ws3. + * We don't show any error info, but let the user know an unexpected + * error has occured and then mail the error info the the admin. + * + * @param BadMethodCallException $e PDO Error Object. + * @param Mail $mail Mail object used to send admin email + * + * @return false + * @access public + * @since Method available since Release 1.0.3 + */ + public function errorBadMethodCallException( + BadMethodCallException $e, + Mail $mail = null + ) { + if (!is_null($mail)) { + $subject = 'Bad Method Call Exception for ' . SITENAME; + self::mailError($mail, $subject, $e); + } else { + echo self::getErrorInfo($e); + } + + return false; + } + + // }}} + + // {{{ filterURI() + + /** + * Filters uri's before they are validated + * + * @param string $uri URI to filter + * + * @return mixed new uri if missing scheme + * @access public + * @static + */ + public static function filterURI($uri) + { + $validProtocol = '/^https?\:\/\/.*/'; + $invalidProtocol = '/^.*?\:\/\/.*/'; + if (empty($uri)) { + // Empty field, just return + return $uri; + } elseif (preg_match($validProtocol, $uri)) { + // has valid protocol, return unchanged + // should pass validation. + return $uri; + } elseif (!preg_match($invalidProtocol, $uri)) { + // missing protocol, prepend default + // http:// protocol and return. + return "http://$uri"; + } else { + // has invalid protocol, return unchanged + // validation should catch this and throw error. + return $uri; + } + } + + // }}} + // {{{ filterPhone() + + /** + * Filters phone numbers before they are validated + * + * @param string $phone number to filter + * + * @return mixed newly formatted phone number + * @access public + * @static + */ + public static function filterPhone($phone) + { + // Ditch anything that is not a number + $number = preg_replace('/[^0-9]/', '', $phone); + + // Invalid Number, validation will catch error + $len = strlen($number); + if (($len < 10) || ($len > 11)) { + return $phone; + } + + // subscriber number + $sn = substr($number, -4); + // city code + $cc = substr($number, -7, 3); + // area code + $ac = substr($number, -10, 3); + if ($len == 11) { + // country prefix + $cp = $number[0]; + } + + $filteredNumber = "($ac) $cc-$sn"; + if (!is_null($cp)) { + $filteredNumber = "$cp $filteredNumber"; + } + + return $filteredNumber; + } + + // }}} + + // {{{ getCities() + + /** + * Get an array of cities from the database + * + * @param PDO $dbh Database handler + * @param integer $state State id the city is in + * @param integer $county County id the city is in + * @param integer $region Region id the city is in + * + * @return array states + * @access public + * @static + */ + public static function getCities( + PDO $dbh, + $state = null, + $county = null, + $region = null + ) { + $param = array(); + if (ctype_digit((string)$state)) { + $param[] = 'state_id = ' . $dbh->quote($state); + } + if (ctype_digit((string)$county)) { + $param[] = 'county_id = ' . $dbh->quote($county); + } + if (ctype_digit((string)$region)) { + $param[] = 'region_id = ' . $dbh->quote($region); + } + + try { + $sql = " + SELECT * + FROM city"; + + if (!empty($param)) { + $sql .= ' WHERE ' . implode(' AND ', $param); + } + $sql .= ' ORDER BY city_name'; + + $stmt = $dbh->prepare($sql); + $stmt->execute(); + + $cities = array(); + while ($row = $stmt->fetch()) { + $cities[$row['city_id']] = $row['city_name']; + } + + return $cities; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getErrorInfo() + + /** + * extract error info from error object + * + * @param mixed $obj Error object to get info for + * + * @return string formatted error information + * @access public + */ + public function getErrorInfo($obj) + { + $state = '' . get_class($obj) . ' error: '; + + $state .= '
    $_SERVER[\'QUERY_STRING\']: ' . $_SERVER['QUERY_STRING'] + . "\n"; + $state .= '
    $_SERVER[\'HTTP_REFERER\']: ' . $_SERVER['HTTP_REFERER'] + . "\n"; + $state .= '
    $_SERVER[\'REDIRECT_QUERY_STRING\']: ' + . $_SERVER['REDIRECT_QUERY_STRING'] . "\n"; + $state .= '
    $_SERVER[\'REQUEST_URI\']: ' . $_SERVER['REQUEST_URI'] + . "\n"; + + $state .= '
    $_GET:
    ' . print_r($_GET, true) . '
    '; + $state .= '
    $_POST:
    ' . print_r($_POST, true) . '
    '; + $state .= '
    $_SESSION:
    ' . print_r($_SESSION, true) . '
    '; + + if (method_exists($obj, 'getMessage')) { + $state .= $obj->getMessage(); + if (method_exists($obj, 'getDebugInfo')) { + $state .= '; ' . $obj->getDebugInfo(); + } + } + if (method_exists($obj, 'getFile')) { + $state .= ' in ' . $obj->getFile() . ''; + } + if (method_exists($obj, 'getLine')) { + $state .= ' on line ' . $obj->getLine() . ''; + } + if (method_exists($obj, 'getBacktrace')) { + $backtrace = print_r($obj->getBacktrace(), true); + + $state .= "
    $backtrace
    "; + } + + return $state; + } + + // }}} + // {{{ getHierarchicalTreeStructure() + + /** + * Create a hierarchical tree stored in an linear array + * + * Produces a representation of a hierarchical tree structure into a + * linear array so you can iterate straight through to get the tree + * structure. + * + * @param PDO $pdo Database handler + * @param string $table Name of the source relation + * @param string $key Name of the key field + * @param string $parent Name of the parent-key field + * @param string $order Name of the field to order siblings by + * @param integer $start Key value of the row to start at + * @param integer $maxDepth Maximum depth to descend to, or zero + * for unlimited depth + * @param boolean $validParent exclude branches that have null + * parent values + * + * @return array Linear array of tree structure + * @access public + * @see http://www.postgresql.org/doc/8.3/interactive/tablefunc.html#AEN104085 + */ + public function getHierarchicalTreeStructure( + PDO $pdo, + $table = 'pages', + $key = 'id', + $parent = 'parent', + $order = 'pos', + $start = 0, + $maxDepth = 0, + $validParent = true + ) { + try { + $tree = array(); + + $sql = " + SELECT * + FROM connectby('{$table}', '{$key}', '{$parent}', + '{$order}', '{$start}', {$maxDepth}) + as t(id text, parent text, level int, pos int)"; + if ($validParent) { + $sql .= " WHERE parent is not null"; + } + foreach ($pdo->query($sql) as $row) { + $tree[$row['id']] = $row['level']; + } + + return $tree; + } catch (PDOException $e) { + return self::handleError($e); + } + } + + // }}} + // {{{ getScripts() + + /** + * Gets all scripts for the page + * + * adds version number to url for all local (non-app.glm) urls + * so we can use .htaccess cachebusting + * + * combines script by server id, so we can decrease http requests to fetch + * the needed scripts + * + * @param array $scripts The array of js scripts for the page + * + * @return string HTML markup for scripts + * @access public + * @static + */ + public static function getScripts(array $scripts) + { + if (!is_array($scripts) || empty($scripts)) { + return false; + } + + $uniqueScripts = array_unique($scripts); + // Get the main jquery file + $jquery = JQUERY_CDN_JS; + $key = array_search($jquery, $uniqueScripts); + // If it exists, remove it from its current location + // and put at front of array. + if ($key !== false) { + unset($uniqueScripts[$key]); + array_unshift($uniqueScripts, $jquery); + } + $format = ''; + + $ret = ''; + $baseUrlStrLen = strlen(BASE_URL); + $appUrlStrLen = strlen(GLM_APP_BASE_URL); + + // Use versioning with local scripts for cachebusting + $localPath = BASE_URL . 'v/' . VERSION . '/javascript/'; + $appPath = GLM_APP_BASE_URL . 'javascript/'; + + $localScripts = array(); + $appScripts = array(); + foreach ($uniqueScripts as $origScript) { + //if ($_ENV['GLM_HOST_ID'] == "PRODUCTION") { + // if (@substr_compare($origScript, BASE_URL, 0, $baseUrlStrLen) === 0) { + // local site scripts + // if (substr($origScript, '-3') == '.js') { + // $localScripts[] = substr($origScript, strlen(BASE_URL)); + // } else { + // scripts written in other language than JS (ie: php) + // $ret .= sprintf($format, $origScript); + // } + // } elseif (@substr_compare($origScript, GLM_APP_BASE_URL, 0, $appUrlStrLen) === 0) { + // app.glm scripts + // $pieces = explode('/', $origScript); + // switch (end($pieces)) { + // case 'ckeditor.js' : + // case 'jquery.tree.js' : + // $ret .= sprintf($format, $origScript) . "\n"; + // break; + + // default : + // $appScripts[] = substr($origScript, strlen(GLM_APP_BASE_URL)); + // break; + // } + // } else { + // // other server scripts ie: (google.com) + // $ret .= sprintf($format, $origScript) . "\n"; + // } + //} else { + $ret .= sprintf($format, $origScript) . "\n"; + //} + } + + if (!empty($appScripts)) { + $appPath = $appPath . implode(',', $appScripts); + $ret .= sprintf($format, $appPath) . "\n"; + } + + if (!empty($localScripts)) { + $localPath = $localPath . implode(',', $localScripts); + $ret .= sprintf($format, $localPath) . "\n"; + } + + return $ret; + } + + // }}} + // {{{ getStates() + + + /** + * Get an array of states from the database + * + * @param PDO $dbh Database handler + * @param boolean $unionStatesOnly If we want to only retrieve + * the 50 US states + * + * @return array states + * @access public + * @static + */ + public static function getStates(PDO $dbh, $unionStatesOnly = false) + { + if ($unionStatesOnly) { + // Just grab the 50 states of the union + $where = "WHERE us_state = :bool"; + } + + try { + $sql = " + SELECT * + FROM state + $where + ORDER BY state_name"; + + $stmt = $dbh->prepare($sql); + if ($unionStatesOnly) { + $stmt->bindValue(':bool', 1, PDO::PARAM_BOOL); + } + $stmt->execute(); + + $states = array(); + while ($row = $stmt->fetch()) { + $states[$row['state_id']] = $row['state_name']; + } + + return $states; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getStyleSheets() + + /** + * Gets all style sheets for the page + * + * adds version number to url for all local (non-app.glm) urls + * so we can use .htaccess cachebusting + * + * combines style sheets by server id, so we can decrease http + * requests to fetch the needed style sheets + * + * @return string HTML markup for stylesheets + * @access public + * @static + */ + public static function getStyleSheets() + { + if ( !isset($GLOBALS['styleSheets']) + || !is_array($GLOBALS['styleSheets']) + || empty($GLOBALS['styleSheets']) + ) { + return false; + } + + $uniqueStyleSheets = array_unique($GLOBALS['styleSheets']); + $format = ''; + + $baseUrlStrLen = strlen(BASE_URL); + $appUrlStrLen = strlen(GLM_APP_BASE_URL); + $ret = ''; + + $localPath = BASE_URL . 'v/' . VERSION . '/css/'; + $appPath = GLM_APP_BASE_URL . 'css/'; + + $localStyleSheets = array(); + $appStyleSheets = array(); + foreach ($uniqueStyleSheets as $origStyleSheet) { + //if ($_ENV['GLM_HOST_ID'] == "PRODUCTION") { + // if (strstr($origStyleSheet, '/themes/')) { + // $ret .= sprintf($format, $origStyleSheet) . "\n"; + // } elseif (@substr_compare($origStyleSheet, BASE_URL, 0, $baseUrlStrLen) === 0) { + // // local site style sheets + // $localStyleSheets[] = substr($origStyleSheet, strlen(BASE_URL)); + // } elseif (@substr_compare($origStyleSheet, GLM_APP_BASE_URL, 0, $appUrlStrLen) === 0) { + // // app.glm style sheets + // $appStyleSheets[] = substr($origStyleSheet, strlen(GLM_APP_BASE_URL)); + // } else { + // // other server style sheets ie: (google.com) + // $ret .= sprintf($format, $origStyleSheet) . "\n"; + // } + //} else { + $ret .= sprintf($format, $origStyleSheet) . "\n"; + //} + } + + if (!empty($appStyleSheets)) { + $appPath = $appPath . implode(',', $appStyleSheets); + $ret .= sprintf($format, $appPath) . "\n"; + } + if (!empty($localStyleSheets)) { + $localPath = $localPath . implode(',', $localStyleSheets); + $ret .= sprintf($format, $localPath) . "\n"; + } + + return $ret; + } + + // }}} + // {{{ getTableMetaData() + + /** + * Gets the meta data of the calling classes table columns + * + * The table used when retrieving the meta data is defined + * in the class property $tableName. The class or parent class + * must also have a $tableMetaData property + * + * @param PDO $pdo Database Handler + * @param string $tableName The name of the table to get the meta data for. + * @param array $clauses Only retrieve meta data for certain column types + * + * @return array metadata for table + * @access protected + */ + public function getTableMetaData( + PDO $pdo, + $tableName, + array $clauses = null + ) { + if (is_array($clauses)) { + while ($c = current($clauses)) { + $ands .= " data_type = '{$c}'"; + if (false !== next($clauses)) { + $ands .= " OR "; + } + } + $ands = " AND ($ands)"; + } + try { + $sql = " + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = :tname + $ands"; + $stmt = $pdo->prepare($sql); + $stmt->bindParam(':tname', $tableName, PDO::PARAM_STR); + + $stmt->execute(); + + $metaData = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $metaData[$row['column_name']] = $row['data_type']; + } + + return $metaData; + } catch (PDOException $e) { + return self::handleError($e); + } + } + + // }}} + + // {{{ handleError() + + /** + * Handles various script error + * + * @param Object $e Error Object + * @param boolean $developmentServer If we are on a development server + * + * @return mixed String, false, void + * @access public + * @static + */ + public static function handleError($e, $developmentServer = DEVELOPMENT) + { + $errorType = str_replace('_', '', get_class($e)); + $errorType = "error$errorType"; + + if (method_exists(__CLASS__, $errorType)) { + if (!$developmentServer) { + // Tell the user we encountered an Error. + if (file_exists(BASE . '404.html')) { + include_once BASE . "404.html"; + } + + $mail = Mail::factory('mail'); + self::$errorType($e, $mail); + exit(); + } else { + return self::$errorType($e, $mail); + } + } else { + echo '

    The system has encountered an un-recoverable error!

    '; + } + } + + // }}} + + // {{{ mailError() + + /** + * Mails the error to the site admin + * + * @param Mail $mail Mail object to use + * @param string $subject Subject of email + * @param Exception $e exception + * + * @return void + * @access public + * @static + */ + public static function mailError( + Mail $mail, + $subject, + Exception $e = null + ) { + $msg = '

    ' . self::getErrorInfo($e) . '

    '; + + $htmlMsg = "$msg"; + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom(self::$from); + $mimeMail->setSubject($subject); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $body = $mimeMail->get(); + $headers = $mimeMail->headers(); + + $mail->send(self::$admin, $headers, $body); + } + + // }}} + // {{{ multiDimArrayLocate() + + /** + * Locates an array value in a multi-dimensional array + * + * @param array $array The Array which holds the value you need. + * @param mixed $text The value that you are looking for. + * + * @return mixed The search result. + */ + public function multiDimArrayLocate($array, $text) + { + if (!is_array($array)) { + return; + } + $arrayResult = array(); + foreach ($array as $k => $v) { + if (is_array($v)) { + $temp[$k] = self::multiDimArrayLocate($v, $text); + if ($temp[$k]) { + $arrayResult[$k] = $temp[$k]; + } + } else { + if ($v == $text) { + $arrayResult[$k] = $v; + } + } + } + return $arrayResult; + } + + // }}} + + // {{{ processQuery() + //The type hint of the argument is incorrect for the type + //definition of the @param tag with argument $dbh in processQuery() + /** + * Performs the sql insert statement + * + * If using a Postgresql driver for the PDO, metadata is used when + * binding parameters to the prepared statement. + * + * @param PDO $dbh Database handler object + * @param string $tableName table used in query + * @param string $sql sql query string + * @param array $values associative array of key/value pairs that will + * be used to bind to the sql query string + * + * @return boolean result of the execute statement on the database + * @access public + * @static + */ + public static function processQuery( + PDO $dbh, + $tableName, + $sql, + array $values = null + ) { + $dbType = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); + if ($dbType == 'pgsql') { + $md = Toolkit_Common::getTableMetaData($dbh, $tableName); + } + $stmt = $dbh->prepare($sql); + foreach ($values as $k => &$v) { + if ($dbType == 'pgsql') { + $metaData = $md[$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. + // as empty values '', are not considered unique + if ( empty($v) + && $dataType !== PDO::PARAM_BOOL + && $dataType !== PDO::PARAM_INT + ) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } else { + $stmt->bindParam(":$k", $v); + } + } + + return $stmt->execute(); + } + + // }}} + // {{{ prepareQuery() + + /** + * Prepares the sql statement + * + * If using a Postgresql driver for the PDO, metadata is used when + * binding parameters to the prepared statement. + * + * @param PDO &$dbh Database handler object + * @param string $tableName table used in query + * @param string $sql sql query string + * @param array $values associative array of key/value pairs that will + * be used to bind to the sql query string + * + * @return PDOStatement if successfully prepares statement + * @access public + * @static + */ + public static function prepareQuery( + PDO &$dbh, + $tableName, + $sql, + array $values = null + ) { + $dbType = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); + if ($dbType == 'pgsql') { + $md = Toolkit_Common::getTableMetaData($dbh, $tableName); + } + $stmt = $dbh->prepare($sql); + foreach ($values as $k => &$v) { + if ($dbType == 'pgsql') { + $metaData = $md[$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. + // as empty values '', are not considered unique + if ( empty($v) + && $dataType !== PDO::PARAM_BOOL + && $dataType !== PDO::PARAM_INT + ) { + $v = null; + $dataType = PDO::PARAM_NULL; + } elseif ($v === '' && $dataType === PDO::PARAM_INT) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + + $stmt->bindParam(":$k", $v, $dataType); + } else { + $stmt->bindParam(":$k", $v); + } + } + + return $stmt; + } + + // }}} + + // {{{ recursiveArraySearch() + + /** + * Recursive multi-dimensional array search + * + * @param string $n Needle + * @param array $h Haystack + * + * @return mixed search result - false if not found + * @access public + * @static + */ + public static function recursiveArraySearch($n, array $h) + { + foreach ($h as $i => $j) { + $curr = $i; + if ( $n === $j + || (is_array($j) && self::recursiveArraySearch($n, $j) !== false) + ) { + return $curr; + } + } + + return false; + } + + // }}} + + // {{{ show() + + /** + * Renders the calling class to the screen + * + * @access public + * @return string calls the toHTML function of calling class + */ + public function show() + { + echo $this->toHTML(); + } + + // }}} +} diff --git a/Toolkit/Contacts/Admin/EditContact.php b/Toolkit/Contacts/Admin/EditContact.php new file mode 100644 index 0000000..9a1ea20 --- /dev/null +++ b/Toolkit/Contacts/Admin/EditContact.php @@ -0,0 +1,1040 @@ + + * @copyright 2010 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: EditContact.php,v 1.3 2010/05/13 20:18:38 matrix Exp $ + * @link http://pear.php.net/package/Contacts + * @see References to other sections (if any)... + */ +/** + * Error codes for Toolkit_Contacts_ContactUs + * + * Codes are mapped to textual messaged by errorMessage() method, + * if you add a new code be sure to add a new message for it to errorMessage() + * + * @see Toolkit_Contacts_ContactUs::errorMessage() + */ +define('FORM_OK', 1); + +/** + * Description for define + */ +define('FORM_ERROR', -1); + +/** + * Description for define + */ +define('NO_RECORD', -2); + +/** + * Description for define + */ +define('INVALID_DB', -3); + +/** + * Description for define + */ +define('MISSING_CONSTANT', -4); + +/** + * Description for define + */ +define('MISSING_CONTACT_TYPE', -5); + +/** + * Toolkit_Contacts_Admin_EditContact + * + * Edit Process class to insert or update a contact + * can be used with customer table with little modification + * + * @category Toolkit + * @package Contacts + * @author Steve Sutton + * @copyright 2010 Steve Sutton + * @license Gaslight Media + * @version Release: @package_version@ + * @link http://pear.php.net/package/Contacts + * @see References to other sections (if any)... + */ +class Toolkit_Contacts_Admin_EditContact + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * Table in Database which holds the contact data + * + * @var string + * @access public + */ + public $tableName = 'contact'; + + /** + * Primary Key for the table + * + * @var string + * @access public + */ + public $primaryKey = 'id'; + + /** + * Sequence for the table + * + * @var string + * @access public + */ + public $sequence = 'contact_id_seq'; + + /** + * 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 = array(); + + /** + * The interests from the contact db + * + * @var array + * @access protected + */ + protected $inquiries = array(); + + /** + * What do you want the error msg to be if the form doesn't validate + * + * @var string + * @access protected + */ + protected $errorMsg + = '
    + Warning: The form was not sent, please review the errors below. +
    '; + + /** + * What do you want the success msg to be if the form validates successfully + * + * @var string + * @access protected + */ + protected $successMsg + = '
    + The information below has been successfully submitted. +
    '; + + /** + * Include a captcha on the form or not + * + * @var boolean + * @access protected + */ + protected $useCaptcha = false; + + /** + * The default templates to inject into the form renderer + * + * @var string + * @access protected + */ + protected $template; + + /** + * 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. + * + * These rules can be removed in subclasses before the rules are configured + * if you want to omit any of them from validating input - just remember + * to not call them in your configured rules! + * + * Phone: validates input against US and CA style phone #'s + * + * $rules[] = array('element' => 'phone', + * 'message' => 'ERROR: Invalid Phone Format!', + * 'type' => 'phone', + * 'format' => null, + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * Zip: Validates input against US and CA zip codes, if DB check is + * set to true, validate zip codes against all the zip codes in the + * DB. + * + * $rules[] = array('element' => 'zip', + * 'message' => 'ERROR: Invalid Zip!', + * 'type' => 'zip', + * 'format' => array('requireDBCheck' => true), + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * Banwords: Make sure each each doesn't contain a banned word. Checking + * against a DB of banned words. + * + * State: Validate input against US and CA region / province codes. If DB + * check is set to true, validate region / province against all the + * regions / provinces in the DB. + * + * $rules[] = array('element' => 'state_id', + * 'message' => 'ERROR: Invalid State / Province!', + * 'type' => 'state', + * 'format' => array('requireDBCheck' => true), + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * @var array + * @access protected + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Zip.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Phone.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Banwords.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/State.php + */ + protected $registeredRules = array('phone', 'zip', 'state'); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param object $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
    tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @author Jamie Kahgee + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see 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->dbh = $pdo; + + /** + * Where are the flexy templates stored at for this class. + */ + define('TEMPLATES_DIR', BASE . 'Toolkit/Contacts/templates'); + + /** + * Where are the compiled flexy templates stored at for this class. + */ + define('COMPILED_DIR', BASE . 'Toolkit/Contacts/templates/compiled'); + $oldUmask = umask(0); + if (!is_dir(TEMPLATES_DIR)) { + mkdir(TEMPLATES_DIR, 0770, true); + } + if (!is_dir(COMPILED_DIR)) { + mkdir(COMPILED_DIR, 0770, true); + } + umask($oldUmask); + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = TEMPLATES_DIR; + $this->flexyOptions['compileDir'] = COMPILED_DIR; + + } + + // }}} + + // {{{ checkContactEmail() + + /** + * 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 checkContactEmail($data) + { + try { + // If we're editing a contact, they + // can save that member as its + // own name. so don't include that + // member in the check. + if (ctype_digit($_REQUEST[$this->primaryKey])) { + $and = "AND {$this->primaryKey} <> :id"; + } + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE email = :email + $and"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $data, PDO::PARAM_STR); + if (ctype_digit($_REQUEST[$this->primaryKey])) { + $stmt->bindParam(':id', $_REQUEST[$this->primaryKey], PDO::PARAM_STR); + } + $stmt->execute(); + $stmt->bindColumn('total', $valid); + $stmt->fetch(); + + return !(bool) $valid; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureConstats() + + /** + * Constant variables for the form + * + * These values won't get overridden by POST or GET vars + * + * @return void + * @access public + */ + public function configureConstants() + { + if (ctype_digit($_REQUEST['id'])) { + $constants = array('id' => $_REQUEST['id']); + } else { + $constants = array(); + } + $this->setupConstants($constants); + } + + // }}} + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + if (ctype_digit($_REQUEST[$this->primaryKey])) { + try { + $sql = " + SELECT ci.id,ig.name + FROM contact_inq ci LEFT OUTER JOIN inq_group ig ON (ci.groupid = ig.id) + WHERE ci.id = :id"; + $getIntData = $this->dbh->prepare($sql); + $sql = " + SELECT * + FROM {$this->tableName} + WHERE {$this->primaryKey} = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":id", $_REQUEST[$this->primaryKey], PDO::PARAM_INT); + $stmt->execute(); + $defaults = $stmt->fetch(PDO::FETCH_ASSOC); + if ($defaults['interest']) { + $pattern = "/^:|:$/"; + $intString = preg_replace($pattern, "", $defaults['interest']); + $intArray = explode(":", $intString); + if (is_array($intArray) && !empty($intArray)) { + $newIntArray = array(); + foreach ($intArray as $intId) { + if (is_numeric($intId)) { + $getIntData->bindParam(":id", $intId, PDO::PARAM_INT); + $getIntData->execute(); + $row = $getIntData->fetch(PDO::FETCH_ASSOC); + // set the new interest array + $newIntArray[$row['name']][$row['id']] = true; + } + } + $defaults['interest'] = $newIntArray; + } + } + if ($defaults['contact_type']) { + $pattern = "/^:|:$/"; + $cTypesString = preg_replace($pattern, "", $defaults['contact_type']); + // set the new contact type array + $defaults['contact_type'] = explode(":", $cTypesString); + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } else { + $defaults = array( + 'state' => '', + 'mail_ok' => 1 + ); + } + + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + + $contactTypesSetup + = $this->config->getItem('section', 'contact_types') + ->toArray(); + $cType = $contactTypesSetup['contact_types']; + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'name' => 'start', + 'display' => $_REQUEST['start'] + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'user_agent', + 'display' => 'User Agent' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'remote_addr', + 'display' => 'Remote Address' + ); + if (ctype_digit($_REQUEST[$this->primaryKey])) { + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => $this->primaryKey + ); + } + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lname', + 'display' => 'Last Name' + ); + if ($this->tableName == 'customer') { + $add1 = 'add1'; + $add2 = 'add2'; + } else { + $add1 = 'address'; + $add2 = 'address2'; + } + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => $add1, + 'display' => 'Address 1' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => $add2, + 'display' => 'Address 2' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'city', + 'display' => 'City' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'mail_ok', + 'display' => 'Mail Ok?', + 'opts' => 'Yes', + 'val' => array(0, 1) + ); + 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 + ); + } + } + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'contact_type', + 'display' => 'Contact Type', + 'opts' => $cType, + 'att' => array('multiple' => 'multiple') + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit_rmv', + 'display' => 'Submit Form' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Invalid Email Format!', + 'type' => 'email', + 'format' => array('use_rfc822' => true), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'fax', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'mail_ok', + 'message' => 'ERROR: Invalid Value!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: There is an existing account with this name!', + 'type' => 'callback', + 'format' => array($this, 'checkContactEmail'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ 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' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function, configures the entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + $this->configureDefaults(); + $this->configureConstants(); + } + + // }}} + // {{{ contactExists() + + /** + * Checks for a duplicate email address already in the DB. + * + * @param string $email The email address to check for in the DB + * + * @return boolean If the email address already exists + * @access protected + */ + protected function contactExists($email) + { + // Check if a contact w/ the submitted email already exists. + // if so, then we need to update, if not then do a fresh insert. + try { + $sql = " + SELECT count(*) AS count + FROM {$this->tableName} + WHERE email = :email"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $email, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('count', $contactExists); + $stmt->fetch(); + + return (bool) $contactExists; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ error() + + /** + * Display errors with the form to the user + * + * @param object $error PEAR Error Object + * + * @return void + * @access public + */ + public function error($error) + { + // make the variables static so that is only has to do the defining + // on the first call. + static $errorMessages; + static $className; + + // define the various error messages + if (!isset($errorMessages)) { + $className = get_class($this); + $errorMessages = array( + FORM_OK => 'No error', + FORM_ERROR => 'Unknown error', + NO_RECORD => 'Setting both properties (email and hasContactDB) to false in the ' . $className . ' class will result in no email record being sent and no record being inserted into the database. There will be no record that this form was ever filled out.', + INVALID_DB => 'Please set the property hasContactDB to a boolean value in the class ' . $className . ' before continuing', + MISSING_CONSTANT => 'You have failed to set a CONSTANT for the class ' . $className . ' to function properly', + MISSING_CONTACT_TYPE => 'Please set the property contactType in the class '. $className . ' before continuing',); + } + + if (!is_null($error->message)) { + $message = $error->message; + } elseif (isset($errorMessages[$error->code])) { + $message = $errorMessages[$error->code]; + } else { + $message = $errorMessages[$error->code]; + $message = $errorMessages[FORM_ERROR]; + } + + echo "
    {$message}
    "; + } + + // }}} + + // {{{ 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; + } + + // }}} + + // {{{ 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( + 'user_agent', + 'remote_addr', + 'contact_type', + ); + $this->setFormData($e); + $this->start = $values['start']; + unset($values['start']); + // Get rid of any elements in the values array that + // aren't going to be used when inserting/updating the db. + $values = Toolkit_Common::cleanArray($values); + + $isUpdate = (ctype_digit($_REQUEST[$this->primaryKey])) ? true: false; + + if (is_array($values['interest']) && !empty($values['interest'])) { + foreach ($values['interest'] as $iGroup => $interests) { + $newInterest[] = implode(':', array_keys($interests)); + } + if (is_array($newInterest)) { + $values['interest'] = ':' . implode(':', $newInterest) . ':'; + } + } + if (!isset($values['interest'])) { + $values['interest'] = ''; + } + if (is_array($values['contact_type']) && !empty($values['contact_type'])) { + $values['contact_type'] = ':' . implode(':', $values['contact_type']) . ':'; + } + if (!isset($values['contact_type'])) { + $values['contact_type'] = ''; + } + + if ($isUpdate) { + $this->Action = 'Contact Updated'; + } else { + $this->Action = 'Contact Added'; + } + $values['create_date'] = date('m/d/Y'); + // build a contact or customer class object with the values from + // the Contact form + if ($this->tableName == 'contact') { + $contact = Toolkit_LeadManager_Contact::createByValues($values); + } else { + $contact = Toolkit_LeadManager_Customer::createByValues($values); + } + + if ($contact->getMailOk()) { + if ( defined('STREAMSEND_FORMS_API') + && STREAMSEND_FORMS_API) { + $contact->attach(new Toolkit_LeadManager_StreamSend()); + } + if ( defined('CONSTANT_CONTACT') + && CONSTANT_CONTACT) { + $contact->attach(new Toolkit_LeadManager_ConstantContact()); + } + } + + $contact->save($this->dbh, false); + return true; + } + + // }}} + // {{{ setConfig() + /** + * setConfig + * + * @param Config_Container $c instance of Config Container + * + * @access public + * @return string + */ + function setConfig(Config_Container $c) + { + $this->config = $c; + }// }}} + // {{{ setInterestFields() + + /** + * Contact DB interests + * + * @return void + * @access protected + */ + protected function setInterestFields() + { + try { + $sql = " + SELECT contact_inq.*, inq_group.name + FROM contact_inq LEFT OUTER JOIN inq_group ON (contact_inq.groupid = inq_group.id) + ORDER BY groupid, pos"; + + $i = array(); + foreach ($this->dbh->query($sql) as $row) { + $i[$row['name']][$row['id']] = $row['header']; + } + + $this->inquiries = $i; + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setPrimaryKey() + /** + * setPrimaryKey + * + * @param mixed $fieldName Primary Key of Table + * + * @access public + * @return string + */ + function setPrimaryKey($fieldName) + { + $this->primaryKey = $fieldName; + }// }}} + // {{{ setTableName() + /** + * setTableName + * + * @param mixed $tableName Database table name + * + * @access public + * @return string + */ + function setTableName($tableName) + { + $this->tableName = $tableName; + }// }}} + + // {{{ setupRenderers() + // @codeCoverageIgnoreStart + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = ' + * + '; + $error = ' +
    {error}
    + '; + $renderer->setElementTemplate( + ' + + '.$required.'{label}'.$error.'{element} + + ', + 'interest' + ); + if (is_array($this->interestsGroups)) { + foreach ($this->interestsGroups as $group => $gData) { + $renderer->setGroupTemplate( + '
    {content}', + 'interest['.$group.']' + ); + $renderer->setGroupElementTemplate( + '{element}', + 'interest['.$group.']' + ); + $renderer->setElementTemplate( + ' + '.$required.'{label}'.$error.'{element} + + ', + 'interest['.$group.']' + ); + } + } + $renderer->setElementTemplate( + ''.$required.'{label}'.$error.'{element}', + 'comments' + ); + $renderer->setElementTemplate( + ' + '.$required.'{label}'.$error.'{element} + + ', + 'submit' + ); + + $renderer->setElementTemplate( + ' + + + + + {element} + + ', + 'captcha_question'); + $renderer->setElementTemplate( + ' + + '.$required.' + + + '.$error.'{element} + What is this? + + ', + 'captcha_rmv' + ); + } + + // @codeCoverageIgnoreEnd + // }}} + // {{{ 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() + { + $this->setupRenderers(); + if ($this->validate()) { + $this->cleanForm(); + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + $output = $this->successMsg; + header("Location: list_contact.phtml?back=1&start=" + . $this->start . "&Action=" . $this->Action); + exit; + } + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $output = parent::toHTML(); + } + return $output; + } + + // }}} + +} diff --git a/Toolkit/Contacts/ContactUs.php b/Toolkit/Contacts/ContactUs.php new file mode 100755 index 0000000..f173add --- /dev/null +++ b/Toolkit/Contacts/ContactUs.php @@ -0,0 +1,1126 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ContactUs.php,v 1.36 2010/07/14 23:33:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Error codes for Toolkit_Contacts_ContactUs + * + * Codes are mapped to textual messaged by errorMessage() method, + * if you add a new code be sure to add a new message for it to errorMessage() + * + * @see Toolkit_Contacts_ContactUs::errorMessage() + */ +define('FORM_OK', 1); +define('FORM_ERROR', -1); +define('NO_RECORD', -2); +define('INVALID_DB', -3); +define('MISSING_CONSTANT', -4); +define('MISSING_CONTACT_TYPE', -5); + +/** + * GLM Contact Us form + * + * This form handles rendering and processing the contact us form. + * Controls the email functionality of the form, whether the client + * has a contact DB to store contact records and how to insert/update + * submitted form values. + * + * @category Toolkit + * @package Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_ContactUs + extends Toolkit_FormBuilder implements Toolkit_Form +{ + + /** + * Table in Database which holds the contact data + * + * @var string + * @access public + */ + public $tableName = 'contact'; + + /** + * 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 = array(); + + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access protected + */ + protected $contactType = '1'; + /** + * which groups to use on form if empty will grab all groups + */ + protected $contactInqGroups = array(); + + /** + * 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. + * + * protected $email = false; + * + * + * @var string + * @access protected + */ + protected $email; + + /** + * From header in the owner email + * + * This just sets the From header in the owner email + * SITENAME + * + * 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 string + * @access protected + */ + protected $siteName; + + /** + * Email subject and

    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 + */ + public $subject; + + /** + * Whether the site has a contact DB to store contact records + * + * If this value is set to false, an email will still be sent to the + * addressed specified in the email property. + * + * @var boolean + * @access protected + */ + protected $hasContactDB = true; + + /** + * The interests from the contact db + * + * @var array + * @access protected + */ + protected $inquiries = array(); + + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access protected + */ + protected $successMsg = ' + +
    + Thank you for your questions or comments! +
    '; + + /** + * 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 + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rules/Zip.php + */ + protected $registeredRules = array( + 'zip', + 'phone', + array( + 'checkEmail', + 'callback', + 'email', + '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; + + /** + * Class constructor + * + * @param object $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 tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @author Jamie Kahgee + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + // Make sure these end cases are never met. + // These are more for the development phase. + if ($this->email === false && $this->hasContactDB === false) { + PEAR::raiseError( + null, + NO_RECORD, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + if (!is_bool($this->hasContactDB)) { + PEAR::raiseError( + null, + INVALID_DB, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + // we haven't defined the FROM_NEWS_EMAIL constant and + // the email will default to relying on it. + if ( !defined('FROM_NEWS_EMAIL') + && (empty($this->email) && $this->email !== false) + ) { + PEAR::raiseError( + 'You need to define the FROM_NEWS_EMAIL + constant for this form to work correctly', + MISSING_CONSTANT, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + if (!is_numeric($this->contactType) && $this->hasContactDB) { + PEAR::raiseError( + null, + MISSING_CONTACT_TYPE, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + + $conf = new Config; + $c =& $conf->parseConfig( + BASE . 'Toolkit/Contacts/config.ini', + 'IniFile' + ); + $table = $c->getItem('section', 'conf') + ->getItem('directive', 'table') + ->getContent(); + $this->tableName = $table; + + // Default Renderer Form templates for QuickForm in respect to this + // classes needs. + if ($this->email !== false && empty($this->email)) { + // Set to false to turn off email function. + $this->email = CONTACT_EMAIL; + } + if (empty($this->siteName)) { + $this->siteName = SITENAME; + } + if (empty($this->subject)) { + $this->subject = 'Contact Request from website ' . SITENAME; + } + + /** + * Where are the flexy templates stored at for this class. + */ + define('TEMPLATES_DIR', BASE . 'Toolkit/Contacts/templates'); + + /** + * Where are the compiled flexy templates stored at for this class. + */ + define('COMPILED_DIR', BASE . 'Toolkit/Contacts/templates/compiled'); + $oldUmask = umask(0); + if (!is_dir(TEMPLATES_DIR)) { + mkdir(TEMPLATES_DIR, 0770, true); + } + if (!is_dir(COMPILED_DIR)) { + mkdir(COMPILED_DIR, 0770, true); + } + umask($oldUmask); + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = TEMPLATES_DIR; + $this->flexyOptions['compileDir'] = COMPILED_DIR; + + $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' => 20, + 'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/', + 'font_file' => 'times.ttf', + 'background_color' => '#cccccc', + 'obfuscation' => false, + 'angle' => true, + ), + ); + } + + /** + * Constant variables for the form + * + * These values won't get overridden by POST or GET vars + * + * @return void + * @access public + */ + public function configureConstants() + { + $constants = array( + 'user_agent' => $_SERVER['HTTP_USER_AGENT'], + 'remote_addr' => $_SERVER['REMOTE_ADDR'], + ); + $this->setupConstants($constants); + } + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + $defaults = array( + 'state' => '', + 'mail_ok' => 1 + ); + if (defined("MEMBERS_DB") && MEMBERS_DB) { + $defaults['members'] = 1; + } + + $this->setupDefaults($defaults); + } + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + if ($this->hasContactDB) { + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + } + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lname', + 'display' => 'Last Name' + ); + if ($this->tableName == 'customer') { + $add1 = 'add1'; + $add2 = 'add2'; + } else { + $add1 = 'address'; + $add2 = 'address2'; + } + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => $add1, + 'display' => 'Address 1' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => $add2, + 'display' => 'Address 2' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'city', + 'display' => 'City' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax' + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'comments', + 'display' => 'Comments' + ); + if ($this->hasContactDB) { + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'mail_ok', + 'display' => '', + 'opts' => 'Yes, I would like to receive Email Newsletters', + 'val' => array(0, 1) + ); + if (defined("MEMBERS_DB") && MEMBERS_DB) { + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'members', + 'display' => '', + 'opts' => 'Yes, I would like to receive information via e-mail from '.SITENAME.' Members', + 'val' => array(0, 1) + ); + } + } + 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 + ); + } + } + $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 Form' + ); + + $this->setupElements($e); + } + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + $r[] = array( + 'element' => array('email', 'email_rmv'), + 'message' => 'ERROR: Your Email Addresses Do Not Match!', + 'type' => 'compare', + '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' => 'state', + 'message' => 'ERROR: Invalid State!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + */ + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'fax', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'mail_ok', + 'message' => 'ERROR: Invalid Value!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'captcha_rmv', + 'message' => 'ERROR: Incorrect verification code!', + 'type' => 'CAPTCHA', + 'format' => $this->captchaQuestion, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + + $this->setupRules($r); + } + + /** + * 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' + ); + + $this->setupFilters($f); + } + + /** + * Helper function, configures the entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + $this->configureDefaults(); + $this->configureConstants(); + } + + /** + * Checks for a duplicate email address already in the DB. + * + * @param string $email The email address to check for in the DB + * + * @return boolean If the email address already exists + * @access protected + */ + protected function contactExists($email) + { + // Check if a contact w/ the submitted email already exists. + // if so, then we need to update, if not then do a fresh insert. + try { + $sql = " + SELECT count(*) AS count + FROM {$this->tableName} + WHERE email = :email"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $email, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('count', $contactExists); + $stmt->fetch(); + + return (bool) $contactExists; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + /** + * Check for a contact or customer with given email address if found + * it returns the contact or customer id + * + * @param type $email Matching email for contact or customer + * + * @return integer + */ + protected function getContactIdByEmail($email) + { + try { + $id = ($this->tableName == 'contact') + ? 'id' + : 'cust_id'; + $sql = " + SELECT {$id} + FROM {$this->tableName} + WHERE email = :email"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $email, PDO::PARAM_STR); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * 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; + } + + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + // for comments textarea need to replace newlines with br + $this->formData['comments']['element'] + = nl2br($this->getSubmitValue('comments')); + + $userEmail = $this->getSubmitValue('email'); + $page->email_from = GLM_TOOLBOX::valid_email(($userEmail)) + ? $userEmail + : OWNER_EMAIL; + $page->subject = $this->subject; + $page->client_info = $this->clientInfo; + $page->fname = $this->getSubmitValue('fname'); + $page->lname = $this->getSubmitValue('lname'); + $page->formData = $this->formData; + + if ( isset($this->newInterest) + && is_array($this->newInterest) + && !empty($this->newInterest) + ) { + // Clean up the interests so they will look nice in the email + $page->formData['interest']['nowrap'] = 'nowrap'; + $page->formData['interest']['element'] = null; + + foreach ($this->newInterest as $group => $elements) { + $page->formData['interest['.$group.']']['label'] = $group; + foreach ($elements as $e => $vale) { + $interest[] = $this->inquiries[$group][$e]; + } + $page->formData['interest['.$group.']']['element'] + = implode("
    ", $interest); + unset($interest); + } + } + + if ($this->elementExists('mail_ok')) { + // Clean up the mail_ok flag so its human readable + $page->formData['mail_ok']['label'] = 'Emails'; + $page->formData['mail_ok']['element'] + = ($page->formData['mail_ok']['element']) ? 'Yes' : 'No'; + } + + if (defined("MEMBERS_DB") && MEMBERS_DB) { + if ($this->elementExists('members')) { + // Clean up the mail_ok flag so its human readable + $page->formData['members']['label'] = 'Members'; + $page->formData['members']['element'] + = ($page->formData['members']['element']) ? 'Yes' : 'No'; + } + } + + $template->compile('emailOwner.tpl'); + $htmlMsg = $template->bufferedOutputObject($page); + + if ($hasInterestField) { + // Text version can't have HTML in it + // so reset the interests to use commas + $page->formData['interest']['element'] = implode(", ", $interests); + } + $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"); + $fromName = preg_replace( + '/[^A-Z ]/i', '', + $page->fname.' '.$page->lname + ); + $mimeMail->setFrom("{$fromName} <{$page->email_from}>"); + $mimeMail->setSubject($this->subject); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory($mailFactory); + $body = $mimeMail->get(); + $setHeader['Reply-To'] = sprintf( + '%1$s %2$s <%3$s>', + trim($this->getSubmitValue('fname'), "\r"), + trim($this->getSubmitValue('lname'), "\r"), + trim($this->getSubmitValue('email'), "\r") + ); + + $headers = $mimeMail->headers($setHeader); + + $res = $mail->send($this->email, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } else { + return $res; + } + } + + /** + * Display errors with the form to the user + * + * @param object $error PEAR Error Object + * + * @return void + * @access public + */ + public function error($error) + { + // make the variables static so that is only has to do the defining + // on the first call. + static $errorMessages; + static $className; + + // define the various error messages + if (!isset($errorMessages)) { + $className = get_class($this); + $errorMessages = array( + FORM_OK => 'No error', + FORM_ERROR => 'Unknown error', + NO_RECORD => 'Setting both properties (email and hasContactDB) to false in the ' . $className . ' class will result in no email record being sent and no record being inserted into the database. There will be no record that this form was ever filled out.', + INVALID_DB => 'Please set the property hasContactDB to a boolean value in the class ' . $className . ' before continuing', + MISSING_CONSTANT => 'You have failed to set a CONSTANT for the class ' . $className . ' to function properly', + MISSING_CONTACT_TYPE => 'Please set the property contactType in the class '. $className . ' before continuing',); + } + + if (!is_null($error->message)) { + $message = $error->message; + } elseif (isset($errorMessages[$error->code])) { + $message = $errorMessages[$error->code]; + } else { + $message = $errorMessages[$error->code]; + $message = $errorMessages[FORM_ERROR]; + } + + echo "
    {$message}
    "; + } + + /** + * 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; + } + + /** + * 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) + { + unset($values['catid']); + // Form data used for the insert/update sql queries and + // the form email. + $e = array( + 'user_agent', + 'remote_addr', + 'contact_type', + ); + $this->setFormData($e); + + + // If no contact db, return true so we can send owner email. + if (!$this->hasContactDB) { + return true; + } + + // Get rid of any elements in the values array that + // aren't going to be used when inserting/updating the db. + $values = Toolkit_Common::cleanArray($values); + + // Check if we are updating an existing contact or not + // question: is this the best approach? what if someone else + // sends a form through w/ different data but the same emil addy + // the old users data can be completely wiped out. + $existingContact = $this->contactExists($values['email']); + // setup newInterest aray with the interest values + // because their grouped can't be found with getElement('interest') + $this->newInterest = $values['interest']; + // update create_date for this contact + $values['create_date'] = date('m/d/Y'); + + // set up interest field values + if (is_array($values['interest']) && !empty($values['interest'])) { + foreach ($values['interest'] as $iGroup => $interests) { + $newInterest[] = implode(':', array_keys($interests)); + } + if (is_array($newInterest)) { + $values['interest'] = ':' . implode(':', $newInterest) . ':'; + } + } + if ($existingContact) { + $contactId = $this->getContactIdByEmail($values['email']); + $cType = $this->_getExistingContactTypes($contactId); + $idFieldName + = ($this->tableName == 'contact') + ? 'id' + : 'cust_id'; + $values[$idFieldName] = $contactId; + $existingTypes + = (is_array($cType)) + ? explode(':', $cType) + : array(); + if (!in_array($this->contactType, $existingTypes)) { + $values['contact_type'] = "$cType{$this->contactType}:"; + } else { + $values['contact_type'] = ":".implode(':', array_filter($existingTypes)).":"; + } + } else { + $values['contact_type'] = ":{$this->contactType}:"; + } + // build a contact or customer class object with the values from + // the Contact form + if ($this->tableName == 'contact') { + $contact = Toolkit_LeadManager_Contact::createByValues($values); + } else { + $contact = Toolkit_LeadManager_Customer::createByValues($values); + } + if ($contact->getMailOk()) { + if ( defined('STREAMSEND_FORMS_API') + && STREAMSEND_FORMS_API) { + $contact->attach(new Toolkit_LeadManager_StreamSend()); + } + if ( defined('CONSTANT_CONTACT') + && CONSTANT_CONTACT) { + $contact->attach(new Toolkit_LeadManager_ConstantContact()); + } + } + $contact->save($this->dbh, false); + return true; + } + + /** + * Contact DB interests + * + * @return void + * @access protected + */ + protected function setInterestFields() + { + try { + $groupWhere + = (!empty($this->contactInqGroups)) + ? "WHERE contact_inq.groupid IN (".implode(',',$this->contactInqGroups).")" + : ""; + $sql = " + SELECT contact_inq.*, inq_group.name + FROM contact_inq + LEFT OUTER JOIN inq_group + ON (contact_inq.groupid = inq_group.id) + $groupWhere + ORDER BY inq_group.name, contact_inq.pos"; + + $i = array(); + foreach ($this->dbh->query($sql) as $row) { + $i[$row['name']][$row['id']] = $row['header']; + } + + $this->inquiries = $i; + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // @codeCoverageIgnoreStart + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = ' * '; + $error = '
    {error}
    '; + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'interest'); + if (is_array($this->interestsGroups)) { + foreach ($this->interestsGroups as $group => $gData) { + $renderer->setGroupTemplate('
    {content}', 'interest['.$group.']'); + $renderer->setGroupElementTemplate('{element}', 'interest['.$group.']'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'interest['.$group.']'); + } + } + $renderer->setElementTemplate(''.$required.'{element} {label}'.$error.'', 'mail_ok'); + $renderer->setElementTemplate(''.$required.'{element} {label}'.$error.'', 'members'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'comments'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'submit_rmv'); + + $renderer->setElementTemplate('{element}', 'captcha_question'); + $renderer->setElementTemplate(''.$required.''.$error.'{element}What is this?', 'captcha_rmv'); + } + + // @codeCoverageIgnoreEnd + + /** + * 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->setupRenderers(); + if ($this->validate()) { + $this->captchaQuestion->destroy(); + $this->cleanForm(); + + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + $this->emailOwner(); + $output = $this->successMsg; + } + $this->sent = true; + } elseif ($this->isSubmitted()) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output = parent::toHTML(); + } + return $output; + } + + /** + * Return the existing contact/customer contact_type + * + * @param type $contactId id of cust/contact + * + * @return type + */ + private function _getExistingContactTypes($contactId) + { + try { + $idField + = ($this->tableName == 'contact') + ? 'id' + : 'cust_id'; + $sql = " + SELECT contact_type + FROM {$this->tableName} + WHERE {$idField} = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $contactId, PDO::PARAM_STR); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + +} + diff --git a/Toolkit/Contacts/Database/application.sql b/Toolkit/Contacts/Database/application.sql new file mode 100644 index 0000000..f219edd --- /dev/null +++ b/Toolkit/Contacts/Database/application.sql @@ -0,0 +1,15 @@ +CREATE SCHEMA contacts; +GRANT ALL ON SCHEMA contacts TO nobody; + +-- +-- Tables +-- +\i ./tables/contact.sql +\i ./tables/contact_inq.sql +\i ./tables/inq_group.sql +\i ./tables/query_db.sql +\i ./tables/news_response.sql + +-- +-- Procedures +-- diff --git a/Toolkit/Contacts/Database/removeApplication.sql b/Toolkit/Contacts/Database/removeApplication.sql new file mode 100644 index 0000000..f9c8178 --- /dev/null +++ b/Toolkit/Contacts/Database/removeApplication.sql @@ -0,0 +1,8 @@ +-- +-- This will drop everything in the contacts schema. +-- Nothin better be in here except contact related object +-- or it will be dropp +-- +-- The force is strong w/ this one, use it wisely. +-- +DROP SCHEMA IF EXISTS contacts CASCADE; diff --git a/Toolkit/Contacts/Database/tables/contact.sql b/Toolkit/Contacts/Database/tables/contact.sql new file mode 100644 index 0000000..fd43ab4 --- /dev/null +++ b/Toolkit/Contacts/Database/tables/contact.sql @@ -0,0 +1,45 @@ +DROP TABLE IF EXISTS contacts.contact CASCADE; + +CREATE TABLE contacts.contact +(id SERIAL, + create_date DATE DEFAULT CURRENT_DATE, + fname text, + lname text, + company text, + address text, + address2 text, + city text, + state text, + zip text, + country text, + phone text, + fax text, + email text, + user_agent text, + remote_addr text, + interest text, + mail_ok BOOLEAN DEFAULT FALSE, + visitorguide BOOLEAN DEFAULT FALSE, + uidpdf text, + visitorguide_download BOOLEAN DEFAULT FALSE, + email_verified BOOLEAN DEFAULT true, + contact_type text, + discover text, + member_ok BOOLEAN DEFAULT FALSE, + staff BOOLEAN DEFAULT FALSE, + comments text, + password text, + verify_password text, + gift_cert BOOLEAN DEFAULT FALSE, + members BOOLEAN DEFAULT FALSE, + PRIMARY KEY (id)); + +CREATE INDEX contact_create_date_indx ON contacts.contact USING btree(create_date); +CREATE INDEX contact_email_indx ON contacts.contact USING btree(email); +CREATE INDEX contact_fname_indx ON contacts.contact USING btree(fname); +CREATE INDEX contact_lname_indx ON contacts.contact USING btree(lname); +CREATE UNIQUE INDEX news_response_id_indx ON contacts.contact USING btree(id); +CREATE UNIQUE INDEX query_db_id_indx ON contacts.contact USING btree(id); + +GRANT ALL ON contacts.contact_id_seq TO nobody; +GRANT ALL ON contacts.contact TO nobody; diff --git a/Toolkit/Contacts/Database/tables/contact_inq.sql b/Toolkit/Contacts/Database/tables/contact_inq.sql new file mode 100644 index 0000000..410e809 --- /dev/null +++ b/Toolkit/Contacts/Database/tables/contact_inq.sql @@ -0,0 +1,13 @@ +DROP TABLE IF EXISTS contacts.contact_inq CASCADE; + +CREATE TABLE contacts.contact_inq +(id SERIAL, + header text, + pos integer, + description text, + image text, + groupid integer, + PRIMARY KEY (id)); + +GRANT ALL ON contacts.contact_inq_id_seq TO nobody; +GRANT ALL ON contacts.contact_inq TO nobody; diff --git a/Toolkit/Contacts/Database/tables/inq_group.sql b/Toolkit/Contacts/Database/tables/inq_group.sql new file mode 100644 index 0000000..01bcd2a --- /dev/null +++ b/Toolkit/Contacts/Database/tables/inq_group.sql @@ -0,0 +1,11 @@ +DROP TABLE IF EXISTS contacts.inq_group CASCADE; + +CREATE TABLE contacts.inq_group +(id SERIAL, + name text, + PRIMARY KEY (id)); + +GRANT ALL ON contacts.inq_group_id_seq TO nobody; +GRANT ALL ON contacts.inq_group TO nobody; + +INSERT INTO contacts.inq_group (name) VALUES ('Interests'); \ No newline at end of file diff --git a/Toolkit/Contacts/Database/tables/news_response.sql b/Toolkit/Contacts/Database/tables/news_response.sql new file mode 100644 index 0000000..a496353 --- /dev/null +++ b/Toolkit/Contacts/Database/tables/news_response.sql @@ -0,0 +1,20 @@ +DROP TABLE IF EXISTS contacts.news_response; + +CREATE TABLE contacts.news_response +(id SERIAL, + subject TEXT, + response TEXT, + image TEXT, + image2 TEXT, + image3 TEXT, + image_align TEXT, + image2_align TEXT, + image3_align TEXT, + mailout DATE DEFAULT CURRENT_DATE, + last_update DATE DEFAULT CURRENT_DATE, + PRIMARY KEY (id)); + +GRANT ALL ON contacts.news_response_id_seq TO nobody; +GRANT ALL ON contacts.news_response TO nobody; + +INSERT INTO contacts.news_response (subject, response) VALUES ('subject', 'response'); diff --git a/Toolkit/Contacts/Database/tables/query_db.sql b/Toolkit/Contacts/Database/tables/query_db.sql new file mode 100644 index 0000000..3a2a0b3 --- /dev/null +++ b/Toolkit/Contacts/Database/tables/query_db.sql @@ -0,0 +1,12 @@ +DROP TABLE IF EXISTS contacts.query_db; + +CREATE TABLE contacts.query_db +(id SERIAL, + query_name TEXT, + query TEXT, + file TEXT, + delimiter text, + PRIMARY KEY (id)); + +GRANT ALL ON contacts.query_db_id_seq TO nobody; +GRANT ALL ON contacts.query_db TO nobody; diff --git a/Toolkit/Contacts/ENewsSignup.php b/Toolkit/Contacts/ENewsSignup.php new file mode 100755 index 0000000..87ff44f --- /dev/null +++ b/Toolkit/Contacts/ENewsSignup.php @@ -0,0 +1,214 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ContactUs.php,v 1.36 2010/07/14 23:33:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Error codes for Toolkit_Contacts_ContactUs + * + * Codes are mapped to textual messaged by errorMessage() method, + * if you add a new code be sure to add a new message for it to errorMessage() + * + * @see Toolkit_Contacts_ContactUs::errorMessage() + */ + +/** + * GLM Contact Us form + * + * This form handles rendering and processing the contact us form. + * Controls the email functionality of the form, whether the client + * has a contact DB to store contact records and how to insert/update + * submitted form values. + * + * @category Toolkit + * @package Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_ENewsSignup + extends Toolkit_Contacts_ContactUs +{ + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access protected + */ + protected $contactType = '2'; + /** + * Email subject and

    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 + */ + public $subject = "ENews Signup Form from website"; + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access protected + */ + protected $successMsg = ' + +
    + Thank you for requesting the ENewsetter. +
    '; + // {{{ configureConstats() + + /** + * Class constructor + * + * @param object $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 tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @author Jamie Kahgee + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->email = ENEWS_EMAIL; + } + + /** + * Constant variables for the form + * + * These values won't get overridden by POST or GET vars + * + * @return void + * @access public + */ + public function configureConstants() + { + $constants = array( + 'user_agent' => $_SERVER['HTTP_USER_AGENT'], + 'remote_addr' => $_SERVER['REMOTE_ADDR'], + 'mail_ok' => 1 + ); + $this->setupConstants($constants); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + if ($this->hasContactDB) { + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + } + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email' + ); + if ($this->hasContactDB) { + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'mail_ok', + ); + } + $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 Form' + ); + + $this->setupElements($e); + } + + // }}} +} diff --git a/Toolkit/Contacts/MeetingRequest.php b/Toolkit/Contacts/MeetingRequest.php new file mode 100755 index 0000000..91625be --- /dev/null +++ b/Toolkit/Contacts/MeetingRequest.php @@ -0,0 +1,337 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ContactUs.php,v 1.36 2010/07/14 23:33:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Error codes for Toolkit_Contacts_ContactUs + * + * Codes are mapped to textual messaged by errorMessage() method, + * if you add a new code be sure to add a new message for it to errorMessage() + * + * @see Toolkit_Contacts_ContactUs::errorMessage() + */ + +/** + * GLM Contact Us form + * + * This form handles rendering and processing the contact us form. + * Controls the email functionality of the form, whether the client + * has a contact DB to store contact records and how to insert/update + * submitted form values. + * + * @category Toolkit + * @package Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_MeetingRequest + extends Toolkit_Contacts_ContactUs +{ + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access protected + */ + protected $contactType = '5'; + /** + * Email subject and

    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 + */ + public $subject = "Meeting Request from website"; + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access protected + */ + protected $successMsg = ' + +
    + Thank you for requesting a meeting. +
    '; + // {{{ configureConstats() + + /** + * Class constructor + * + * @param object $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 tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @author Jamie Kahgee + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->email = ENEWS_EMAIL; + } + + /** + * Constant variables for the form + * + * These values won't get overridden by POST or GET vars + * + * @return void + * @access public + */ + public function configureConstants() + { + $constants = array( + 'user_agent' => $_SERVER['HTTP_USER_AGENT'], + 'remote_addr' => $_SERVER['REMOTE_ADDR'], + 'mail_ok' => 1 + ); + $this->setupConstants($constants); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + if ($this->hasContactDB) { + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + } + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'lname', + 'display' => 'Last Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address1', + 'display' => 'Address 1' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address2', + 'display' => 'Address 2' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $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' => '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' => 'text', + 'req' => false, + 'name' => 'eventtype', + 'display' => 'Type of function' + ); + $num = array(1,2,3,4,5,6,7,8,9,10); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'rooms', + 'display' => 'Number of Rooms', + 'opts' => $num + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'nights', + 'display' => 'Number of Nights', + 'opts' => $num + ); + if ($this->hasContactDB) { + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'mail_ok', + ); + } + $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 Form' + ); + + $this->setupElements($e); + } + + // }}} +} diff --git a/Toolkit/Contacts/SaveTripPlanner.php b/Toolkit/Contacts/SaveTripPlanner.php new file mode 100755 index 0000000..d0af397 --- /dev/null +++ b/Toolkit/Contacts/SaveTripPlanner.php @@ -0,0 +1,619 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Ask the concierge form + * + * This form handles rendering and processing the contact form. + * + * @category Toolkit + * @package Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: + * @link <> + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_SaveTripPlanner + extends Toolkit_Contacts_ContactUs +{ + // {{{ properties + + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access public + */ + public $contactType = '3'; + + /** + * 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. + * + * public $email = false; + * + * + * @var unknown + * @access public + */ + public $email = false; + + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access public + */ + public $successMsg = ' +
    + You have successfully created a new account. You may receive a confirmation email. +
    '; + + /** + * Email subject and

    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 public + */ + public $subject; + + protected $plannerListPageId; + protected $plannerFormPageId; + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param string $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 defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for 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->subject = 'Travel List from website ' . SITENAME; + $this->plannerListPageId = MEMBER_SESSION_PAGE; + $this->plannerFormPageId = MEMBER_SESSION_FORM; + } + + // }}} + + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lname', + 'display' => 'Last Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address', + 'display' => 'Address 1' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address2', + 'display' => 'Address 2' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'city', + 'display' => 'City' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'password', + 'display' => 'Password' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'verify_password', + 'display' => 'Verify Password' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'mail_ok', + 'display' => ', I would like to receive Email Newsletters', + 'opts' => 'Yes', + 'val' => array(0, 1) + ); + 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 + ); + } + } + $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 Form' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + $r[] = array( + 'element' => array('email', 'email_rmv'), + 'message' => 'ERROR: Your Email Addresses Do Not Match!', + 'type' => 'compare', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => array('password', 'verify_password'), + 'message' => 'ERROR: Your Passwords do not match!', + 'type' => 'compare', + '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' => 'state', + 'message' => 'ERROR: Invalid State!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + */ + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'fax', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'mail_ok', + 'message' => 'ERROR: Invalid Value!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'captcha_rmv', + 'message' => 'ERROR: Incorrect verification code!', + 'type' => 'CAPTCHA', + 'format' => $this->captchaQuestion, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ contactExists() + + /** + * Checks for a duplicate email address already in the DB. + * + * @param string $email The email address to check for in the DB + * + * @return boolean If the email address already exists + * @access protected + */ + protected function contactExists($email) + { + // Check if a contact w/ the submitted email already exists. + // if so, then we need to update, if not then do a fresh insert. + try { + $sql = " + SELECT id,password + FROM contact + WHERE email = :email"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $email, PDO::PARAM_STR); + $stmt->execute(); + //$stmt->bindColumn('id', $contactExists); + //$stmt->bindColumn('password', $password); + $row = $stmt->fetch(); + //die('
    '.print_r($row, true).'
    '); + if (!empty($row)) { + return array( + 'contactId' => $row['id'], + 'password' => $row['password'] + ); + } else { + return false; + } + + } 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) + { + // Form data used for the insert/update sql queries and + // the form email. + $e = array( + 'user_agent', + 'remote_addr', + 'contact_type', + 'catid', + 'cPage', + ); + $this->setFormData($e); + + + // If no contact db, return true so we can send owner email. + if (!$this->hasContactDB) { + return true; + } + + // Get rid of any elements in the values array that + // aren't going to be used when inserting/updating the db. + $values = Toolkit_Common::cleanArray($values); + + // Check if we are updating an existing contact or not + // question: is this the best approach? what if someone else + // sends a form through w/ different data but the same emil addy + // the old users data can be completely wiped out. + $existingContact = $this->contactExists($values['email']); + // update create_date for this contact + $values['create_date'] = date('m/d/Y'); + + $values['password'] = md5($values['password']); + unset($values['catid']); + unset($values['cPage']); + + $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 (is_array($existingContact)) { + // if there already in the database then give a message that they're already in and need to login + // this is true only if they already have a password set + if (!$existingContact['password']) { + $contactId = $existingContact['contactId']; + $cType = $this->_getExistingContactTypes($contactId); + $existingTypes + = (is_array($cType)) + ? explode(':', $cType) + : array(); + if (!in_array($this->contactType, $existingTypes)) { + $values['contact_type'] = "$cType{$this->contactType}:"; + } else { + $values['contact_type'] = ":".implode(':', array_filter($existingTypes)).":"; + } + // build a contact or customer class object with the values from + // the Contact form + if ($this->tableName == 'contact') { + $contact = Toolkit_LeadManager_Contact::createByValues($values); + } else { + $contact = Toolkit_LeadManager_Customer::createByValues($values); + } + if ( defined('STREAMSEND_FORMS_API') + && STREAMSEND_FORMS_API + && $values['mail_ok']) { + $contact->attach(new Toolkit_LeadManager_StreamSend()); + } + $contact->save($this->dbh); + $tripPlannerAuth->setAuth($values['email']); + $tripPlannerAuth->setAuthData('id', $contactId); + $tripPlannerAuth->setAuthData('username', $values['email']); + $sessionList->saveList($contactId); + return true; + } else { + $seoUrl = Toolkit_Template_Page::getSeoUrl($this->_pageGateway, $this->plannerListPageId); + $this->errorMsg = "

    Your Email address already exist. Please sign-in.

    "; + return false; + } + } else { + $values['contact_type'] = ":{$this->contactType}:"; + // build a contact or customer class object with the values from + // the Contact form + if ($this->tableName == 'contact') { + $contact = Toolkit_LeadManager_Contact::createByValues($values); + } else { + $contact = Toolkit_LeadManager_Customer::createByValues($values); + } + if ( defined('STREAMSEND_FORMS_API') + && STREAMSEND_FORMS_API + && $values['mail_ok']) { + $contact->attach(new Toolkit_LeadManager_StreamSend()); + } + $contact->save($this->dbh); + $contactId = $contact->getId(); + // put in the creation of the contact record here + // and set contactId + $contactData = $this->contactExists($values['email']); + $contactId = $contactData['contactId']; + $tripPlannerAuth->setAuth($values['email']); + $tripPlannerAuth->setAuthData('id', $contactId); + $tripPlannerAuth->setAuthData('username', $values['email']); + $sessionList->saveList($contactId); + return true; + } + } + + // }}} + + public function setGateway(Toolkit_Toolbox_PageGatewayAbstract $gateway) + { + $this->_pageGateway = $gateway; + } + + // {{{ 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() + { + $this->setupRenderers(); + if ($this->validate()) { + $this->captchaQuestion->destroy(); + $this->cleanForm(); + + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + $output = $this->successMsg; + } else { + $output = $this->errorMsg; + //$output .= parent::toHTML(); + } + $this->sent = true; + } elseif ($this->isSubmitted()) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + //$output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output .= parent::toHTML(); + } + return $output; + } + + // }}} + +} diff --git a/Toolkit/Contacts/SendTripPlanner.php b/Toolkit/Contacts/SendTripPlanner.php new file mode 100755 index 0000000..342d6a9 --- /dev/null +++ b/Toolkit/Contacts/SendTripPlanner.php @@ -0,0 +1,742 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Ask the concierge form + * + * This form handles rendering and processing the contact form. + * + * @category Toolkit + * @package Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: + * @link <> + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_SendTripPlanner extends Toolkit_Contacts_ContactUs +{ + // {{{ properties + + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access public + */ + public $contactType = '3'; + + /** + * 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. + * + * public $email = false; + * + * + * @var unknown + * @access public + */ + public $email = false; + + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access public + */ + public $successMsg = ' + +
    +

    Thank you for adding these businesses to your Trip Planner. + Your information is currently being sent to each business so they + may contact you regarding your visit.

    +
    '; + + /** + * Email subject and

    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 public + */ + public $subject; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param string $pdo Passed in 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 defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for 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->subject = 'Travel List from website ' . SITENAME; + $successMsg = ' + +
    +

    Thank you for adding these businesses to your Trip Planner. + Your information is currently being sent to each business so they + may contact you regarding your visit to '.SITENAME.'.

    +
    '; + } + + // }}} + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + $defaults = array( + 'state' => '', + 'mail_ok' => 1, + 'catid' => $_REQUEST['catid'], + 'cPage' => $_REQUEST['cPage'] + ); + + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'catid' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'cPage' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lname', + 'display' => 'Last Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address', + 'display' => 'Address 1' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address2', + 'display' => 'Address 2' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'city', + 'display' => 'City' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax' + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'comments', + 'display' => 'Comments' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'mail_ok', + 'display' => 'Yes, I would like to receive Email Newsletters', + 'opts' => 'Yes', + 'val' => array(0, 1) + ); +// 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 +// ); +// } +// } + $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 Form' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + $r[] = array( + 'element' => array('email', 'email_rmv'), + 'message' => 'ERROR: Your Email Addresses Do Not Match!', + 'type' => 'compare', + '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' => 'state', + 'message' => 'ERROR: Invalid State!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + */ + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'fax', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'mail_ok', + 'message' => 'ERROR: Invalid Value!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'captcha_rmv', + 'message' => 'ERROR: Incorrect verification code!', + 'type' => 'CAPTCHA', + 'format' => $this->captchaQuestion, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ sendEmails() + + /** + * sendEmails + * + * From the list of emails contained in $_SESSIEN['wish_list'] + * send out emails to each email address + * only if we're on the production server + * if on the development server send to OWNER_EMAIL + * + * @return void + * @access public + */ + function sendEmails() + { + $hasInterestField = $this->elementExists('interest'); + + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + // for comments textarea need to replace newlines with br + $this->formData['comments']['element'] = nl2br($this->getSubmitValue('comments')); + + $page->email_from = OWNER_EMAIL; + $page->subject = $this->subject; + $page->client_info = $this->clientInfo; + $page->fname = $this->getSubmitValue('fname'); + $page->lname = $this->getSubmitValue('lname'); + $page->formData = $this->formData; + + // unset some extra fields + unset( + $page->formData['catid'], + $page->formData['cPage'] + ); + + if ($hasInterestField) { + // Clean up the interests so they will look nice in the email + $page->formData['interest']['nowrap'] = 'nowrap'; + $page->formData['interest']['element'] = null; + $g =& $this->getElement('interest'); + $ge =& $g->getElements(); + $interests = array(); + foreach ($ge as $e) { + if ($e->getChecked()) { + $interests[] = $e->getText(); + } + } + $page->formData['interest']['element'] = implode('
    ', $interests); + } + + if ($this->elementExists('mail_ok')) { + // Clean up the mail_ok flag so its human readable + $page->formData['mail_ok']['element'] + = ($page->formData['mail_ok']['element']) ? 'Yes' : 'No'; + } + + $template->compile('emailOwner.tpl'); + $htmlMsg = $template->bufferedOutputObject($page); + + if ($hasInterestField) { + // Text version can't have HTML in it + // so reset the interests to use commas + $page->formData['interest']['element'] = implode(", ", $interests); + } + $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"; + } + + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom("Online Form <{$page->email_from}>"); + $mimeMail->setSubject($this->subject); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory('mail'); + $body = $mimeMail->get(); + $headerFormat = "%s %s <%s>"; + $setHeader['Reply-To'] = sprintf( + $headerFormat, + $this->getSubmitValue('fname'), + $this->getSubmitValue('lname'), + $this->getSubmitValue('email') + ); + $headers = $mimeMail->headers($setHeader); + $sql = " + SELECT member_contact_email + FROM member + WHERE member_id = :member_id"; + $getMemberEmail = $this->dbh->prepare($sql); + + switch (GLM_HOST_ID) { + case "DEVELOPMENT": + case "STEVE" : + // code for sending email + if ( is_array($_SESSION['wish_list']) + && !empty($_SESSION['wish_list'])) { + foreach ($_SESSION['wish_list'] as $memberId => $row) { + try { + $getMemberEmail->bindParam( + ':member_id', + $memberId, + PDO::PARAM_INT + ); + $getMemberEmail->execute(); + $memberEmail = $getMemberEmail->fetchColumn(); + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + if (GLM_TOOLBOX::valid_email($memberEmail)) { + echo '

    Send mail to: '.$memberEmail.'

    '; + } + } + } + $res = $mail->send(OWNER_EMAIL, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } + break; + case "PRODUCTION": + if ( is_array($_SESSION['wish_list']) + && !empty($_SESSION['wish_list'])) { + foreach ($_SESSION['wish_list'] as $memberId => $row) { + try { + $getMemberEmail->bindParam( + ':member_id', + $memberId, + PDO::PARAM_INT + ); + $getMemberEmail->execute(); + $memberEmail = $getMemberEmail->fetchColumn(); + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + // code for sending emails + if (GLM_TOOLBOX::valid_email($memberEmail)) { + $res = $mail->send($memberEmail, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } + } + } + } + break; + } + $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( + $this->dbh, + &$tripPlannerAuth + ); + $sessionList->dumpList(); + return $res; + } + + // }}} + // {{{ showDirectList() + + /** + * showDirectList + * + * Display the list of members in $_SESSION['wish_list'] + * + * @return void + * @access public + */ + function showDirectList() + { + // Initiate HTML_Template_Flexy. + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + $page->memberDirect = $page->memberDirectNoEmail = array(); + if (is_array($_SESSION['wish_list']) && !empty($_SESSION['wish_list'])) { + $sql = " + SELECT member_name,member_contact_email,phone,toll_free + FROM member + WHERE member_id = :member_id"; + $getMemberData = $this->dbh->prepare($sql); + $mACount = $mBCount = 0; + foreach ($_SESSION['wish_list'] as $memberId => $row) { + try { + $getMemberData->bindParam( + ':member_id', + $memberId, + PDO::PARAM_INT + ); + $getMemberData->execute(); + $memberData = $getMemberData->fetch(); + $memberName = $memberData['member_name']; + $memberPhone = $memberData['phone']; + $memberTollFree = $memberData['toll_free']; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + if ($memberData['member_contact_email']) { + $page->memberDirect[] = array( + 'memberName' => $memberName, + 'memberPhone' => $memberPhone, + 'memberTollFree' => $memberTollFree, + 'memberLink' => BASE_URL + .'index.php?catid='.$row['catid'].'&member_id='.$memberId, + 'deleteLink' => BASE_URL + .'Toolkit/Members/TripPlanner/' + .'wish-list.php?catid=' + .$_REQUEST['catid'].'&member_id=' . $memberId + . '&cPage=' . urlencode($_REQUEST['cPage']), + 'trclass' => (($mACount % 2 == 0) ? 'tr1': 'tr2') + ); + $mACount++; + } else { + $page->memberDirectNoEmail[] = array( + 'memberName' => $memberName, + 'memberPhone' => $memberPhone, + 'memberTollFree' => $memberTollFree, + 'memberLink' => BASE_URL + .'index.php?catid='.$row['catid'].'&member_id='.$memberId, + 'deleteLink' => BASE_URL + .'Toolkit/Members/TripPlanner/' + . 'wish-list.php?catid=' + . $_REQUEST['catid'].'&member_id=' . $memberId + . '&cPage=' . urlencode($_REQUEST['cPage']), + 'trclass' => (($mBCount % 2 == 0) ? 'tr1': 'tr2') + ); + $mBCount++; + } + } + } + $this->totalMembersEmails = $mACount; + $this->totalMembersNoEmails = $mBCount; + // Compile the direct-list.html from the templates directory. + $template->compile('direct-list.html'); + + // Merge compiled template with the $page object. + $out = $template->bufferedOutputObject($page); + return $out; + } + // }}} + // {{{ showNoList() + + /** + * showNoList + * + * What to display If nothing is in $_SESSION['wish_list'] + * + * @return void + * @access public + */ + function showNoList() + { + // Initiate HTML_Template_Flexy. + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + $page->baseUrl = BASE_URL; + // Compile the direct-nolist.html from the templates directory. + $template->compile('direct-nolist.html'); + + // Merge compiled template with the $page object. + $out = $template->bufferedOutputObject($page); + return $out; + } + // }}} + // {{{ 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() + { + $this->setupRenderers(); + if ($this->validate()) { + $this->captchaQuestion->destroy(); + $this->cleanForm(); + + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + $this->sendEmails(); + $output = $this->successMsg; + } + $this->sent = true; + } elseif ($this->isSubmitted()) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output .= parent::toHTML(); + } else { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output = $this->showDirectList(); + if ($this->totalMembersEmails > 0) { + $output .= parent::toHTML(); + } + } + return $output; + } + + // }}} +} + diff --git a/Toolkit/Contacts/StreamSend.php b/Toolkit/Contacts/StreamSend.php new file mode 100755 index 0000000..50dec94 --- /dev/null +++ b/Toolkit/Contacts/StreamSend.php @@ -0,0 +1,212 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: StreamSend.php,v 1.5 2010/04/30 19:02:10 matrix Exp $ + * @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', 'false'); +/** + * 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', 'true'); +/** + * 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'); +/** + * URI for streamsend API + */ +define('STREAMSEND_BASE_URL', "https://app.streamsend.com"); + +/** + * Toolkit_Contacts_StreamSend + * + * Contact support class for inergration with StreamSend API + * + * @category Toolkit + * @package Contacts + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_Contacts_StreamSend +{ + // {{{ Class Properties + + + /** + * Description for public + * @var boolean + * @access public + */ + public $debug = false; + + /** + * streamSendFields + * + * array with key values matching the gaslight contact tabel to the + * StreamSend field (normal fields) + * + * @var array + * @access protected + */ + protected $streamSendFields = array( + 'email' => 'email-address', + 'fname' => 'first-name', + 'lname' => 'last-name', + 'address' => 'address1', + 'address2' => 'address2', + 'city' => 'city', + 'state' => 'stateprovince', + 'zip' => 'postal-code', + 'phone' => 'phone-number', + 'interest' => 'interests', + 'contact_type' => 'contact-type' + ); + + /** + * contactInqTypes + * + * array with key values matching the gaslight contact_inq tabel to the + * StreamSend field (Radio fields) + * key = id from contact_inq table + * value = name from contact_inq_table + * value is same name as the StreamSend fieldname + * + * @var array + * @access protected + */ + protected $contactInqTypes = array(); + + /** + * booleanTypes + * + * StreamSend fields (boolean fields) an array of field names for the + * boolean field types + * + * @var array + * @access protected + */ + protected $booleanTypes = array(); + // }}} + // {{{ __construct() + + + /** + * __construct( + * + * @return void + * @access public + */ + public function __construct() + { + } + + + // }}} + // {{{ addContact() + + + /** + * addContact + * + * Given $values from a Toolkit_Contacts Form add Contact + * + * @param array $values Parameter description (if any) ... + * + * @return boolean Return true if successfull + * @access public + */ + public function addContact($values) + { + // check the array $values to make sure it is correct + if (is_array($values) && !empty($values)) { + include_once GLM_APP_BASE.'StreamSend/class_streamsend_api.inc'; + // initialize the streamsend object + $ss = new streamSend (STREAMSEND_BASE_URL, STREAMSEND_LOGIN_ID, + STREAMSEND_KEY); + $ss->debug = $this->debug; + $ret = $ss->contactSearch($values['email']); + + $contactData = array(); + $values[$type] = 1; + foreach ($this->streamSendFields as $glmName => $ssName) { + switch ($glmName) { + case "state": + $contactData[$ssName] = ($values[$glmName]) ? $GLOBALS['states'][$values[$glmName]]: ''; + break; + default: + $contactData[$ssName] = $values[$glmName]; + break; + } + } + foreach ($this->contactInqTypes as $contactInqId => $name) { + $slug = str_replace(" ", "-", strtolower($this->contactInqTypes[$contactInqId])); + if ($values['interest'][$contactInqId]) { + $contactData[$slug] = 'Yes'; + } else { + $contactData[$slug] = 'No'; + } + } + foreach ($this->booleanTypes as $name) { + if ($values[$name]) { + $contactData[$name] = 'Yes'; + } else { + $contactData[$name] = 'No'; + } + } + if ($ret->contact) { + $contacts = $ss->contactUpdate( + $ret->contact->id, + $contactData + ); + } else { + $contacts = $ss->contactCreate( + $contactData, + STREAMSEND_DEFAULT_ACTIVATE, + STREAMSEND_DEFAULT_DELIVER_ACTIVATION, + STREAMSEND_DEFAULT_DELIVER_WELCOME + ); + } + if (!$contacts) { + + // show errors if on development server + switch (GLM_HOST_ID) { + case "DEVELOPMENT": + echo "

    A total and complete failure occured."; + break; + case "PRODUCTION": + break; + } + } + if ($ss->debug == true) { + echo '

    Debug Results

    '.$ss->debugBuffer.'

    '; + } + return true; + } + return false; + } + + + // }}} +} +?> diff --git a/Toolkit/Contacts/VisitorGuide.php b/Toolkit/Contacts/VisitorGuide.php new file mode 100755 index 0000000..1f0009d --- /dev/null +++ b/Toolkit/Contacts/VisitorGuide.php @@ -0,0 +1,308 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ContactUs.php,v 1.36 2010/07/14 23:33:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Error codes for Toolkit_Contacts_ContactUs + * + * Codes are mapped to textual messaged by errorMessage() method, + * if you add a new code be sure to add a new message for it to errorMessage() + * + * @see Toolkit_Contacts_ContactUs::errorMessage() + */ + +/** + * GLM Contact Us form + * + * This form handles rendering and processing the contact us form. + * Controls the email functionality of the form, whether the client + * has a contact DB to store contact records and how to insert/update + * submitted form values. + * + * @category Toolkit + * @package Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_VisitorGuide + extends Toolkit_Contacts_ContactUs +{ + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access protected + */ + protected $contactType = '4'; + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access protected + */ + protected $successMsg = ' + +
    + Thank you for requesting the Visitors guide. +
    '; + /** + * Email subject and

    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 + */ + public $subject = "Visitor Guide Form from website"; + + /** + * Class constructor + * + * @param object $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 tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @author Jamie Kahgee + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->email = VISITOR_GUIDE_EMAIL; + } + // {{{ configureConstants() + + /** + * Constant variables for the form + * + * These values won't get overridden by POST or GET vars + * + * @return void + * @access public + */ + public function configureConstants() + { + $constants = array( + 'user_agent' => $_SERVER['HTTP_USER_AGENT'], + 'remote_addr' => $_SERVER['REMOTE_ADDR'] + ); + $this->setupConstants($constants); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + if ($this->hasContactDB) { + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + } + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'lname', + 'display' => 'Last Name' + ); + if ($this->tableName == 'customer') { + $add1 = 'add1'; + $add2 = 'add2'; + } else { + $add1 = 'address'; + $add2 = 'address2'; + } + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => $add1, + 'display' => 'Address 1' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => $add2, + 'display' => 'Address 2' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'city', + 'display' => 'City' + ); + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax' + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'comments', + 'display' => 'Comments' + ); + if ($this->hasContactDB) { + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'mail_ok', + 'display' => 'I would like to receive Email Newsletters', + 'opts' => 'Yes, ', + 'val' => array(0, 1) + ); + if (defined("MEMBERS_DB") && MEMBERS_DB) { + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'members', + 'display' => 'I would like to receive information via e-mail from '.SITENAME.' Members', + 'opts' => 'Yes, ', + 'val' => array(0, 1) + ); + } + } + 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 + ); + } + } + $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 Form' + ); + + $this->setupElements($e); + } + + // }}} +} diff --git a/Toolkit/Contacts/assets/.keepme b/Toolkit/Contacts/assets/.keepme new file mode 100644 index 0000000..e69de29 diff --git a/Toolkit/Contacts/config.ini b/Toolkit/Contacts/config.ini new file mode 100644 index 0000000..850e902 --- /dev/null +++ b/Toolkit/Contacts/config.ini @@ -0,0 +1,15 @@ +; Contact Database configuration file +[conf] +; Table Name for records +table = "contact" +; Primary Key +primarykey = "id" +; Sequence +sequence = "contact_id_seq" + +[contact_types] +1 = "Web Contact" +;2 = "E-News" +;3 = "Travel Planner" +;4 = "Visitor Guide" +5 = "Meeting Request" diff --git a/Toolkit/Contacts/database-table-modifiers.sql b/Toolkit/Contacts/database-table-modifiers.sql new file mode 100644 index 0000000..b539d26 --- /dev/null +++ b/Toolkit/Contacts/database-table-modifiers.sql @@ -0,0 +1,46 @@ +CREATE SEQUENCE contact_id_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +ALTER TABLE contact ALTER COLUMN id SET DEFAULT nextval('contact_id_seq'::regclass); + +ALTER TABLE ONLY contact + ADD CONSTRAINT contact_pkey PRIMARY KEY (id); + +CREATE INDEX contact_create_date_indx ON contact USING btree (create_date); + +CREATE INDEX contact_email_indx ON contact USING btree (email); + +CREATE INDEX contact_fname_indx ON contact USING btree (fname); + +CREATE UNIQUE INDEX contact_id_indx ON contact USING btree (id); + +CREATE INDEX contact_lname_indx ON contact USING btree (lname); + +CREATE UNIQUE INDEX news_response_id_indx ON contact USING btree (id); + +CREATE UNIQUE INDEX query_db_id_indx ON contact USING btree (id); + +CREATE SEQUENCE contact_inq_id_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +ALTER TABLE contact_inq ALTER COLUMN id SET DEFAULT nextval('contact_inq_id_seq'::regclass); + +ALTER TABLE ONLY inq_group + ADD CONSTRAINT inq_group_pkey PRIMARY KEY (id); + +CREATE SEQUENCE inq_group_id_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +ALTER TABLE inq_group ALTER COLUMN id SET DEFAULT nextval('inq_group_id_seq'::regclass); + +ALTER TABLE ONLY inq_group + ADD CONSTRAINT inq_group_pkey PRIMARY KEY (id); diff --git a/Toolkit/Contacts/database-tables.sql b/Toolkit/Contacts/database-tables.sql new file mode 100644 index 0000000..1b71879 --- /dev/null +++ b/Toolkit/Contacts/database-tables.sql @@ -0,0 +1,45 @@ +CREATE TABLE contact ( + id integer NOT NULL, + create_date date DEFAULT CURRENT_DATE, + fname text, + lname text, + company text, + address text, + address2 text, + city text, + state text, + zip text, + country text, + phone text, + fax text, + email text, + user_agent text, + remote_addr text, + interest text, + mail_ok boolean DEFAULT false, + visitorguide boolean DEFAULT false, + uidpdf text, + visitorguide_download boolean DEFAULT false, + email_verified boolean DEFAULT true, + contact_type text, + discover text, + member_ok boolean DEFAULT false, + staff boolean DEFAULT false, + comments text, + password text, + verify_password text +); + +CREATE TABLE inq_group ( + id integer NOT NULL, + name text +); + +CREATE TABLE contact_inq ( + id integer NOT NULL, + header text, + pos integer, + description text, + image text, + groupid integer +); diff --git a/Toolkit/Contacts/templates/brochurePage.html b/Toolkit/Contacts/templates/brochurePage.html new file mode 100755 index 0000000..0ceb81b --- /dev/null +++ b/Toolkit/Contacts/templates/brochurePage.html @@ -0,0 +1,9 @@ + +
    DOWNLOAD: +

    We will email you a link to the PDF version of the {brochure}.

    +
    +
    + {pdfForm:h} +
    +

    ORDER BY MAIL:

    +{contactForm:h} diff --git a/Toolkit/Contacts/templates/currentTables/Element.tpl b/Toolkit/Contacts/templates/currentTables/Element.tpl new file mode 100755 index 0000000..595457b --- /dev/null +++ b/Toolkit/Contacts/templates/currentTables/Element.tpl @@ -0,0 +1,14 @@ + + + + * + + + + + +
    {error}
    + + {element} + + diff --git a/Toolkit/Contacts/templates/currentTables/Form.tpl b/Toolkit/Contacts/templates/currentTables/Form.tpl new file mode 100755 index 0000000..8875737 --- /dev/null +++ b/Toolkit/Contacts/templates/currentTables/Form.tpl @@ -0,0 +1,8 @@ +
    + + {hidden} + + {content} +
    + +
    \ No newline at end of file diff --git a/Toolkit/Contacts/templates/currentTables/Group.tpl b/Toolkit/Contacts/templates/currentTables/Group.tpl new file mode 100755 index 0000000..cdd24cf --- /dev/null +++ b/Toolkit/Contacts/templates/currentTables/Group.tpl @@ -0,0 +1,5 @@ + + + {content} + +
    diff --git a/Toolkit/Contacts/templates/currentTables/GroupElement.tpl b/Toolkit/Contacts/templates/currentTables/GroupElement.tpl new file mode 100755 index 0000000..1a4ba27 --- /dev/null +++ b/Toolkit/Contacts/templates/currentTables/GroupElement.tpl @@ -0,0 +1,9 @@ + + + {element} + + * + + {label} + + diff --git a/Toolkit/Contacts/templates/currentTables/Header.tpl b/Toolkit/Contacts/templates/currentTables/Header.tpl new file mode 100755 index 0000000..64ac244 --- /dev/null +++ b/Toolkit/Contacts/templates/currentTables/Header.tpl @@ -0,0 +1,5 @@ + + + {header} + + diff --git a/Toolkit/Contacts/templates/currentTables/RequiredNote.tpl b/Toolkit/Contacts/templates/currentTables/RequiredNote.tpl new file mode 100755 index 0000000..dad5d0b --- /dev/null +++ b/Toolkit/Contacts/templates/currentTables/RequiredNote.tpl @@ -0,0 +1 @@ +* = Required Fields diff --git a/Toolkit/Contacts/templates/direct-list.html b/Toolkit/Contacts/templates/direct-list.html new file mode 100755 index 0000000..eefc842 --- /dev/null +++ b/Toolkit/Contacts/templates/direct-list.html @@ -0,0 +1,29 @@ +

    Your Trip Planner List

    +

    Below is the list of businesses you have added to your Trip Planner. The form below will be sent to each individual business listing that has an email address listed with their business listing. For those businesses with no email address, we have included their phone numbers for you to call directly and request additional information.

    +

    Request Information by Phone from:

    +

    These business listings have no current email address on file. To receive additional information please call the phone numbers listed next to each business name.

    + + + + {foreach:memberDirectNoEmail,member} + + + + + + {end:} +
    Name + Phone +   +
    {member[memberName]}{member[memberPhone]}Remove
    +

    Request Information by Email from:

    +

    This list of businesses will receive the following information form directly to their email account.

    + + {foreach:memberDirect,member} + + + + + {end:} +
    {member[memberName]}Remove
    +

    Plan Your Trip Information Request Form

    diff --git a/Toolkit/Contacts/templates/emailOwner.tpl b/Toolkit/Contacts/templates/emailOwner.tpl new file mode 100755 index 0000000..e574342 --- /dev/null +++ b/Toolkit/Contacts/templates/emailOwner.tpl @@ -0,0 +1,61 @@ + + + + + {title:h} + + + +

    + + {subject:h} + +

    +

    + + From {fname:h} {lname:h} + +

    + + + + + + + + +
    + + {foreach:formData,v} + + + {if:v[nowrap]} + + {else:} + + {end:} + + {end:} +
    + + {v[label]:h} + + + {v[element]:h} + + {v[element]:h} +
    +
    + + + + +
    + + To ensure the delivery of these e-mails to your inbox, please add {email_from:h} to your e-mail Address Book or Safe List. + +
    +
    + + + diff --git a/Toolkit/Contacts/templates/friendEmail.html b/Toolkit/Contacts/templates/friendEmail.html new file mode 100644 index 0000000..358ded6 --- /dev/null +++ b/Toolkit/Contacts/templates/friendEmail.html @@ -0,0 +1,49 @@ + + + + +

    Dear {fname}

    +

    Your friend {yname} has been to demo.gaslightmedia.com, and thought you might be interested in it.

    +

    Message here.

    +
     

    + + diff --git a/Toolkit/Contacts/templates/pdfDownloadEmail.html b/Toolkit/Contacts/templates/pdfDownloadEmail.html new file mode 100755 index 0000000..6f01198 --- /dev/null +++ b/Toolkit/Contacts/templates/pdfDownloadEmail.html @@ -0,0 +1,19 @@ + + + + + {title:h} + + + + {subject:h} +

    Thank you for requesting the {pdfName} Link. Here is the link to the Adobe PDF version: +

    +

    Brochure ({pdfFileSize})

    +

    Thank you for your interest in {client_info[name]:h}'!

    +

    Sincerely,

    +

    {client_info[name]:h}

    +

    {client_info[url]:h}

    + + + diff --git a/Toolkit/DataGridBuilder.php b/Toolkit/DataGridBuilder.php new file mode 100644 index 0000000..83218de --- /dev/null +++ b/Toolkit/DataGridBuilder.php @@ -0,0 +1,285 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ + +/** + * Create Datagrids for displaying data + * + * This abstract class handles all the base functionality of creating + * handeling all the details associated w/ a regular dataGrid. + * 1. Creation + * 2. Sorting (via column headers or sortform) + * 3. Pagenation + * + * @category Structures + * @package Toolkit_DataGridBuilder + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @Release CVS: $Id: DataGridBuilder.php,v 1.13 2009/09/16 00:07:44 jamie Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit_SortForm, Structures_DataGrid + */ +abstract class Toolkit_DataGridBuilder extends Structures_DataGrid +{ + // {{{ properties + + /** + * Options to pass to DataGrid + * + * @var array + * @access protected + */ + protected $options; + + /** + * Rendering options for DataGrid + * + * @var array + * @access protected + */ + protected $rendererOptions = array( + 'sortIconASC' => '⇑', + 'sortIconDESC' => '⇓', + 'evenRowAttributes' => 'class="even"', + 'oddRowAttributes' => 'class="odd"', + 'sortingResetsPaging' => false, + ); + + /** + * Rendering options for DataGrid paging element + * + * @var array + * @access protected + */ + protected $pagerOptions = array( + 'nextImg' => 'Next', + 'prevImg' => 'Previous', + 'separator' => '', + 'spacesBeforeSeparator' => 0, + 'spacesAfterSeparator' => 0, + 'containerClass' => 'paging', + ); + + /** + * 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'; + + // }}} + // {{{ __construct() + + /** + * DataGrid constructor + * + * Instantiates a DataGrid and sets up when to make the grid sortable + * + * @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. + * + * @return void + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + parent::__construct($limit, $page, $rendererType); + + $this->options = array('dbc' => $pdo); + if (!is_null($limit)) { + $this->sortableAfter = $limit; + } + } + + // }}} + + // {{{ configureColumns() + + /** + * configure retrieved columns + * + * Tells the DataGrid how to render the retrieved columns + * + * @return void + * @access protected + */ + abstract protected function configureColumns(); + + // }}} + + // {{{ setNoRecordMessage() + + /** + * The message to display if no results were found from the sql query + * + * @param string $msg No result message. + * + * @return void + * @access public + */ + public function setNoRecordMessage($msg) + { + $this->noRecMessage = $msg; + } + + // }}} + // {{{ setQuery() + + /** + * Sets the sql query to use in the DataGrid to get the results + * + * @param string $sql The SQL query + * + * @return void + * @access public + */ + public function setQuery($sql) + { + $this->sql = $sql; + } + + // }}} + // {{{ show() + + /** + * Displays the DataGrid results + * + * @return void + * @access public + */ + public function show() + { + echo $this->toHTML(); + } + + // }}} + + // {{{ toHTML() + + /** + * returns a HTML table of the datagrid + * + * @return string + * @access public + */ + public function toHTML() + { + $this->configureColumns(); + + try { + $bind = $this->bind($this->sql, $this->options, 'PDO'); + } 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); + $renderer =& $this->getRenderer(); + // Allows us to turn off the id name for the table, + // when we subclass this class out. + if ($this->tableId) { + $renderer->setTableAttribute('id', $this->tableId); + } + // Allows us to turn off the class name for the table, + // when we subclass this class out. + if ($this->tableClass) { + $renderer->setTableAttribute('class', $this->tableClass); + } + $gridBody = $this->getOutput(); + + if (PEAR::isError($gridBody)) { + return Toolkit_Common::handleError($gridBody); + } + + $gridPager = $this->getOutput( + DATAGRID_RENDER_PAGER, + array('pagerOptions' => $this->pagerOptions) + ); + if (PEAR::isError($gridPager)) { + return Toolkit_Common::handleError($gridPager); + } + + if ($recCount > $this->sortableAfter) { + $form = new Toolkit_SortForm($this->sortFormId); + $options = array('directionStyle' => 'radio'); + $this->fill($form, $options, DATAGRID_RENDER_SORTFORM); + // Datagrid never ads a submit button. + $form->addElement('submit', null, 'Submit'); + $gridSorter = $form->toHTML(); + } + + return $gridPager . $gridSorter . $gridBody . $gridPager; + } else { + return "

    {$this->noRecMessage}

    "; + } + } + + // }}} +} +?> diff --git a/Toolkit/Database.php b/Toolkit/Database.php new file mode 100644 index 0000000..f9deb36 --- /dev/null +++ b/Toolkit/Database.php @@ -0,0 +1,262 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Database.php,v 1.8 2010/05/25 14:09:12 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Database Singleton class + * + * Used to create a one and only one instance of a databsae PDO object. + * Only uses the PHP PDO. Later additions may be worked on the + * use master/slave database setups. Hopefully! + * + * @category Database + * @package Database + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Database +{ + // {{{ properties + + /** + * Master database handler object + * + * Handles insert/update/delete requests + * + * @var PDO + * @access private + */ + private $_masterDbh; + + /** + * Slave database handler object + * + * Handles read requests + * + * @var PDO + * @access private + */ + private $_slaveDbh; + + /** + * Class instance + * + * @var Toolkit_Database + * @access private + */ + private static $_instance; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * Make the database handler connection for the class + * + * @param boolean $master Whether Use connection for master of slave + * + * @access private + */ + private function __construct($master) + { + try { + $dsn = 'pgsql:' . CONN_STR; + // Keep the fetch mode set to FETCH_BOTH, we use + // associative arrays throughout our apps, but some PEAR lib + // apps require numerical indicies to work correctly. + // i.e. (DataGrids working w/ PDO's) + $driverOptions = array( + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_BOTH, + ); + $this->_masterDbh = new PDO($dsn, null, null, $driverOptions); + $this->_masterDbh->setAttribute( + PDO::ATTR_ERRMODE, + PDO::ERRMODE_EXCEPTION + ); + $this->_setDateStyle($this->_masterDbh); + $this->_setSearchPath($this->_masterDbh); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ __clone() + + /** + * Clone magic method + * + * Don't allow cloning of instances of this class + * which could potentially duplicate system resources + * and make extra DB connections + * + * @return void + * @access private + */ + private function __clone() + { + // Do nothing so we don't create duplicate resources + } + + // {{{ _setDateStyle() + + /** + * Set the default date style + * @param PDO $dbh + */ + private function _setDateStyle(PDO &$dbh) + { + $dbh->query("SET DATESTYLE TO 'SQL, US'"); + } + + // }}} + // {{{ _setSearchPath() + + /** + * Set the search path for schemas + * @param PDO $dbh + */ + private function _setSearchPath(PDO &$dbh) + { + // Add schemas to search path. + $sql = " + SELECT set_config( + 'search_path', + current_setting('search_path') || ', ' || :schema, + false + )"; + + $stmt = $dbh->prepare($sql); + $stmt->bindValue(':schema', 'toolbox', PDO::PARAM_STR); + $stmt->execute(); + + $stmt->bindValue(':schema', 'ckimages', PDO::PARAM_STR); + $stmt->execute(); + + if (defined('RETAIL_SHOP') && RETAIL_SHOP) { + $stmt->bindValue(':schema', 'retail_shop', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('GLM_BLOCKS') && GLM_BLOCKS) { + // define seasonator search path + $stmt->bindValue(':schema', 'blocks', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('CONTACT_DB') && CONTACT_DB) { + // define banner search path + $stmt->bindValue(':schema', 'contacts', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('BANNERS') && BANNERS) { + // define banner search path + $stmt->bindValue(':schema', 'banners', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('ROTATING_IMAGES') && ROTATING_IMAGES) { + // define rotating images search path + $stmt->bindValue(':schema', 'rotatingImages', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) { + // define phot gallery search path + $stmt->bindValue(':schema', 'photos', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('POSTCARD_DB') && POSTCARD_DB) { + // define phot gallery search path + $stmt->bindValue(':schema', 'postcards', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('EVENT_DB') && EVENT_DB) { + // define members search path + $stmt->bindValue(':schema', 'events', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('MEMBERS_DB') && MEMBERS_DB) { + // define members search path + $stmt->bindValue(':schema', 'members', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('COUPONS') && COUPONS) { + // define coupon search path + $stmt->bindValue(':schema', 'coupons', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('PRESS_DB') && PRESS_DB) { + // define press/archive search path + $stmt->bindValue(':schema', 'press', PDO::PARAM_STR); + $stmt->execute(); + } + if (defined('EMPLOYMENT') && EMPLOYMENT) { + // define press/archive search path + $stmt->bindValue(':schema', 'employment', PDO::PARAM_STR); + $stmt->execute(); + } + if (defined('VIDEOS') && VIDEOS) { + // define videos search path + $stmt->bindValue(':schema', 'videos', PDO::PARAM_STR); + $stmt->execute(); + } + if (defined('EVENT_MANAGEMENT') && EVENT_MANAGEMENT) { + // define event management search path + $stmt->bindValue(':schema', 'reservations', PDO::PARAM_STR); + $stmt->execute(); + } + } + + // }}} + + // {{{ getInstance() + + /** + * Get an instance of this class + * + * If this object hasn't been instantiated once already + * then create the object and return the dbh. + * Otherwise just return the already instantiated dbh. + * + * @param boolean $master Whether Use connection for master or slave + * + * @return PDO $_instance database handler instance + * @access public + * @static + */ + public static function getInstance($master = true) + { + settype($master, 'bool'); + + if (!(self::$_instance instanceof self)) { + self::$_instance = new self($master); + } + + return $master + ? self::$_instance->_masterDbh + : self::$_instance->_slaveDbh; + } + + // }}} +} diff --git a/Toolkit/FileServer/AdapterAbstract.php b/Toolkit/FileServer/AdapterAbstract.php new file mode 100644 index 0000000..956483f --- /dev/null +++ b/Toolkit/FileServer/AdapterAbstract.php @@ -0,0 +1,405 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: AdapterAbstract.php,v 1.6 2010/06/04 11:33:54 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + + +/** + * Validation Secret + */ +define('IS_VALIDATE_SECRET', 'Glm0IS1secreT'); + +/** + * URL to file server, this is dynamic based on the server + * so can be setup for any sandbox + */ +define('IS_SUBMIT_URL', FILE_SERVER_URL . 'submit.phtml'); + +/** + * Adapter class for linking to the file server + * + * @category Toolkit + * @package FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +abstract class Toolkit_FileServer_AdapterAbstract +{ + // {{{ properties + + /** + * ID of owner that was setup in the file server + * + * This is defined via the file server web interface + * @var string + * @access protected + */ + protected $ownerID; + + /** + * Owners password that was setup for them + * + * This is defined via the file server web interface + * @var string + * @access protected + */ + protected $ownerPW; + + /** + * XML to send to the file server + * @var unknown + * @access protected + */ + protected $xml; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param string $owner File Server owner + * @param string $pword File Server owner password + */ + public function __construct($owner = IS_OWNER_ID, $pword = IS_OWNER_PW) + { + $this->ownerID = $owner; + $this->ownerPW = $pword; + } + + // }}} + + // {{{ buildFileServerXML() + + /** + * buildFileServerXML + * + * Create the xml for the FileServerRequest + * + * @param string $fName File name to upload or delete + * @param string $type Upload, Delete or URL + * + * @return string xml content + * @access protected + */ + protected function buildFileServerXML($fName, $type) + { + $xml = new DOMDocument('1.0'); + $xml->formatOutput = true; + + $fileServerRequest = $xml->createElement('FileServerRequest'); + $fileServerRequest->setAttribute('version', '1.0'); + + // access request + $accessRequest = $xml->createElement('AccessRequest'); + $owner = $xml->createElement('Owner'); + $ownerID = $xml->createElement('OwnerID', $this->ownerID); + $ownerPW = $xml->createElement('OwnerPW', $this->ownerPW); + + $owner->appendChild($ownerID); + $owner->appendChild($ownerPW); + + $accessRequest->appendChild($owner); + + $fileServerRequest->appendChild($accessRequest); + + $file = $this->getFileElement($xml, $type, $fName); + + $fileServerRequest->appendChild($file); + $validStr = md5($this->ownerID . $this->ownerPW . IS_VALIDATE_SECRET); + + $validation = $xml->createElement('Validation', $validStr); + $fileServerRequest->appendChild($validation); + $xml->appendChild($fileServerRequest); + + return $xml->saveXML($xml); + } + + // }}} + + // {{{ delete() + + /** + * Delete a file from the file server + * + * @param string $name File name + * + * @return string file name + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function delete($name) + { + // don't do anything if on development server + if (defined('DEVELOPMENT') && DEVELOPMENT == true) { + return true; + } + $ch = curl_init(); + + $fileData = array( + 'request' => $this->buildFileServerXML($name, 'Delete') + ); + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument; + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + return $message; + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + + // }}} + + // {{{ getFileElement() + + + /** + * Gets the file element used in the XML sent to the file server + * + * @param DOMDocument $xml DOM object used to build the xml string + * @param string $type Type of manipulation (Upload, URL, Delete) + * @param string $fName File name + * + * @return DOMElement $file File xml element + * @access protected + */ + abstract protected function getFileElement( + DOMDocument $xml, + $type, + $fName + ); + + // }}} + // {{{ getErrorMessage() + + /** + * Gets an appropriate error message for file upload errors + * + * @param integer Error code + * + * @return string Error message + * @access protected + */ + protected function getErrorMessage($code) + { + switch ($code) { + case UPLOAD_ERR_INI_SIZE : + $message = 'The Uploaded file exceeds the upload max filesize directive in php.ini'; + break; + + case UPLOAD_ERR_FORM_SIZE : + $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; + break; + + case UPLOAD_ERR_PARTIAL : + $message = 'The uploaded file was only partially uploaded'; + break; + + case UPLOAD_ERR_NO_FILE : + $message = 'No file was uploaded'; + break; + + case UPLOAD_ERR_NO_TMP_DIR : + $message = 'Missing a temporary folder'; + break; + + case UPLOAD_ERR_CANT_WRITE : + $message = 'Failed to write file to disk'; + break; + + case UPLOAD_ERR_EXTENSION : + $message = 'A PHP extension stopped the file upload'; + break; + + default : + $message = 'Unknown error uploading file'; + break; + } + + return $message; + } + + // }}} + + // {{{ upload() + + /** + * Upload a file to the File Server + * + * @param string $name $_FILES index key that holds the file data + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function upload($name) + { + $fileType = null; + if (preg_match('/^http/', $name)) { + $fileType = 'URL'; + } elseif (isset($_FILES[$name]) && is_array($_FILES[$name])) { + $fileType = 'Upload'; + } + + if ($_FILES[$name]['error'] != 0) { + $message = $this->getErrorMessage($_FILES[$name]['error']); + throw new Toolkit_FileServer_Exception( + $message, + $_FILES[$name]['error'] + ); + } + + if (is_null($fileType)) { + return false; + } else { + $request = $this->buildFileServerXML($name, $fileType); + + $ch = curl_init(); + if ($fileType == 'URL') { + $fileData = array( + 'request' => $request + ); + } else { + $fileData = array( + 'request' => $request, + 'file_upload' => "@{$_FILES[$name]['tmp_name']}", + 'file_upload_name' => $_FILES[$name]['name'] + ); + } + + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument(); + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $storedName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $storedSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $mediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + $extension = end(explode('.', $storedName)); + return array( + 'name' => $storedName, + 'size' => $storedSize, + 'type' => $mediaType, + 'extension' => $extension, + ); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + } + + // }}} + + // {{{ xmlPathContent() + + /** + * Extract a XML node value + * + * @param DOMDocument $dom DOM object holding the XML + * @param string $content Node name to extract content from + * + * @return mixed Node value on success, false if can't find the value + * @access protected + */ + protected function xmlPathContent(DOMDocument $dom, $content) + { + $xPath = new DOMXPath($dom); + $nodeList = $xPath->query($content); + if ($nodeList->length > 0) { + $node = $nodeList->item(0); + return $node->nodeValue; + } + + return false; + } + + // }}} +} diff --git a/Toolkit/FileServer/Exception.php b/Toolkit/FileServer/Exception.php new file mode 100644 index 0000000..8739c0f --- /dev/null +++ b/Toolkit/FileServer/Exception.php @@ -0,0 +1,5 @@ + diff --git a/Toolkit/FileServer/FileAdapter.php b/Toolkit/FileServer/FileAdapter.php new file mode 100644 index 0000000..a83ef98 --- /dev/null +++ b/Toolkit/FileServer/FileAdapter.php @@ -0,0 +1,101 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: FileAdapter.php,v 1.4 2010/05/25 14:02:28 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * File Adapter + * + * Used for linking to the file server for file uploading, storage and deletion + * + * @category Toolkit + * @package FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_FileServer_FileAdapter extends Toolkit_FileServer_AdapterAbstract +{ + // {{{ getFileElement() + + /** + * Creates the file element for the XML string + * + * @param DOMDocument $xml XML object used to build the string + * @param string $type Type of action to take on the file (Upload, Delete) + * @param string $fName file name to delete + * + * @return DOMElement $file File xml element + * @access protected + * @throws RuntimeException + */ + protected function getFileElement(DOMDocument $xml, $type, $fName) + { + $file = $xml->createElement('File'); + + switch ($type) { + case 'Upload' : + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'Submit'); + $fieldName = $xml->createElement('FieldName', 'file_upload'); + + $fileName = filter_var($_FILES[$fName]['name'], FILTER_SANITIZE_STRING); + $nameParts = explode('.', $fileName); + $extension = end($nameParts); + $fieldName = $xml->createElement('Extension', end($nameParts)); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($fieldName); + break; + + case 'URL': + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'URL'); + $src = $xml->createElement('Src', $fName); + + $nameParts = explode('.', $fName); + $extension = end($nameParts); + $fieldName = $xml->createElement('Extension', end($nameParts)); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($src); + $file->appendChild($fieldName); + break; + + case 'Delete' : + $action = $xml->createElement('FileAction', 'Delete'); + $file->appendChild($action); + + $fileName = $xml->createElement('FileName', $fName); + $file->appendChild($fileName); + break; + + default : + throw new RuntimeException("Invalid XML type - `$type`."); + break; + } + + return $file; + } + + // }}} +} diff --git a/Toolkit/FileServer/ImageAdapter.php b/Toolkit/FileServer/ImageAdapter.php new file mode 100644 index 0000000..85b7951 --- /dev/null +++ b/Toolkit/FileServer/ImageAdapter.php @@ -0,0 +1,248 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: ImageAdapter.php,v 1.5 2010/06/04 11:34:31 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Image Adapter + * + * Used for linking to the file server for image uploading, storage and deletion + * + * @category Toolkit + * @package FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_FileServer_ImageAdapter extends Toolkit_FileServer_AdapterAbstract +{ + // {{{ getAllowedMimeTypes() + + /** + * Get the mime types that are allowed to be uploaded + * + * @return array allowed mime types + */ + public function getAllowedMimeTypes() + { + return array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/gif', + 'image/png', + ); + } + + // }}} + // {{{ getFileElement() + + /** + * Creates the file element for the XML string + * + * @param DOMDocument $xml XML object used to build the string + * @param string $type Type of action to take on the file (Upload, Delete) + * @param string $fName file name to delete + * + * @return DOMElement $file File xml element + * @access protected + * @throws RuntimeException + */ + protected function getFileElement(DOMDocument $xml, $type, $fName) + { + $file = $xml->createElement('File'); + + switch ($type) { + case 'Upload' : + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'Submit'); + $fieldName = $xml->createElement('FieldName', 'file_upload'); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($fieldName); + break; + + case 'URL': + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'URL'); + $src = $xml->createElement('Src', $fName); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($src); + break; + + case 'Delete': + $action = $xml->createElement('FileAction', 'Delete'); + $file->appendChild($action); + + $fileName = $xml->createElement('FileName', $fName); + $file->appendChild($fileName); + break; + + default : + throw new RuntimeException("Invalid XML type - `$type`."); + break; + } + + return $file; + } + + // }}} + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws Exception + */ + public function getImageSize($image) + { + $options = array('allowed_schemes' => array('http','https')); + if (!Validate::uri($image, $options)) { + throw new Exception('Invalid URI for the image'); + } + + $ch = curl_init(); + $curlOptions = array( + CURLOPT_URL => "{$image}/info", + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + if (!@simplexml_load_string($response)) { + $logger = Toolkit_Logger::getLogger(); + $logger->warning("$response - $image"); + } + + $wPattern = '/(.*)<\/width>/'; + preg_match($wPattern, $response, $matches); + $width = $matches[1]; + $hPattern = '/(.*)<\/height>/'; + preg_match($hPattern, $response, $matches); + $height = $matches[1]; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + // {{{ uploadImageFile() + + /** + * Upload a file to the File Server + * + * @param string $fname full path to image file + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function uploadImageFile($fname) + { + if (!file_exists($fname)) { + throw new RuntimeException("could not find file `$fname`"); + } + + $request = $this->buildFileServerXML(basename($fname), 'Upload'); + + $ch = curl_init(); + $fileData = array( + 'request' => $request, + 'file_upload' => "@$fname", + 'file_upload_name' => basename($fname) + ); + + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument(); + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $storedName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $storedSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $mediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + return array( + 'name' => $storedName, + 'size' => $storedSize, + 'type' => $mediaType, + ); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + + // }}} +} +?> diff --git a/Toolkit/FileServer/Mock/ImageAdapter.php b/Toolkit/FileServer/Mock/ImageAdapter.php new file mode 100644 index 0000000..ed9307d --- /dev/null +++ b/Toolkit/FileServer/Mock/ImageAdapter.php @@ -0,0 +1,125 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: ImageAdapter.php,v 1.1 2010/07/29 16:30:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Mock Image Adapter + * + * Mocks uploading and deleting images from the image server + * This script prevents unneeded resources from being uploaded + * or deleted from the file server + * + * @category FileServer + * @package Toolkit_FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_FileServer_Mock_ImageAdapter + extends Toolkit_FileServer_ImageAdapter +{ + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws Exception + */ + public function getImageSize($image) + { + $width = $height = 1; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + // {{{ uploadImageFile() + + /** + * Upload a file to the File Server + * + * @param string $fname full path to image file + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function uploadImageFile($fname) + { + return array( + 'name' => 'is00-mock-image.jpg', + 'size' => 100, + 'type' => 'image/jpeg', + ); + } + + // }}} + // {{{ upload() + + /** + * Upload a file to the File Server + * + * @param string $name $_FILES index key that holds the file data + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function upload($name) + { + return array( + 'name' => 'is00-mock-image.jpg', + 'size' => 100, + 'type' => 'image/jpeg', + ); + } + + // }}} + // {{{ delete() + + /** + * Delete a file from the file server + * + * @param string $name File name + * + * @return string file name + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function delete($name) + { + return true; + } + + // }}} +} +?> diff --git a/Toolkit/FlexyDataGridBuilder.php b/Toolkit/FlexyDataGridBuilder.php new file mode 100644 index 0000000..793b864 --- /dev/null +++ b/Toolkit/FlexyDataGridBuilder.php @@ -0,0 +1,223 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: FlexyDataGridBuilder.php,v 1.14 2010/07/25 17:08:39 jamie Exp $ + * @link <> + */ + +/** + * Create Flexy templating Datagrids for displaying data + * + * This abstract class handles all the base functionality of creating + * handeling all the details associated w/ a Flexy template datagrid + * 1. Creation + * 2. Sorting (via column headers or sortform) + * 3. Pagenation + * + * @category Toolkit + * @package FlexyDataGridBuilder + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com/Gaslightmedia Gaslightmedia + * @link http://pear.php.net/package/Structures_DataGrid/docs + * @see Structures_DataGrid_Renderer_Flexy, HTML_Template_Flexy + */ +abstract class Toolkit_FlexyDataGridBuilder extends Toolkit_DataGridBuilder +{ + // {{{ properties + + /** + * Name of the table which we will be dealing with + * + * @var string + * @access protected + */ + protected $tableName; + + /** + * The name of the template that renders this datagrid + * + * @var string + * @access protected + */ + protected $template; + + /** + * Output an object as $t to the template + * + * converts array keys to objects usable in a template form. + * + * + * $this->ctrlObj['url'] = BASE_URL; + * + * + * + * {row[img]} src= + * + * + * @var array + * @access protected + */ + protected $ctrlObj = array(); + + /** + * Rendering options for DataGrid + * + * @var array + * @access protected + */ + protected $rendererOptions = array( + 'sortIconASC' => '⇑', + 'sortIconDESC' => '⇓', + 'sortingResetsPaging' => false, + ); + + /** + * The HTML id of the DataGrid + * + * @var string + * @access protected + */ + protected $gridId = 'dataGrid'; + + /** + * The HTML class of the DataGrid + * + * @var string + * @access protected + */ + protected $gridClass = 'dataGrid'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * Builds the DataGrid class. + * + * @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. + * + * @return void + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + $this->dbh = $pdo; + if (ctype_digit($_GET['setPerPage'])) { + $limit = $_GET['setPerPage']; + } + + parent::__construct($pdo, $limit, $page, $rendererType); + + // If all records show on one page, then hide sort form. + if (!is_null($limit)) { + $this->sortableAfter = $limit; + } + } + + // }}} + + // {{{ show() + + /** + * Displays the DataGrid results + * + * @param Structures_DataGrid_Renderer_Flexy $renderer Rendering engine used to render DG + * + * @return void + * @access public + */ + public function show(Structures_DataGrid_Renderer_Flexy $renderer) + { + echo $this->toHtml($renderer); + } + + // }}} + + // {{{ toHtml() + + /** + * Returns the DataGrid + * + * @param Structures_DataGrid_Renderer_Flexy $renderer Rendering engine used to render DG + * @param string $template Template to use + * + * @return string html templated datagrid results + * @access public + */ + public function toHtml( + Structures_DataGrid_Renderer_Flexy $renderer, + $template = null + ) { + $this->configureColumns(); + + try { + $bind = $this->bind($this->sql, $this->options, 'PDO'); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + if (PEAR::isError($bind)) { + return Toolkit_Common::handleError($bind); + } + + if (method_exists($this, 'setControlObject')) { + $this->setControlObject(); + foreach ($this->ctrlObj as $k => $v) { + $renderer->$k = $v; + } + } + + $renderer->setOptions($this->rendererOptions); + $renderer->setOptions(array('pagerOptions' => $this->pagerOptions)); + + $this->attachRenderer($renderer); + $tEngine = $renderer->getContainer(); + + $pathToTemplate = $tEngine->options['templateDir'][0]; + + if ( !is_null($template) + && file_exists("$pathToTemplate/$template") + ) { + $tEngine->compile($template); + } elseif (isset($this->template) + && file_exists($pathToTemplate . $this->template) + ) { + $tEngine->compile($this->template); + } else { + throw new RuntimeException('Template not available'); + } + + // Get the entire datagrid body. + $gridBody = $this->getOutput(); + if (PEAR::isError($gridBody)) { + return Tolkit_Common::handleError($gridBody); + } + + return $gridSorter . $gridBody; + } + + // }}} +} +?> diff --git a/Toolkit/Form.php b/Toolkit/Form.php new file mode 100644 index 0000000..c14a16b --- /dev/null +++ b/Toolkit/Form.php @@ -0,0 +1,143 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Form.php,v 1.6 2009/08/31 17:43:48 jamie Exp $ + * @link http://demo.gaslightmedia.com/ + */ + +/** + * Minimum form object method definitions + * + * Each form must at least define some elements and setup the rules for + * that form. They must also create a method which handless extracting + * the form object into an html string suitable to be displayed onto a + * page. + * + * @category Toolkit + * @package Form + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com/ + */ +interface Toolkit_Form +{ + // {{{ configureElements() + + /** + * Defines all elements to be used in a form + * + * Creates an array of elements and passes them off to the setupElements + * function wich adds each element to the form object. + * + * + * public function configureElements() + * { + * $e = array(); + * + * $e[] = array( + * 'type' => 'text', + * 'req' => false + * 'name' => 'text_field', + * 'display' => 'Text Label', + * ); + * $e[] = array( + * 'type' => 'checkbox', + * 'req' => false + * 'name' => 'checkbox_field', + * 'display' => 'Checkbox Label', + * ); + * + * // ... More Element Definitions + * + * $this->setupElements($e); + * } + * + * + * @access public + * @return void + */ + //public function configureElements(); + + // }}} + // {{{ configureForm() + + /** + * Calls all the configuration methods to configure a form for use + * + * @access public + * @return void + */ + //public function configureForm(); + + // }}} + // {{{ configureRules() + + /** + * Defines all element rules to be used for validation in the form + * + * At the bare minimum, this function needs to be called to setup the + * form rules, even if no extra rules are defined. Because it still + * creates all the required rules that are defined w/ each element. + * + * + * public function configureRules() + * { + * $r = array(); + * + * $r[] = array( + * 'element' => 'text_field', + * 'message' => 'ERROR: 10 characters max!', + * 'type' => 'maxlength', + * 'format' => 10, + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false, + * ); + * $r[] = array( + * 'element' => 'text_field', + * 'message' => 'ERROR: Numric characters only!', + * 'type' => 'numeric', + * 'format' => null, + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false, + * ); + * + * // ... More Rule Definitions + * + * $this->setupRules($r); + * } + * + * + * @access public + * @return void + */ + public function configureRules(); + + // }}} + // {{{ toHtml() + + /** + * Get an html string that contains the form + * + * Check if the form needs to be validated (ie. it was submitted) + * Check if submitted data needs to be processed + * + * @access public + * @return string an html string that contains the entire form + */ + public function toHtml(); + + // }}} +} diff --git a/Toolkit/FormBuilder.php b/Toolkit/FormBuilder.php new file mode 100644 index 0000000..2265a77 --- /dev/null +++ b/Toolkit/FormBuilder.php @@ -0,0 +1,1263 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: FormBuilder.php,v 1.48 2010/08/05 14:19:47 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Allow the inclusion of the Element Grid plugin for QuickForms + */ +require_once 'HTML/QuickForm/ElementGrid.php'; + +/** + * Handle QuickForm CAPTCHA's + */ +require_once 'HTML/QuickForm/CAPTCHA/Image.php'; + +/** + * Require PEAR QuickForm class + */ +require_once 'HTML/QuickForm.php'; + +require_once 'HTML/QuickForm/Rule/Zip.php'; +require_once 'HTML/QuickForm/Rule/Phone.php'; +require_once 'HTML/QuickForm/Rule/Banwords.php'; +require_once 'HTML/QuickForm/Rule/State.php'; + +/** + * Base functionality for creating HTML_Quickforms + * + * @category Toolkit + * @package FormBuilder + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +abstract class Toolkit_FormBuilder extends HTML_QuickForm +{ + // {{{ properties + + /** + * Holds if the form has been validated + * + * once the form is validated, store the result of the validation + * in this variable. That way, if multiple validations are attempted + * we don't have to reprocess all the data + * + * @var boolean + * @access protected + */ + protected $validated = false; + + /** + * Global form captcha question element + * + * @var object + * @access protected + */ + protected $captchaQuestion; + + /** + * Global form captcha answer from user + * + * @var object + * @access protected + */ + protected $captchaAnswer; + + /** + * Form submitted data used when emailing form results + * + * @var array + * @access protected + */ + protected $formData = array(); + + /** + * Automatically create validation rules for any date elements + * + * This will only work if the date element is in m-d-Y format + * + * @var boolean + * @access protected + */ + protected $autoValidateDateElements = true; + + /** + * How do we want to validate the form + * + * Possible options are [server, client] + * + * @var string + * @access protected + */ + protected $validationType = 'server'; + + /** + * 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 = true; + + /** + * What do you want the error msg to be if the form doesn't validate + * + * @var string + * @access protected + */ + protected $errorMsg + = '
    + Warning: The form was not sent, please review the errors below. +
    '; + + /** + * What do you want the success msg to be if the form validates successfully + * + * @var string + * @access protected + */ + protected $successMsg + = '
    + The information below has been successfully submitted. +
    '; + + /** + * Whether uploaded files should be processed too (if present) + * + * @var string + * @access protected + */ + protected $mergeFiles = true; + + /** + * Include a captcha on the form or not + * + * @var boolean + * @access protected + */ + protected $useCaptcha; + + /** + * The default templates to inject into the form renderer + * + * @var string + * @access protected + */ + protected $template; + + /** + * 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. + * + * These rules can be removed in subclasses before the rules are configured + * if you want to omit any of them from validating input - just remember + * to not call them in your configured rules! + * + * Phone: validates input against US and CA style phone #'s + * + * $rules[] = array('element' => 'phone', + * 'message' => 'ERROR: Invalid Phone Format!', + * 'type' => 'phone', + * 'format' => null, + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * Zip: Validates input against US and CA zip codes, if DB check is + * set to true, validate zip codes against all the zip codes in the + * DB. + * + * $rules[] = array('element' => 'zip', + * 'message' => 'ERROR: Invalid Zip!', + * 'type' => 'zip', + * 'format' => array('requireDBCheck' => true), + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * Banwords: Make sure each each doesn't contain a banned word. Checking + * against a DB of banned words. + * + * State: Validate input against US and CA region / province codes. If DB + * check is set to true, validate region / province against all the + * regions / provinces in the DB. + * + * $rules[] = array('element' => 'state_id', + * 'message' => 'ERROR: Invalid State / Province!', + * 'type' => 'state', + * 'format' => array('requireDBCheck' => true), + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * @var array + * @access protected + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Zip.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Phone.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Banwords.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/State.php + */ + protected $registeredRules = array('phone', 'zip', 'state'); + + // }}} + // {{{ __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
    tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + * @todo Remove assigning the dbh the global dbh and setup a PDO + * to be passed in from a parameter - this will allow for easier + * PHPUnit testing + */ + 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->template = BASE . 'Toolkit/Forms/templates/tables/'; + $this->dbh = Toolkit_Database::getInstance(); + + if ($this->includeContactStyleSheet) { + $GLOBALS['styleSheets'][] = BASE_URL . 'css/contactform.css'; + } + } + + // }}} + + // {{{ addCharLimit() + + /** + * adds a maxlength character limitation to an element + * + * @param string $element The name of the element to add + * the char limit to + * @param integer $limit The number of characters allowed + * + * @return void + * @access public + */ + public function addCharLimit($element, $limit) + { + $this->addRule( + $element, + "ERROR: $limit characters max!", + 'maxlength', + $limit, + 'server' + ); + // Add a maxlength attribute to the field on the form + // which will help prevent users from sending over 100 chars + // to the server in the first place. + if ($this->getElementType($element) == 'text') { + $e =& $this->getElement($element); + $e->setMaxLength($limit); + } + } + + // }}} + // {{{ apiVersion() + + /** + * Returns the current FormBuilder API version + * + * @since 1.10 + * @access public + * @return float + */ + public function version() + { + return 1.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) + { + if ( empty($value['m']) + || empty($value['d']) + || empty($value['Y']) + ) { + return false; + } + return checkdate($value['m'], $value['d'], $value['Y']); + } + + // }}} + // {{{ cleanElements() + + /** + * Removes elements from form + * + * Loops through elements and if any names end in '_rmv' they are removed + * from the form object. + * + * Dynamically finds all elements on a form and removes any that + * end in '_rmv'. This can be really usefull if you want to display + * from results after the form was successfully submitted and validated, + * but don't need to display any extra form elements initially displayed + * on the form (like email confirmation fields, or static instruction + * elements). + * + * @param array $elements Form elements. + * + * @return void + * @access protected + */ + protected function cleanElements($elements) + { + if (is_array($elements)) { + foreach ($elements as $e) { + if ($e['type'] == 'group') { + $this->cleanGroup($e['name']); + } elseif (preg_match('/^.+_rmv$/', $e['name'])) { + $this->removeElement($e['name']); + } + } + } + } + + // }}} + // {{{ cleanForm() + + /** + * Removes elements from form + * + * Dynamically finds all elements on a form and removes any that + * end in '_rmv'. This can be really usefull if you want to display + * from results after the form was successfully submitted and validated, + * but don't need to display any extra form elements initially displayed + * on the form (like email confirmation fields, or static instruction + * elements). + * + * @return void + * @access protected + */ + protected function cleanForm() + { + $formArray = $this->toArray(); + if (array_key_exists('sections', $formArray)) { + foreach ($formArray['sections'] as $k) { + if (preg_match('/^.+_rmv$/', $k['name'])) { + $this->removeElement($k['name']); + } + $this->cleanElements($k['elements']); + } + } else { + $this->cleanElements($formArray['elements']); + } + } + + // }}} + // {{{ cleanGroup() + + /** + * Removes any elements from a group that have names that end in '_rmv' + * + * @param string $name The name of the group element + * + * @return void + * @access protected + */ + protected function cleanGroup($name) + { + $e =& $this->getElement($name); + $g =& $e->getElements(); + $i = 0; + while ($name = $e->getElementName($i++)) { + if (preg_match('/^.+_rmv/', $name)) { + unset($g[($i - 1)]); + } + } + } + + // }}} + // {{{ createGridElement() + + /** + * Creates a grid element for the form + * + * Written so this can be overridden easily in subclasses later if needed! + * + * @param string $elementType QuickForm ElementGrid element definition + * + * @return mixed ElementGrid element. + * @access protected + */ + protected function &createGridElement($elementType) + { + $args = func_get_args(); + return call_user_func_array(array($this, 'createElement'), $args); + + } + + // }}} + + // {{{ getErrorMessage() + + public function getErrorMessage() + { + return $this->errorMsg; + } + + // }}} + // {{{ prepElement() + + /** + * Make sure all the element array indexes are set + * + * @param array &$e Element to prep + * + * @return void + * @access protected + */ + protected function prepElement(&$e) + { + if (!isset($e['opts'])) { + $e['opts'] = ''; + } + if (!isset($e['att'])) { + $e['att'] = ''; + } + if (!isset($e['val'])) { + $e['val'] = ''; + } + if (!isset($e['display'])) { + $e['display'] = ''; + } + if (!isset($e['label'])) { + $e['label'] = ''; + } + if (!isset($e['noCharLimit'])) { + $e['noCharLimit'] = false; + } + } + + // }}} + + // {{{ registerRules() + + /** + * Registers custom form rules you can use when validating + * + * If the registeredRule token is an array, any QF rule can be + * registered. This is useful if you want to register rules + * from outside classes + * e.g. (Validate, Validate_US, Validate_CA, etc...). + * + * This will set up a rule called 'checkEmail' which uses the + * Validate::email() function. + * you can still pass in parameters to this rule if you pass them in + * via the 'format' option when you are defining your rules. + * + * class exampleClass + * { + * $registeredRules = array( + * array( + * 'checkEmail', + * 'callback', + * 'email', + * 'Validate' + * ) + * ); + * + * // ... Rest of your class code + * + * public function configureRules() + * { + * $r = array(); + * + * $r[] = array( + * 'element' => 'process_email', + * 'message' => 'ERROR: Invalid email format!', + * 'type' => 'checkEmail', + * 'format' => array('use_rfc822' => true), + * 'validation' => $this->validationType, + * 'reset' => false, + * 'force' => false + * ); + * + * $this->setupRules($r); + * } + * + * // ... Rest of your class code + * } + * + * + * If the registeredRule is a string, the corresponding rule in the + * glmPEAR/HTML/QuickForm/Rule/ directory will be registered with + * the form. + * + * This will set up the 'phone' rule already defined in the + * glmPEAR/HTML/QuickForm/Rule directory which validates both + * US and Canadian phone numbers + * + * class exampleClass + * { + * $registeredRules = array('phone'); + * + * // ... Rest of your class code + * + * public function configureRules() + * { + * $r = array(); + * + * $r[] = array( + * 'element' => 'phone', + * 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + * 'type' => 'phone', + * 'format' => null, + * 'validation' => $this->validationType, + * 'reset' => false, + * 'force' => false + * ); + * + * $this->setupRules($r); + * } + * + * // ... Rest of your class code + * } + * + * + * @return void + * @access protected + */ + protected function registerRules() + { + if (is_array($this->registeredRules)) { + foreach ($this->registeredRules as $r) { + if (is_array($r)) { + call_user_func_array(array(&$this, 'registerRule'), $r); + } else { + // Don't nedd to register rules more than once + if (!$this->isRuleRegistered($r)) { + $this->registerRule($r, null, "HTML_QuickForm_Rule_$r"); + } + } + } + } + } + + // }}} + + // {{{ setAutoValidateDateElements() + + /** + * Set if we need to auto validate the Date Elements + * + * @param boolean $validate true/false to auto validate date elements + * + * @return void + * @access public + */ + public function setAutoValidateDateElements($validate) + { + $this->autoValidateDateElements = $validate; + } + + // }}} + // {{{ setFormData() + + /** + * Sets the submitted values from the form + * + * Set these values into an internal variable so they will be accessible + * anywhere we need them in the form. + * + * @param array $exclude (optional) Any element names you don't want + * included. Since this is primarily used in + * emailing, this is helpful to exclude any data + * we don't want before the array is generated. + * + * @return void + * @access protected + */ + protected function setFormData(array $exclude = array()) + { + $values = $this->getSubmitValues(); + foreach ($values as $k => $v) { + if ($this->elementExists($k)) { + $e =& $this->getElement($k); + if (!in_array($e->getName(), $exclude)) { + switch ($e->getType()) { + case 'date' : + list($m, $d, $y) = array_values($e->getValue()); + // If all the date fields are empty, then don't add + // the output to the formData. + if (!(empty($m[0]) && empty($d[0]) && empty($y[0]))) { + $this->formData[$e->getName()]['label'] + = $e->getLabel(); + + $oldDate = $e->getValue(); + $newDate = Toolkit_Common::arrayFlatten( + $oldDate, + 0, + $newDate + ); + + $this->formData[$e->getName()]['element'] + = implode(' / ', $newDate); + unset($oldDate, $newDate); + } + break; + + case 'group': + $e->freeze(); + $this->formData[$e->getName()]['label'] = $e->getLabel(); + $this->formData[$e->getName()]['element'] = $e->toHtml(); + break; + + case 'select' : + $this->formData[$e->getName()]['label'] = $e->getLabel(); + + $values = $e->getValue(); + foreach ($values as $v) { + $this->formData[$e->getName()]['element'] .= $v; + } + break; + + default : + $this->formData[$e->getName()]['label'] = $e->getLabel(); + $this->formData[$e->getName()]['element'] = $e->getValue(); + break; + } + } + } + } + } + + // }}} + // {{{ setupConstants() + + /** + * Sets the form constant values + * + * @param array $constants Associative array of form constant values. + * + * @return void + * @access protected + */ + protected function setupConstants($constants) + { + $this->setConstants($constants); + } + + // }}} + // {{{ 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); + } + + // }}} + // {{{ 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($elements) + { + if (!is_array($elements)) { + return; + } + foreach ($elements as &$e) { + $this->prepElement($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) { + $this->prepElement($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'] + ); + unset($columnNames); + + // Loop through the rows (r) and columns (c) + // to add each of the elements to our grid. + foreach ($e['group'] as $k => $r) { + unset($set, $rowTitle); + foreach ($r as $c) { + $columnNames[$c['display']] = $c['display']; + + $set[] =& $this->createGridElement( + $c['type'], + $c['name'], + null, + $c['opts'], + $c['att'] + ); + } + $rowTitle = is_int($k) ? ' ' : $k; + $source->addRow($set, $rowTitle); + } + + $source->setColumnNames($columnNames); + 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)) { + var_dump($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; + } + + if ($e['name'] == 'captcha_rmv') { + $this->captchaAnswer =& $source; + } + + if ($e['name'] == 'captcha_question') { + $this->captchaQuestion =& $source; + } + break; + } + } + $this->formElements = $elements; + } + + // }}} + // {{{ 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); + } + } + } + + // }}} + // {{{ 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. + * + * // 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 + * ); + * + * + * 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. + * + * $r[] = array( + * 'element' => 'element_name', + * 'message' => 'ERROR: Error to display!', + * 'type' => 'required', + * 'format' => null, + * 'howMany' => 1, + * 'validation'=> $this->validationType, + * 'reset' => true, + * 'force' => false, + * ); + * + * + * @param array $rules Multi-Dimensional array of rules for form elements. + * + * @return void + * @access protected + */ + protected function setupRules(array $rules = null) + { + $this->registerRules(); + $preRegisteredRules = $this->getRegisteredRules(); + if (is_array($this->formElements)) { + foreach ($this->formElements as $e) { + // Put length limitations on text and textarea fields + if ($e['type'] == 'text' && !$e['noCharLimit']) { + $this->addCharLimit($e['name'], 100); + } elseif ($e['type'] == 'textarea' && !$e['noCharLimit']) { + $this->addCharLimit($e['name'], 1000); + } elseif ($e['type'] == 'group') { + // We need to apply these same limitations to the + // text and textarea fields inside of groups + $r = array(); + if (is_array($e['group'])) { + foreach ($e['group'] as $i) { + // Loop through group elements and if they are + // text/textarea fields then put the field into + // a rule array that we will assign to the group + if ($i['type'] == 'text' && !$i['noCharLimit']) { + $r[$i['name']][] = array( + 'ERROR: 100 characters max!', + 'maxlength' + ); + } elseif ($i['type'] == 'textarea' && !$i['noCharLimit']) { + $r[$i['name']][] = array( + 'ERROR: 1000 characters max!', + 'maxlength' + ); + } + } + } + if (!empty($r)) { + $this->addGroupRule($e['name'], $r); + } + } + 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'] + ); + } elseif (in_array($r['type'], $preRegisteredRules)) { + $this->addRule( + $r['element'], + $r['message'], + $r['type'], + $r['format'], + $r['validation'], + $r['reset'], + $r['force'] + ); + } + } + } + } + + // }}} + // {{{ setupRenderers() + + /** + * Sets up renderers for form objects + * + * Uses the default form renderer to allow templates to be injected + * into the form object before displaying on a page. This allows + * changing the face of the form w/ out any backend adjustment. + * + * Files that can be created for templates are + * + * Examples: + * # Element.tpl + * + * + * + * + * * + * + * + * + * + * + *
    {error}
    + * + * {element} + * + * + *
    + * + * # Form.tpl + * + *
    + * + * + * {content} + *
    + * + *
    + *
    + * + * # GroupElement.tpl + * + * + * + * {element} + * + * * + * + * {label} + * + * + * + * + * # Group.tpl + * + * + * + * {content} + * + *
    + *
    + * + * # Header.tpl + * + * + * + * {header} + * + * + * + * + * # RequiredNote.tpl + * + * * Denotes required field + * + * + * @param array $groups any groups that need to be rendered + * via the groupElementTemplate and groupTemplate + * + * @return void + * @access protected + */ + protected function setupRenderers(array $groups = array()) + { + $renderer =& $this->defaultRenderer(); + if (is_dir($this->template)) { + if ($dh = opendir($this->template)) { + while (($file = readdir($dh)) !== false) { + // Ignore current dir and parent dir. + if ($file != '..' && $file != '.' && $file != 'CVS') { + $baseName = reset(explode('.', $file)); + // Ignores swp files. + if (!empty($baseName)) { + $method = "set{$baseName}Template"; + $template = file_get_contents($this->template . $file); + if ( $method != 'setGroupTemplate' + && $method != 'setGroupElementTemplate' + ) { + if (method_exists($renderer, $method)) { + $renderer->$method($template); + } + } else { + // apply the templates to any defined groups + foreach ($groups as $k) { + $renderer->$method($template, $k); + } + } + } + } + } + closedir($dh); + } + } + + // Set the default how the captcha's should look + // can be overridden in subclasses + if ($this->useCaptcha) { + $required = '*'; + $error = '
    {error}
    '; + $renderer->setElementTemplate( + ' + + {element} + ', + 'captcha_question' + ); + $renderer->setElementTemplate( + ' + '.$required.' + '.$error.'{element} + What is this? + + ', + 'captcha_rmv' + ); + } + } + + // }}} + // {{{ useCaptcha() + + /** + * Set if we need to use a captcha in this form or not + * + * @param boolean $useCaptcha true/false to use a captcha with the form + * + * @return void + * @access public + */ + public function useCaptcha($useCaptcha) + { + $this->useClueTip(); + $this->useCaptcha = $useCaptcha; + } + + // }}} + // {{{ useClueTip() + + /** + * Set if we need to use the JS cluetip + * + * @param boolean $useCaptcha include cluetip resources or not + * + * @return void + * @access public + */ + public function useClueTip() + { + $GLOBALS['styleSheets'][] + = GLM_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.css'; + $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['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/contactform.js'; + } + + // }}} + // {{{ show() + + /** + * Shows the form + * + * @return void + * @access public + */ + public function show() + { + Toolkit_Common::show(); + } + + // }}} + // {{{ validate() + + public function validate() + { + if (!$this->validated) { + $this->validated = parent::validate(); + } + + return $this->validated; + } + + // }}} +} diff --git a/Toolkit/Forms/Rules/Date.php b/Toolkit/Forms/Rules/Date.php new file mode 100644 index 0000000..e5a53c8 --- /dev/null +++ b/Toolkit/Forms/Rules/Date.php @@ -0,0 +1,93 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_Date + * + * Description of Toolkit_Forms_Rules_Date + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_Date extends HTML_QuickForm_Rule +{ + /** + * Validate if a string is a valid date + * + * If element is part of a group, then you can pass in the group name + * under the options parameter, that way you can find the date values + * + * You must pass in at least the format of the date in an array. + * array('format' => '%m-%d-%Y') is the default + * + * @param string $value the date array to validate + * @param array $options options used to dictate validation of the date + * + * @return bool if the string could correctly be validated as a date. + * @access public + * @see Validate::date() + */ + function validate($value, array $options) + { + $month = !isset($options['group']) + ? $value['m'] + : $value[$options['group']]['m']; + $day = !isset($options['group']) + ? $value['d'] + : $value[$options['group']]['d']; + $year = !isset($options['group']) + ? $value['Y'] + : $value[$options['group']]['Y']; + + if (isset($options['allowEmpty']) + && $options['allowEmpty'] + && empty($month) + && empty($day) + && empty($year) + ) { + return true; + } + + unset($options['group'], $options['allowEmpty']); + + $day = str_pad($day, 2, '0', STR_PAD_LEFT); + $month = str_pad($month, 2, '0', STR_PAD_LEFT); + + return Validate::date("$month-$day-$year", $options); + } + + /** + * gets validation script + * + * @return array + */ + function getValidationScript() + { + return array('', true); + } +} + +HTML_QuickForm::registerRule( + 'Date', + 'rule', + 'Toolkit_Forms_Rules_Date', + BASE . 'Toolkit/Forms/Rules/Date.php' +); +?> diff --git a/Toolkit/Forms/Rules/Image.php b/Toolkit/Forms/Rules/Image.php new file mode 100644 index 0000000..86eec64 --- /dev/null +++ b/Toolkit/Forms/Rules/Image.php @@ -0,0 +1,209 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_Image + * + * Description of Toolkit_Forms_Rules_Image + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_Image extends HTML_QuickForm_Rule +{ + // {{{ validate() + + /** + * Handle image uploading rules + * + * The options array is required and has specific key values + * that must be present. + * + * form : (HTML_Quickform) form object - so we can insert + * the new image name back back into the forms + * submit values. + * fieldName : (string) name of the upload field - this is + * generally the same name as the field we're + * calling the rule on. + * imageField : (string) name of the field that stores the + * filename of the image that was uploaded + * is : (Toolkit_FileServer_ImageAdapter) + * image server instance + * deleteExistingImage : (boolean) Whether to delete any old image from + * the image server before uploading the new image + * injectImage : (array) + * tgtElement : (string) Name of the field that will hold the preview + * of the image - This is usually a static element + * path : (optional) Path to the image - defaults to FORM_THUMB + * imgTag : (optional) Format of the image tag - defaults to + * where %s is the path + image + * + * + * Full Example: + * + * $r[] = array( + * 'element' => 'file_rmv', + * 'message' => 'ERROR: Error uploading image!', + * 'type' => 'Image', + * 'format' => array( + * 'form' => $this, + * 'fieldName' => 'file_rmv', + * 'imageField' => 'image', + * 'is' => new Toolkit_FileServer_ImageAdapter(), + * 'deleteExistingImage' => true, + * 'injectImage' => array( + * 'tgtElement' => 'current_image_rmv', + * 'imgTag' => '', + * 'path' => FORM_THUMB + * ) + * ), + * 'validation' => $this->validationType, + * 'reset' => false, + * 'force' => false + * ); + * + * @param string $value the $_FILES['xxxx'] array + * @param array $options upload options + * + * @return bool if the image was successfully uploaded or not + * @access public + */ + function validate($value, array $options) + { + // No image uploaded - return true + // this can be a valid state, if the field is required - then a + // required rule should be used and will catch before this rule + // is even applied. + if (empty($value['tmp_name'])) { + return true; + } + + if (!isset($options['fieldName'])) { + throw new RuntimeException( + 'Missing `fieldName` key in options' + ); + } + if ( isset($options['is']) + && ($options['is'] instanceof Toolkit_FileServer_ImageAdapter) + ) { + $is = $options['is']; + } else { + throw new RuntimeException( + 'Missing `is` key in options for Image Server instance' + ); + } + + if ( isset($options['form']) + && ($options['form'] instanceof HTML_QuickForm) + ) { + $form =& $options['form']; + } else { + throw new RuntimeException( + 'Missing `form` key in options' + ); + } + + if (isset($options['imageField'])) { + $imageField = $options['imageField']; + } else { + throw new RuntimeException( + 'Missing `imageField` key in options' + ); + } + + if ( isset($options['injectImage']) + && !is_array($options['injectImage']) + ) { + if (!is_array($options['injectImage'])) { + throw new RuntimeException( + '`injectImage` must be an array of options' + ); + } + } elseif ( isset($options['injectImage']) + && is_array($options['injectImage']) + && !isset($options['injectImage']['tgtElement']) + ) { + throw new RuntimeException( + 'The `injectImage` array needs a `tgtElement` index to inject the new image into' + ); + } + + if ( isset($options['deleteExistingImage']) + && $options['deleteExistingImage'] + ) { + $existingImage =& $form->getSubmitValue($imageField); + if (!empty($existingImage)) { + $is->delete($existingImage); + } + } + + try { + $uploadedImage = $is->upload($options['fieldName']); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + return false; + } + + if (isset($options['injectImage'])) { + $imgTag = isset($options['injectImage']['imgTag']) + ? $options['injectImage']['imgTag'] + : ''; + + $path = isset($options['injectImage']['path']) + ? $options['injectImage']['path'] + : FORM_THUMB; + + $htmlImg = sprintf($imgTag, $path . $uploadedImage['name']); + $tgt = $options['injectImage']['tgtElement']; + $currImg =& $form->getElement($tgt); + $currImg->setValue($htmlImg); + } + + $fileName =& $form->getElement($imageField); + $fileName->setValue($uploadedImage['name']); + $form->_submitValues[$imageField] = $uploadedImage['name']; + + return true; + } + + // }}} + + // {{{ getValidationScript() + + /** + * gets validation script + * + * @return array + */ + function getValidationScript() + { + return array('', true); + } + + // }}} +} + +HTML_QuickForm::registerRule( + 'Image', + 'rule', + 'Toolkit_Forms_Rules_Image', + BASE . 'Toolkit/Forms/Rules/Image.php' +); +?> diff --git a/Toolkit/Forms/Rules/ShortUrl.php b/Toolkit/Forms/Rules/ShortUrl.php new file mode 100644 index 0000000..823f14c --- /dev/null +++ b/Toolkit/Forms/Rules/ShortUrl.php @@ -0,0 +1,81 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_ShortUrl + * + * Description of Toolkit_Forms_Rules_ShortUrl + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_ShortUrl extends HTML_QuickForm_Rule +{ + // {{{ validate() + + /** + * Validate if a string is a valid short url + * + * Short URLs can only contain alpha numeric characters plus + * dash and underscore. They must also not be the same name as a file + * on the server. + * + * @param string $value short url to validate + * + * @return bool if the string could correctly be validated as a short url + * @access public + */ + public function validate($value) + { + $hasValidCharacters = !preg_match('/[^-a-zA-Z0-9_]/', $value); + // Short URLs that are the same as an existing file ie: (index.php) + // cause .htaccess to throw errors + $fileDoesNotExist = !file_exists(BASE . $value); + // Short URLs that are the same as an existing file basename + // ie: (index) cause .htaccess to throw errors + list($path, $suffix) = explode('.', $value); + $files = array_filter(glob(BASE . "$path*"), 'is_file'); + $baseNameDoesNotExist = ($files !== false && empty($files)); + return $hasValidCharacters && $fileDoesNotExist && $baseNameDoesNotExist; + } + + // }}} + // {{{ getValidationScript() + + /** + * gets validation script + * + * @return array + */ + public function getValidationScript() + { + return array('', true); + } + + // }}} +} + +HTML_QuickForm::registerRule( + 'ShortUrl', + 'rule', + 'Toolkit_Forms_Rules_ShortUrl', + BASE . 'Toolkit/Forms/Rules/ShortUrl.php' +); +?> diff --git a/Toolkit/Forms/Rules/Url.php b/Toolkit/Forms/Rules/Url.php new file mode 100644 index 0000000..4216c24 --- /dev/null +++ b/Toolkit/Forms/Rules/Url.php @@ -0,0 +1,80 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_Url + * + * Description of Toolkit_Forms_Rules_Url + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_Url extends HTML_QuickForm_Rule +{ + // {{{ validate() + + /** + * Validate if a string is a valid url + * + * @param string $value url to validate + * @param array $options set to null + * + * @return bool if the string could correctly be validated as a url + * @access public + */ + public function validate($value, array $options = null) + { + $validateFilter = FILTER_VALIDATE_URL; + + if (is_null($options)) { + return (bool) filter_var($value, $validateFilter); + } + + $lambdaFunction = create_function('$a, $b', 'return $a | $b;'); + $flags = array_reduce($options, $lambdaFunction, 0); + + return (bool) filter_var($value, $validateFilter, $flags); + + } + + // }}} + // {{{ getValidationScript() + + /** + * gets validation script + * + * @return array + */ + public function getValidationScript() + { + return array('', true); + } + + // }}} +} + +HTML_QuickForm::registerRule( + 'Url', + 'rule', + 'Toolkit_Forms_Rules_Url', + BASE . 'Toolkit/Forms/Rules/Url.php' +); +?> diff --git a/Toolkit/Forms/templates/tables/Element.tpl b/Toolkit/Forms/templates/tables/Element.tpl new file mode 100644 index 0000000..595457b --- /dev/null +++ b/Toolkit/Forms/templates/tables/Element.tpl @@ -0,0 +1,14 @@ + + + + * + + + + + +
    {error}
    + + {element} + + diff --git a/Toolkit/Forms/templates/tables/Form.tpl b/Toolkit/Forms/templates/tables/Form.tpl new file mode 100644 index 0000000..8ed6c2f --- /dev/null +++ b/Toolkit/Forms/templates/tables/Form.tpl @@ -0,0 +1,11 @@ +
    + +
    + {hidden} +
    + {requiredNote} + + {content} +
    + +
    \ No newline at end of file diff --git a/Toolkit/Forms/templates/tables/Group.tpl b/Toolkit/Forms/templates/tables/Group.tpl new file mode 100644 index 0000000..cdd24cf --- /dev/null +++ b/Toolkit/Forms/templates/tables/Group.tpl @@ -0,0 +1,5 @@ + + + {content} + +
    diff --git a/Toolkit/Forms/templates/tables/GroupElement.tpl b/Toolkit/Forms/templates/tables/GroupElement.tpl new file mode 100644 index 0000000..1a4ba27 --- /dev/null +++ b/Toolkit/Forms/templates/tables/GroupElement.tpl @@ -0,0 +1,9 @@ + + + {element} + + * + + {label} + + diff --git a/Toolkit/Forms/templates/tables/Header.tpl b/Toolkit/Forms/templates/tables/Header.tpl new file mode 100644 index 0000000..64ac244 --- /dev/null +++ b/Toolkit/Forms/templates/tables/Header.tpl @@ -0,0 +1,5 @@ + + + {header} + + diff --git a/Toolkit/Forms/templates/tables/RequiredNote.tpl b/Toolkit/Forms/templates/tables/RequiredNote.tpl new file mode 100644 index 0000000..8d61480 --- /dev/null +++ b/Toolkit/Forms/templates/tables/RequiredNote.tpl @@ -0,0 +1 @@ +
    * Denotes required field
    diff --git a/Toolkit/IController.php b/Toolkit/IController.php new file mode 100644 index 0000000..9ba8e15 --- /dev/null +++ b/Toolkit/IController.php @@ -0,0 +1,36 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ + +/** + * Toolkit_IController + * + * Object Mapper pattern class for the Video PDO Table. Creates + * Toolkit_Video_Video objects by values or by id + * + * @category Toolkit + * @package Controller + * @author Steve Sutton + * @copyright 2012 Gaslight media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +interface Toolkit_IController +{ + /** + * default action for the controller + * + * @return string + */ + public function indexAction(); +} diff --git a/Toolkit/IMapper.php b/Toolkit/IMapper.php new file mode 100644 index 0000000..aa440b2 --- /dev/null +++ b/Toolkit/IMapper.php @@ -0,0 +1,36 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Toolkit_IMapper + * + * Interface for creation of mapper classes + * + * @category Toolkit + * @package Mapper + * @author Steve Sutton + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +interface Toolkit_IMapper +{ + /** + * createByValues + * + * @param Array $values array of values to set for the new object + * + * @return object + */ + public function createByValues($values); +} +?> diff --git a/Toolkit/INavigation.php b/Toolkit/INavigation.php new file mode 100644 index 0000000..1e546b6 --- /dev/null +++ b/Toolkit/INavigation.php @@ -0,0 +1,52 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +/** + * Toolkit_INavigation + * + * Interface + * + * @category Toolkit + * @package Toolkit_INavigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +interface Toolkit_INavigation +{ + /** + * Class constructor + * + * @param HTML_Menu $menu Menu + * @param HTML_Menu_Renderer $rEngine Menu Renderer + */ + public function __construct( + HTML_Menu $menu, + HTML_Menu_Renderer $rEngine + ); + + /** + * Render page navigation + * + * @param array $navigation Navigation + * @param unknown $type Type + * + * @return void + */ + public function renderPageNav(array $navigation, $type); +} +?> diff --git a/Toolkit/ITable.php b/Toolkit/ITable.php new file mode 100644 index 0000000..800fe3c --- /dev/null +++ b/Toolkit/ITable.php @@ -0,0 +1,57 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Interface for Table objects + * + * @category Toolkit + * @package Table + * @author Steve Sutton + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +interface Toolkit_ITable +{ + /** + * setId + * + * @param Int $id Table primary key + * + * @return Object + */ + public function setId($id); + /** + * save + * + * @param PDO $dbh Database Connection + * + * @return void + */ + public function save(PDO $dbh); + /** + * insert + * + * @param PDO $dbh Database Connection + * + * @return Object + */ + public function insert(PDO $dbh); + /** + * update + * + * @param PDO $dbh Database Connection + * + * @return Object + */ + public function update(PDO $dbh); +} diff --git a/Toolkit/Image/Converter.php b/Toolkit/Image/Converter.php new file mode 100644 index 0000000..8b4b859 --- /dev/null +++ b/Toolkit/Image/Converter.php @@ -0,0 +1,262 @@ + + * @copyright 2010 Steve Sutton + * @license Gaslight Media + * @version CVS: $Id: Converter.php,v 1.2 2010/07/29 14:56:50 matrix Exp $ + * @link http://pear.php.net/package/Toolkit_Image + * @see References to other sections (if any)... + */ + +/** + * Toolkit_Image_Converter + * + * Long description (if any) ... + * + * @category Toolkit + * @package Image + * @author Steve Sutton + * @copyright 2010 Steve Sutton + * @license Gaslight Media + * @version Release: @package_version@ + * @link http://pear.php.net/package/Toolkit_Image + * @see References to other sections (if any)... + */ +class Toolkit_Image_Converter extends Toolkit_FormBuilder +{ + + /** + * Description for $is + * @var object + * @access protected + */ + protected $is; + + /** + * Description for $dbh + * @var object + * @access protected + */ + protected $dbh; + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param PDO $pdo Databse Handler + * @param Toolkit_Image_Server $is Parameter description (if any) ... + * @param string $formName Parameter description (if any) ... + * @param string $method Parameter description (if any) ... + * @param string $action Parameter description (if any) ... + * @param string $target Parameter description (if any) ... + * @param unknown $attributes Parameter description (if any) ... + * @param boolean $trackSubmit Parameter description (if any) ... + * + * @return void + * @access public + */ + function __construct( + PDO $pdo, + Toolkit_Image_Server $is, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + $this->dbh = $pdo; + $this->is = $is; + $action = empty($action) ? $_SERVER['REQUEST_URI'] : $action; + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function configureForm() + { + $this->setupElements(); + $this->setupRules(); + $this->setupDefaults(); + $this->setupConstants(); + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return void + * @access public + */ + function processData($values) + { + echo '
    '.print_r($values, true).'
    '; + $sql = " + UPDATE {$values['table_name']} + SET {$values['img_field_name']} = :new_img + WHERE {$values['primary_key']} = :id"; + $updateImg = $this->dbh->prepare($sql); + try { + $sql = " + SELECT * + FROM {$values['table_name']} + WHERE {$values['img_field_name']} != '' + AND {$values['img_field_name']} IS NOT NULL + AND {$values['img_field_name']} != 'ERROR' + AND {$values['img_field_name']} !~ '^is' + AND {$values['img_field_name']} !~ '^fs' + "; + $stmt = $this->dbh->prepare($sql); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + if ($row[$values['primary_key']]) { + echo '
    '
    +                        . print_r(
    +                            $values['original_url']
    +                            . '/' . $row[$values['img_field_name']],
    +                            true
    +                        ) . '
    '; + $newImage = $this->is->imageUpload($values['original_url']. '/' . $row[$values['img_field_name']]); + $updateImg->bindParam(":new_img", $newImage, PDO::PARAM_STR); + $updateImg->bindParam(":id", $row[$values['primary_key']], PDO::PARAM_STR); + $updateImg->execute(); + } + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupElements() + { + $e[] = array( + 'type' => 'header', + 'name' => 'header_rmv', + 'display' => 'Converter' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'original_url', + 'display' => 'Original Path URL without ending /' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'table_name', + 'display' => 'Table Name' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'img_field_name', + 'display' => 'Image Field Name' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'primary_key', + 'display' => 'Primary Key' + ); + $e[] = array( + 'type' => 'submit', + 'name' => 'submit', + 'display' => 'Submit' + ); + parent::setupElements($e); + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupConstants() + { + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupDefaults() + { + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupRules() + { + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + function toHtml() + { + if ($this->validate()) { + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + //$output = $this->successMsg; + //$output .= parent::toHTML(); + } + } else if ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + $output = parent::toHtml(); + } + return $output; + } +} +?> diff --git a/Toolkit/Image/Server.php b/Toolkit/Image/Server.php new file mode 100755 index 0000000..236a283 --- /dev/null +++ b/Toolkit/Image/Server.php @@ -0,0 +1,373 @@ + + * @copyright 2008 Steve Sutton + * @license Gaslight Media + * @version CVS: $Id: Server.php,v 1.19 2010/05/25 14:02:45 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Description for define + */ +define('IS_VALIDATE_SECRET', 'Glm0IS1secreT'); + +/** + * Description for define + */ +define('IS_SUBMIT_URL', FILE_SERVER_URL . 'submit.phtml'); + +/** + * Toolkit_Image_Server + * + * Class for implementation of the image server process Chuck has + * setup for is0.gaslightmedia.com + * Uses Curl PHP Library to upload images to the server + * + * @category Toolkit + * @package Image + * @author Steve Sutton + * @copyright 2008 Steve Sutton + * @license Gaslight Media + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Image_Server +{ + // {{{ properties + + /** + * OwnerID for the Image Server User + * @var string + * @access protected + */ + protected $OwnerID; + + /** + * Owner Password + * @var string + * @access protected + */ + protected $OwnerPW; + + /** + * DOMDocument Object + * @var unknown + * @access protected + */ + protected $xml; + + // }}} + + // {{{ __construct() + + /** + * __construct + * + * @return void + * @access public + */ + function __construct() + { + $this->OwnerID = IS_OWNER_ID; + $this->OwnerPW = IS_OWNER_PW; + } + + // }}} + + // {{{ buildImageServerXML() + + /** + * buildImageServerXML + * + * Create the xml for the FileServerRequest + * + * @param string $fileName File to upload or delete + * @param unknown $type Upload or Delete + * + * @return string xml content + * @access public + */ + function buildImageServerXML($fileName, $type) + { + $xml = new DOMDocument('1.0'); + $xml->formatOutput = true; + $FileServerRequest = $xml->createElement('FileServerRequest'); + $FileServerRequest->setAttribute('version', '1.0'); + // AccessRequest part + $AccessRequest = $xml->createElement('AccessRequest'); + $Owner = $xml->createElement('Owner'); + $OwnerID = $xml->createElement('OwnerID', $this->OwnerID); + $OwnerPW = $xml->createElement('OwnerPW', $this->OwnerPW); + $Owner->appendChild($OwnerID); + $Owner->appendChild($OwnerPW); + $AccessRequest->appendChild($Owner); + $FileServerRequest->appendChild($AccessRequest); + // file part + $File = $xml->createElement('File'); + switch ($type) { + case "Upload": + $FileAction = $xml->createElement('FileAction', 'Submit'); + $DeliveryMethod = $xml->createElement('DeliveryMethod', 'Submit'); + $FieldName = $xml->createElement('FieldName', 'file_upload'); + $File->appendChild($FileAction); + $File->appendChild($DeliveryMethod); + $File->appendChild($FieldName); + $FileServerRequest->appendChild($File); + $size = filesize($_FILES[$fileName]['tmp_name']); + $validStr = md5($this->OwnerID.$this->OwnerPW.IS_VALIDATE_SECRET); + break; + case "URL": + $FileAction = $xml->createElement('FileAction', 'Submit'); + $DeliveryMethod = $xml->createElement('DeliveryMethod', 'URL'); + $Src = $xml->createElement('Src', $fileName); + $File->appendChild($FileAction); + $File->appendChild($DeliveryMethod); + $File->appendChild($Src); + $FileServerRequest->appendChild($File); + $size = strlen($fileName); + $validStr = md5($this->OwnerID.$this->OwnerPW.IS_VALIDATE_SECRET); + break; + case "Delete": + $FileAction = $xml->createElement('FileAction', 'Delete'); + $File->appendChild($FileAction); + $FileName = $xml->createElement('FileName', $fileName); + $File->appendChild($FileName); + $FileServerRequest->appendChild($File); + $validStr = md5($this->OwnerID.$this->OwnerPW.IS_VALIDATE_SECRET); + break; + } + // validation part + $Validation = $xml->createElement('Validation', $validStr); + $FileServerRequest->appendChild($Validation); + $xml->appendChild($FileServerRequest); + return $xml->saveXML($xml); + } + + // }}} + + // {{{ imageDelete() + + /** + * imageDelete + * + * Delete an image from the image server + * + * @param unknown $name Image name + * + * @return unknown image name + * @access public + */ + function imageDelete($name) + { + // don't do anything if on development server + if (defined('DEVELOPMENT') && DEVELOPMENT == true) { + return "File deleted. File: " . $name; + } + if ($name) { + $request = $this->buildImageServerXML($name, 'Delete'); + $ch = curl_init(); + $fileData = array( + 'request' => $request + ); + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $xmlDoc = new DOMDocument; + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $SuccessCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $Message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $Owner = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/Owner' + ); + $StoredName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $StoredSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $MediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + return $Message; + } + } + + // }}} + // {{{ imageUpload() + + /** + * imageUpload + * + * Upload image to server + * + * @param string $name Form field name of image + * + * @return string Image name + * @access public + */ + function imageUpload($name) + { + $fileType = null; + if (preg_match("/^http/", $name)) { + $fileType = 'URL'; + } elseif (is_array($_FILES[$name])) { + $fileType = 'Upload'; + } + if ($fileType) { + $request = $this->buildImageServerXML($name, $fileType); + $ch = curl_init(); + if ($fileType == "URL") { + $fileData = array( + 'request' => $request + ); + } else { + $fileData = array( + 'request' => $request, + 'file_upload' => '@'.$_FILES[$name]['tmp_name'], + 'file_upload_name' => $_FILES[$name]['name'] + ); + } + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $xmlDoc = new DOMDocument; + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $SuccessCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $Message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $Owner = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/Owner' + ); + $StoredName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $StoredSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $MediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + if ($SuccessCode != 0) { + //throw new Exception('Image Server Error said:'.$response); + throw new PEAR_Exception('Image Server Error said:'.$response); + exit; + } + return $StoredName; + } + } + + // }}} + + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws PEAR Error + */ + function getImageSize($image) + { + $options = array('allowed_schemes' => array('http','https')); + if (!Validate::uri($image, $options)) { + throw new PEAR_Exception('Invalid URI for the image'); + exit; + } + + $ch = curl_init(); + $curlOptions = array( + CURLOPT_URL => "{$image}/info", + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, +// CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $wPattern = "/(.*)<\/width>/"; + preg_match($wPattern, $response, $matches); + $width = $matches[1]; + $hPattern = "/(.*)<\/height>/"; + preg_match($hPattern, $response, $matches); + $height = $matches[1]; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + + // {{{ xmlPathContent() + + /** + * xmlPathContent + * + * Grab the content given XPath Query + * + * @param unknown $dom DOMDocument nodelist + * @param unknown $content query for XPath + * + * @return object string of node + * @access public + */ + function xmlPathContent($dom, $content) + { + $xPath = new DOMXPath($dom); + $nodelist = $xPath->query($content); + foreach ($nodelist as $entry) { + return $entry->nodeValue; + } + } + + // }}} +} diff --git a/Toolkit/LeadManager/Affiliates/ConstantContact.php b/Toolkit/LeadManager/Affiliates/ConstantContact.php new file mode 100644 index 0000000..8a859f6 --- /dev/null +++ b/Toolkit/LeadManager/Affiliates/ConstantContact.php @@ -0,0 +1,1095 @@ +requestLogin = $this->apikey . "%" . $this->login . ":" . $this->password; + $this->apiPath = $this->apiPath . $this->login; + + try { + if ($this->login == "username" || $this->password == "password" + || $this->apikey == "apikey") { + throw new Exception("You need to update your credentials in your cc_class.php"); + } + } catch (Exception $e) { + echo "" . $e . ""; + } + } + + /** + * Method that returns a list with all states found in states.txt file + * @return array with state codes and state names + */ + public function getStates() + { + $returnArr = array(); + $lines = file("states.txt"); + foreach ($lines as $line) { + $tmp = explode(" - ", $line); + if (sizeof($tmp) == 2) { + $returnArr[trim($tmp[1])] = trim($tmp[0]); + } + } + return $returnArr; + } + + /** + * Returns a list with all countries found in countries.txt file + * @return array with country codes and country names + */ + public function getCountries() + { + $returnArr = array(); + $lines = file("countries.txt"); + foreach ($lines as $line) { + $tmp = explode(" - ", $line); + if (sizeof($tmp) == 2) { + $returnArr[trim($tmp[1])] = trim($tmp[0]); + } + } + return $returnArr; + } + + /** + * Validate an email address + * @return TRUE if address is valid and FALSE if not. + */ + protected function isValidEmail($email) + { + return preg_match('/^[_a-z0-9-][^()<>@,;:"[] ]*@([a-z0-9-]+.)+[a-z]{2,4}$/i', $email); + } + + /** + * Private function used to send requests to ConstantContact server + * @param string $request - is the URL where the request will be made + * @param string $parameter - if it is not empty then this parameter will be sent using POST method + * @param string $type - GET/POST/PUT/DELETE + * @return a string containing server output/response + */ + protected function doServerCall($request, $parameter = '', $type = "GET") + { + $ch = curl_init(); + $request = str_replace('http://', 'https://', $request); + // Convert id URI to BASIC compliant + curl_setopt($ch, CURLOPT_URL, $request); + curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_USERPWD, $this->requestLogin); + # curl_setopt ($ch, CURLOPT_FOLLOWLOCATION ,1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml", 'Content-Length: ' . strlen($parameter))); + curl_setopt($ch, CURLOPT_FAILONERROR, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + switch ($type) { + case 'POST': + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter); + break; + case 'PUT': + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter); + break; + case 'DELETE': + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); + break; + default: + curl_setopt($ch, CURLOPT_HTTPGET, 1); + break; + } + + $emessage = curl_exec($ch); + if ($this->curl_debug) { + echo $error = curl_error($ch); + } + curl_close($ch); + + return $emessage; + } + +} + +/** + * Class that is used for retrieving + * all the Email Lists from Constant Contact and + * all Registered Email Addresses + */ +class CC_List + extends CC_Utility +{ + + /** + * Recursive Method that retrieves all the Email Lists from ConstantContact. + * @param string $path [default is empty] + * @return array of lists + */ + public function getLists($path = '') + { + $mailLists = array(); + + if (empty($path)) { + $call = $this->apiPath . '/lists'; + } else { + $call = $path; + } + + $return = $this->doServerCall($call); + $parsedReturn = simplexml_load_string($return); + $call2 = ''; + + foreach ($parsedReturn->link as $item) { + $tmp = $item->Attributes(); + $nextUrl = ''; + if ((string) $tmp->rel == 'next') { + $nextUrl = (string) $tmp->href; + $arrTmp = explode($this->login, $nextUrl); + $nextUrl = $arrTmp[1]; + $call2 = $this->apiPath . $nextUrl; + break; + } + } + + foreach ($parsedReturn->entry as $item) { + if ($this->contact_lists) { + if (in_array((string) $item->title, $this->contact_lists)) { + $tmp = array(); + $tmp['id'] = (string) $item->id; + $tmp['title'] = (string) $item->title; + $mailLists[] = $tmp; + } + } else if (!in_array((string) $item->title, $this->doNotIncludeLists)) { + $tmp = array(); + $tmp['id'] = (string) $item->id; + $tmp['title'] = (string) $item->title; + $mailLists[] = $tmp; + } + } + + if (empty($call2)) { + return $mailLists; + } else { + return array_merge($mailLists, $this->getLists($call2)); + } + } + + /** + * Method that retrieves all Registered Email Addresses. + * @param string $email_id [default is empty] + * @return array of lists + */ + public function getAccountLists($email_id = '') + { + $mailAccountList = array(); + + if (empty($email_id)) { + $call = $this->apiPath . '/settings/emailaddresses'; + } else { + $call = $this->apiPath . '/settings/emailaddresses/' . $email_id; + } + + $return = $this->doServerCall($call); + $parsedReturn = simplexml_load_string($return); + + foreach ($parsedReturn->entry as $item) { + $nextStatus = $item->content->Email->Status; + $nextEmail = (string) $item->title; + $nextId = $item->id; + $nextAccountList = array('Email' => $nextEmail, 'Id' => $nextId); + if ($nextStatus == 'Verified') { + $mailAccountList[] = $nextAccountList; + } + } + return $mailAccountList; + } + +} + +/** + * Class that is used for ConstantConact CRUD management + */ +class CC_Contact + extends CC_Utility +{ + + /** + * Method that checks if a subscriber already exist + * @param string $email + * @return subscriber`s id if it exists or false if it doesn't + */ + public function subscriberExists($email = '') + { + $call = $this->apiPath . '/contacts?email=' . $email; + $return = $this->doServerCall($call); + $xml = simplexml_load_string($return); + $id = $xml->entry->id; + if ($id) { + return $id; + } else { + return false; + } + } + + /** + * Method that retrieves from Constant Contact a collection with all the Subscribers + * If email parameter is mentioned then only mentioned contact is retrieved. + * @param string $email + * @return Bi-Dimenstional array with information about contacts. + */ + public function getSubscribers($email = '', $page = '') + { + $contacts = array(); + $contacts['items'] = array(); + + if (!empty($email)) { + $call = $this->apiPath . '/contacts?email=' . $email; + } else { + if (!empty($page)) { + $call = $this->apiPath . $page; + } else { + $call = $this->apiPath . '/contacts'; + } + } + + $return = $this->doServerCall($call); + $parsedReturn = simplexml_load_string($return); + // We parse here the link array to establish which are the next page and previous page + foreach ($parsedReturn->link as $item) { + $attributes = $item->Attributes(); + + if (!empty($attributes['rel']) && $attributes['rel'] == 'next') { + $tmp = explode($this->login, $attributes['href']); + $contacts['next'] = $tmp[1]; + } + if (!empty($attributes['rel']) && $attributes['rel'] == 'first') { + $tmp = explode($this->login, $attributes['href']); + $contacts['first'] = $tmp[1]; + } + if (!empty($attributes['rel']) && $attributes['rel'] == 'current') { + $tmp = explode($this->login, $attributes['href']); + $contacts['current'] = $tmp[1]; + } + } + + foreach ($parsedReturn->entry as $item) { + $tmp = array(); + $tmp['id'] = (string) $item->id; + $tmp['title'] = (string) $item->title; + $tmp['status'] = (string) $item->content->Contact->Status; + $tmp['EmailAddress'] = (string) $item->content->Contact->EmailAddress; + $tmp['EmailType'] = (string) $item->content->Contact->EmailType; + $tmp['Name'] = (string) $item->content->Contact->Name; + $contacts['items'][] = $tmp; + } + + return $contacts; + } + + /** + * Retrieves all the details for a specific contact identified by $email. + * @param string $email + * @return array with all information about the contact. + */ + public function getSubscriberDetails($email) + { + $contact = $this->getSubscribers($email); + $fullContact = array(); + $call = str_replace('http://', 'https://', $contact['items'][0]['id']); + // Convert id URI to BASIC compliant + $return = $this->doServerCall($call); + $parsedReturn = simplexml_load_string($return); + $fullContact['id'] = $parsedReturn->id; + $fullContact['email_address'] = $parsedReturn->content->Contact->EmailAddress; + $fullContact['first_name'] = $parsedReturn->content->Contact->FirstName; + $fullContact['last_name'] = $parsedReturn->content->Contact->LastName; + $fullContact['middle_name'] = $parsedReturn->content->Contact->MiddleName; + $fullContact['company_name'] = $parsedReturn->content->Contact->CompanyName; + $fullContact['job_title'] = $parsedReturn->content->Contact->JobTitle; + $fullContact['home_number'] = $parsedReturn->content->Contact->HomePhone; + $fullContact['work_number'] = $parsedReturn->content->Contact->WorkPhone; + $fullContact['address_line_1'] = $parsedReturn->content->Contact->Addr1; + $fullContact['address_line_2'] = $parsedReturn->content->Contact->Addr2; + $fullContact['address_line_3'] = $parsedReturn->content->Contact->Addr3; + $fullContact['city_name'] = (string) $parsedReturn->content->Contact->City; + $fullContact['state_code'] = (string) $parsedReturn->content->Contact->StateCode; + $fullContact['state_name'] = (string) $parsedReturn->content->Contact->StateName; + $fullContact['country_code'] = $parsedReturn->content->Contact->CountryCode; + $fullContact['zip_code'] = $parsedReturn->content->Contact->PostalCode; + $fullContact['sub_zip_code'] = $parsedReturn->content->Contact->SubPostalCode; + $fullContact['custom_field_1'] = $parsedReturn->content->Contact->CustomField1; + $fullContact['custom_field_2'] = $parsedReturn->content->Contact->CustomField2; + $fullContact['custom_field_3'] = $parsedReturn->content->Contact->CustomField3; + $fullContact['custom_field_4'] = $parsedReturn->content->Contact->CustomField4; + $fullContact['custom_field_5'] = $parsedReturn->content->Contact->CustomField5; + $fullContact['custom_field_6'] = $parsedReturn->content->Contact->CustomField6; + $fullContact['custom_field_7'] = $parsedReturn->content->Contact->CustomField7; + $fullContact['custom_field_8'] = $parsedReturn->content->Contact->CustomField8; + $fullContact['custom_field_9'] = $parsedReturn->content->Contact->CustomField9; + $fullContact['custom_field_10'] = $parsedReturn->content->Contact->CustomField10; + $fullContact['custom_field_11'] = $parsedReturn->content->Contact->CustomField11; + $fullContact['custom_field_12'] = $parsedReturn->content->Contact->CustomField12; + $fullContact['custom_field_13'] = $parsedReturn->content->Contact->CustomField13; + $fullContact['custom_field_14'] = $parsedReturn->content->Contact->CustomField14; + $fullContact['custom_field_15'] = $parsedReturn->content->Contact->CustomField15; + $fullContact['notes'] = $parsedReturn->content->Contact->Note; + $fullContact['mail_type'] = $parsedReturn->content->Contact->EmailType; + $fullContact['status'] = $parsedReturn->content->Contact->Status; + $fullContact['lists'] = array(); + + if ($parsedReturn->content->Contact->ContactLists->ContactList) { + foreach ($parsedReturn->content->Contact->ContactLists->ContactList as $item) { + $fullContact['lists'][] = trim((string) $item->Attributes()); + } + } + + return $fullContact; + } + + /** + * Method that modifies a contact State to DO NOT MAIL + * @param string $email - contact email address + * @return TRUE in case of success or FALSE otherwise + */ + public function deleteSubscriber($email) + { + if (empty($email)) { + return false; + } + $contact = $this->getSubscribers($email); + $id = $contact['items'][0]['id']; + $return = $this->doServerCall($id, '', 'DELETE'); + if (!empty($return)) { + return false; + } + return true; + } + + /** + * Method that modifies a contact State to REMOVED + * @param string $email - contact email address + * @return TRUE in case of success or FALSE otherwise + */ + public function removeSubscriber($email) + { + $contact = $this->getSubscriberDetails($email); + $contact['lists'] = array(); + $xml = $this->createContactXML($contact['id'], $contact); + + if ($this->editSubscriber($contact['id'], $xml)) { + return true; + } else { + return false; + } + } + + /** + * Upload a new contact to Constant Contact server + * @param strong $contactXML - formatted XML with contact information + * @return TRUE in case of success or FALSE otherwise + */ + public function addSubscriber($contactXML) + { + $call = $this->apiPath . '/contacts'; + $return = $this->doServerCall($call, $contactXML, 'POST'); + $parsedReturn = simplexml_load_string($return); + + if ($return) { + return true; + } else { + $xml = simplexml_load_string($contactXML); + $emailAddress = $xml->content->Contact->EmailAddress; + if ($this->subscriberExists($emailAddress)) { + $this->lastError = 'This contact already exists. Click here to edit the contact details.'; + } else { + $this->lastError = 'An Error Occurred'; + } + return false; + } + } + + /** + * Modifies a contact + * @param string $contactUrl - identifies the url for the modified contact + * @param string $contactXML - formed XML with contact information + * @return TRUE in case of success or FALSE otherwise + */ + public function editSubscriber($contactUrl, $contactXML) + { + $return = $this->doServerCall($contactUrl, $contactXML, 'PUT'); + + if (!empty($return)) { + if (strpos($return, '<') !== false) { + $parsedReturn = simplexml_load_string($return); + if (!empty($parsedReturn->message)) { + $this->lastError = $parsedReturn->message; + } + } else { + $this->lastError = $parsedReturn->message; + } + return false; + } + return true; + } + + /** + * Method that compose the needed XML format for a contact + * @param string $id + * @param array $params + * @return Formed XML + */ + public function createContactXML($id, $params = array()) + { + if (empty($id)) { + $id = "urn:uuid:E8553C09F4xcvxCCC53F481214230867087"; + } + + $update_date = date("Y-m-d") . 'T' . date("H:i:s") . '+01:00'; + $xml_string = ""; + $xml_object = simplexml_load_string($xml_string); + $title_node = $xml_object->addChild("title", htmlspecialchars(("TitleNode"), ENT_QUOTES, 'UTF-8')); + $updated_node = $xml_object->addChild("updated", htmlspecialchars(($update_date), ENT_QUOTES, 'UTF-8')); + $author_node = $xml_object->addChild("author"); + $author_name = $author_node->addChild("name", ("CTCT Samples")); + $id_node = $xml_object->addChild("id", htmlspecialchars(($id), ENT_QUOTES, 'UTF-8')); + $summary_node = $xml_object->addChild("summary", htmlspecialchars(("Customer document"), ENT_QUOTES, 'UTF-8')); + $summary_node->addAttribute("type", "text"); + $content_node = $xml_object->addChild("content"); + $content_node->addAttribute("type", "application/vnd.ctct+xml"); + $contact_node = $content_node->addChild("Contact", htmlspecialchars(("Customer document"), ENT_QUOTES, 'UTF-8')); + $contact_node->addAttribute("xmlns", "http://ws.constantcontact.com/ns/1.0/"); + $email_node = $contact_node->addChild("EmailAddress", htmlspecialchars(($params['email_address']), ENT_QUOTES, 'UTF-8')); + $fname_node = $contact_node->addChild("FirstName", urldecode(htmlspecialchars(($params['first_name']), ENT_QUOTES, 'UTF-8'))); + $lname_node = $contact_node->addChild("LastName", urldecode(htmlspecialchars(($params['last_name']), ENT_QUOTES, 'UTF-8'))); + $lname_node = $contact_node->addChild("MiddleName", urldecode(htmlspecialchars(($params['middle_name']), ENT_QUOTES, 'UTF-8'))); + if (isset($params['company_name'])) { + $lname_node = $contact_node->addChild("CompanyName", urldecode(htmlspecialchars(($params['company_name']), ENT_QUOTES, 'UTF-8'))); + } + if (isset($params['JobTitle'])) { + $lname_node = $contact_node->addChild("job_title", urldecode(htmlspecialchars(($params['job_title']), ENT_QUOTES, 'UTF-8'))); + } + if (isset($params['status'])) { + if ($params['status'] == 'Do Not Mail') { + $this->actionBy = 'ACTION_BY_CONTACT'; + } + } + + $optin_node = $contact_node->addChild("OptInSource", htmlspecialchars($this->actionBy)); + $hn_node = $contact_node->addChild("HomePhone", htmlspecialchars($params['home_number'], ENT_QUOTES, 'UTF-8')); + if (isset($params['work_number'])) { + $wn_node = $contact_node->addChild("WorkPhone", htmlspecialchars($params['work_number'], ENT_QUOTES, 'UTF-8')); + } + $ad1_node = $contact_node->addChild("Addr1", htmlspecialchars($params['address_line_1'], ENT_QUOTES, 'UTF-8')); + $ad2_node = $contact_node->addChild("Addr2", htmlspecialchars($params['address_line_2'], ENT_QUOTES, 'UTF-8')); + $ad3_node = $contact_node->addChild("Addr3", htmlspecialchars($params['address_line_3'], ENT_QUOTES, 'UTF-8')); + $city_node = $contact_node->addChild("City", htmlspecialchars($params['city_name'], ENT_QUOTES, 'UTF-8')); + $state_node = $contact_node->addChild("StateCode", htmlspecialchars($params['state_code'], ENT_QUOTES, 'UTF-8')); + $state_name = $contact_node->addChild("StateName", htmlspecialchars($params['state_name'], ENT_QUOTES, 'UTF-8')); + $ctry_node = $contact_node->addChild("CountryCode", htmlspecialchars($params['country_code'], ENT_QUOTES, 'UTF-8')); + $zip_node = $contact_node->addChild("PostalCode", htmlspecialchars($params['zip_code'], ENT_QUOTES, 'UTF-8')); + $subzip_node = $contact_node->addChild("SubPostalCode", htmlspecialchars($params['sub_zip_code'], ENT_QUOTES, 'UTF-8')); + if (isset($params['notes'])) { + $note_node = $contact_node->addChild("Note", htmlspecialchars($params['notes'], ENT_QUOTES, 'UTF-8')); + } + $emailtype_node = $contact_node->addChild("EmailType", htmlspecialchars($params['mail_type'], ENT_QUOTES, 'UTF-8')); + + if (!empty($params['custom_fields'])) { + foreach ($params['custom_fields'] as $k => $v) { + $contact_node->addChild("CustomField" . $k, htmlspecialchars(($v), ENT_QUOTES, 'UTF-8')); + } + } + + $contactlists_node = $contact_node->addChild("ContactLists"); + if ($params['lists']) { + foreach ($params['lists'] as $tmp) { + $contactlist_node = $contactlists_node->addChild("ContactList"); + $contactlist_node->addAttribute("id", $tmp); + } + } + + $entry = $xml_object->asXML(); + return $entry; + } + +} + +/** + * Class that is used for ConstantCampaign CRUD management + */ +class CC_Campaign + extends CC_Utility +{ + + // set this to true to see the xml sent and the output received + var $sent_recived_debug = false; + var $usStates = array("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"); + var $caStates = array("AB", "BC", "MB", "NB", "NL", "NT", "NS", "NU", "ON", "PE", "QC", "SK", "YT"); + var $armedForces = array("AA", "AE", "AP"); + + /** + * Method that returns a html sample for email campaign + * @param string $sample [default is EmailContent]: EmailContent, EmailTextContent or + * PermissionReminder + * @param string $type [default is html]: html or text + * @return a default content for email content or permission reminder + */ + public function getEmailIntro($sample = 'EmailContent', $type = 'html') + { + switch ($sample) { + case 'EmailContent': + $file = 'EmailContent.txt'; + break; + case 'EmailTextContent': + $file = 'EmailContent.txt'; + $type = 'text'; + break; + case 'PermissionReminder': + $file = 'PermissionReminder.txt'; + break; + default: + $file = 'EmailContent.txt'; + } + + $handle = fopen("txt/$file", "rb"); + $contents = ''; + while (!feof($handle)) { + $contents .= fread($handle, 8192); + } + $contents = ($type == 'html') + ? ($contents) + : (trim(strip_tags($contents))); + fclose($handle); + return $contents; + } + + /** + * Method that retrieves campaingn collections from ConstantCampaign + * If campaign_id is mentioned then only mentioned campaign is retrieved. + * If campaign_id represents a status [SENT, DRAFT, RUNNING, SCHEDULED] + * only the campaigns with that status will be retrieved + * @param string $campaign_id [default is empty] + * @return Bi-Dimenstional array with information about campaigns. + */ + public function getCampaigns($campaign_id = '', $page = '') + { + $campaigns = array(); + $campaigns['items'] = array(); + + switch ($campaign_id) { + case 'SENT': + case 'DRAFT': + case 'RUNNING': + case 'SCHEDULED': + $call = $this->apiPath . '/campaigns?status=' . $campaign_id; + break; + case 'ALL': + $call = (!empty($page)) + ? ($this->apiPath . $page) + : ($this->apiPath . '/campaigns'); + break; + default: + $call = $this->apiPath . '/campaigns/' . $campaign_id; + } + + $return = $this->doServerCall($call); + $parsedReturn = simplexml_load_string($return); + //we parse here the link array to establish which are the next page and previous page + if ($parsedReturn != false) { + + foreach ($parsedReturn->link as $item) { + $attributes = $item->Attributes(); + if (!empty($attributes['rel']) && $attributes['rel'] == 'next') { + $tmp = explode($this->login, $attributes['href']); + $campaigns['next'] = $tmp[1]; + } + if (!empty($attributes['rel']) && $attributes['rel'] == 'first') { + $tmp = explode($this->login, $attributes['href']); + $campaigns['first'] = $tmp[1]; + } + if (!empty($attributes['rel']) && $attributes['rel'] == 'current') { + $tmp = explode($this->login, $attributes['href']); + $campaigns['current'] = $tmp[1]; + } + } + + foreach ($parsedReturn->entry as $item) { + $tmp = array(); + $tmp['id'] = (string) $item->id; + $tmp['title'] = (string) $item->title; + $tmp['name'] = (string) $item->content->Campaign->Name; + $tmp['status'] = (string) $item->content->Campaign->Status; + $timestamp = strtotime($item->content->Campaign->Date); + $campaig_date = date("F j, Y, g:i a", $timestamp); + $tmp['date'] = (string) $campaig_date; + $campaigns['items'][] = $tmp; + } + } + return $campaigns; + } + + /** + * Retrieves all the details for a specific campaign identified by $id. + * @param string $id + * @return array with all information about the campaign. + */ + public function getCampaignDetails($id) + { + if (!empty($id)) { + $fullContact = array(); + $call = str_replace('http://', 'https://', $id); + // Convert id URI to BASIC compliant + $return = $this->doServerCall($call); + $parsedReturn = simplexml_load_string($return); + $fullCampaign['campaignId'] = $parsedReturn->id; + $cmp_vars = get_object_vars($parsedReturn->content->Campaign); + + foreach ($cmp_vars as $var_name => $cmp_item) { + $fullCampaign[$var_name] = $cmp_item; + } + + $cmp_from_email = $parsedReturn->content->Campaign->FromEmail->EmailAddress; + $fullCampaign['FromEmail'] = (string) $cmp_from_email; + $cmp_reply_email = $parsedReturn->content->Campaign->ReplyToEmail->EmailAddress; + $fullCampaign['ReplyToEmail'] = (string) $cmp_reply_email; + $fullCampaign['lists'] = array(); + + if ($parsedReturn->content->Campaign->ContactLists->ContactList) { + foreach ($parsedReturn->content->Campaign->ContactLists->ContactList as $item) { + $fullCampaign['lists'][] = trim((string) $item->Attributes()); + } + } + return $fullCampaign; + } else { + return false; + } + } + + /** + * Check if a specific campaign exist already + * @param string $id + * @param string $new_name + * @return a boolean value. + */ + public function campaignExists($id = '', $new_name) + { + if (!empty($id)) { + $call = $this->apiPath . '/campaigns/' . $id; + $return = $this->doServerCall($call); + $xml = simplexml_load_string($return); + if ($xml !== false) { + $id = $xml->content->Campaign->Attributes(); + $id = $id['id']; + $name = $xml->content->Campaign->Name; + } else { + $id = null; + $name = null; + } + $all_campaigns = $this->getCampaigns('ALL'); + $all_campaigns = $all_campaigns['items']; + foreach ($all_campaigns as $key => $item) { + if ($item['name'] == $new_name) { + return 1; // 1 - the new campaign has a similar name with an old one + break; + } + } + /** + * 2 - this campaign already exist + * 0 - this is a new campaign + */ + return ($id != null) + ? (2) + : (0); + } + } + + /** + * Method that delete a camaign; this will exclude + * the removed campaign from overall statistics + * @param string $id - campaign id + * @return TRUE in case of success or FALSE otherwise + */ + public function deleteCampaign($id) + { + if (empty($id)) { + return false; + } + $return = $this->doServerCall($id, '', 'DELETE'); + if (!empty($return) || $return === false) { + return false; + } + return true; + } + + /** + * Upload a new campaign to ConstantContact server + * @param string $campaignXML - formatted XML with campaign information + * @return TRUE in case of success or FALSE otherwise + */ + public function addCampaign($campaignXML) + { + $call = $this->apiPath . '/campaigns'; + $return = $this->doServerCall($call, $campaignXML, 'POST'); + $parsedReturn = simplexml_load_string($return); + if ($return) { + return true; + } else { + $xml = simplexml_load_string($campaignXML); + $cmp_id = $xml->content->Campaign->Attributes(); + $cmp_id = $cmp_id['id']; + $cmp_name = $xml->content->Campaign->Name; + if (!empty($cmp_id)) { + $search_status = $this->campaignExists($cmp_id, $cmp_name); + switch ($search_status) { + case 0: + $error = 'An Error Occurred. The campaign could not be added.'; + break; + case 1: + $error = 'The name of the campaign already exist. Each campaign must have a distinct name.'; + break; + case 2: + $error = 'This campaign already exists.'; + break; + default: + $error = 'An Error Occurred. The campaign could not be added.'; + } + $this->lastError = $error; + } else { + $this->lastError = 'An Error Occurred. The campaign could not be added.'; + } + return false; + } + } + + /** + * Modifies a campaign + * @param string $campaignId - identifies the id for the modified campaign + * @param string $campaignXML - formed XML with campaign information + * @return TRUE in case of success or FALSE otherwise + */ + public function editCampaign($campaignId, $campaignXML) + { + $return = $this->doServerCall($campaignId, $campaignXML, 'PUT'); + if ($return === false) { + $this->lastError = 'An Error Occurred. The campaign could not be edited.'; + return false; + } else { + if (!empty($return)) { + if (strpos($return, '<') !== false) { + $parsedReturn = simplexml_load_string($return); + if (!empty($parsedReturn->message)) { + $this->lastError = $parsedReturn->message; + } + } else { + $this->lastError = $parsedReturn->message; + } + return false; + } + return true; + } + } + + /** + * Method that validate the current campaign before sending it to server + * @param string $id + * @param array $params + * @return an error message or true + */ + public function validateCampaign($id, $params = array()) + { + if (trim($params['cmp_name']) == '') { + $this->lastError = 'Campaign Name is mandatory.'; + return true; + } elseif (trim($params['cmp_subject']) == '') { + $this->lastError = 'Subject is mandatory.'; + return true; + } elseif (trim($params['cmp_from_name']) == '') { + $this->lastError = 'From Name is mandatory.'; + return true; + } elseif (trim($params['cmp_from_email']) == '') { + $this->lastError = 'From Email Address is mandatory.'; + return true; + } elseif (trim($params['cmp_reply_email']) == '') { + $this->lastError = 'Reply Email Address is mandatory.'; + return true; + } elseif (trim($params['cmp_grt_name']) == '') { + $this->lastError = 'Greeting Name is mandatory.'; + return true; + } elseif (trim($params['cmp_org_name']) == '') { + $this->lastError = 'Organization Name is mandatory.'; + return true; + } elseif (trim($params['cmp_org_addr1']) == '') { + $this->lastError = 'Address 1 is mandatory.'; + return true; + } elseif (trim($params['cmp_org_city']) == '') { + $this->lastError = 'City is mandatory.'; + return true; + } elseif (trim($params['org_zip']) == '') { + $this->lastError = 'Zip/Postal Code is mandatory.'; + return true; + } elseif (trim($params['org_country']) == '') { + $this->lastError = 'Country is mandatory.'; + return true; + } elseif (trim($params['cmp_html_body']) == '') { + $this->lastError = 'HTML Body is mandatory.'; + return true; + } elseif ($params["lists"] == NULL) { + $this->lastError = 'Choose at least one Campaign from the list.'; + return true; + } else { + if (trim($params['cmp_perm_reminder']) == 'YES') { + $reminder_text = $params['cmp_txt_reminder']; + if (trim($reminder_text) == '') { + $this->lastError = 'Permission Reminder is required.'; + return true; + } + } + if (trim($params['org_country']) != '') { + if (trim($params['org_country']) == 'us') { + if (trim($params['org_state_us']) == '') { + $this->lastError = 'State is mandatory.'; + return true; + } + if (in_array($params['org_state_us'], $this->caStates)) { + $this->lastError = 'US State is required.'; + return true; + } + } elseif (trim($params['org_country']) == 'ca') { + if (trim($params['org_state_us']) == '') { + $this->lastError = 'State is mandatory.'; + return true; + } + if (in_array($params['org_state_us'], $this->usStates)) { + $this->lastError = 'CA State is required.'; + return true; + } + } + } + if (trim($params['cmp_as_webpage']) == 'YES') { + if (trim($params['cmp_as_webtxt']) == '') { + $this->lastError = 'Webpage Text is required.'; + return true; + } + if (trim($params['cmp_as_weblink']) == '') { + $this->lastError = 'Webpage Link Text is required.'; + return true; + } + } + if (trim($params['cmp_forward']) == 'YES') { + $fwd_email = $params['cmp_fwd_email']; + if (trim($params['cmp_fwd_email']) == '') { + $this->lastError = 'Forward email is required.'; + return true; + } + } + if (trim($params['cmp_subscribe']) == 'YES') { + if (trim($params['cmp_sub_link']) == '') { + $this->lastError = 'Subscribe me is required.'; + return true; + } + } else { + return false; + } + } + } + + /** + * Method that compose the needed XML format for a campaign + * @param string $id + * @param array $params + * @return Formed XML + */ + public function createCampaignXML($id, $params = array()) + { + if (empty($id)) { // Add a new Campaign + $id = str_replace('https://', 'http://', $this->apiPath . "/campaigns/1100546096289"); + $standard_id = str_replace('https://', 'http://', $this->apiPath . "/campaigns"); + } else { + $standard_id = $id; + } + $href = str_replace("http://api.constantcontact.com", "", $id); + $standard_href = str_replace("https://api.constantcontact.com", "", $this->apiPath . "/campaigns"); + $update_date = date("Y-m-d") . 'T' . date("H:i:s") . '+01:00'; + $xml_string = ""; + $xml_object = simplexml_load_string($xml_string); + $link_node = $xml_object->addChild("link"); + $link_node->addAttribute("href", $standard_href); //[1st *href] + $link_node->addAttribute("rel", "edit"); + $id_node = $xml_object->addChild("id", $standard_id); //[1st *id] + $title_node = $xml_object->addChild("title", htmlspecialchars($params['cmp_name'], ENT_QUOTES, 'UTF-8')); + $title_node->addAttribute("type", "text"); + $updated_node = $xml_object->addChild("updated", htmlentities($update_date)); + $author_node = $xml_object->addChild("author"); + $author_name = $author_node->addChild("name", htmlentities("Constant Contact")); + $content_node = $xml_object->addChild("content"); + $content_node->addAttribute("type", "application/vnd.ctct+xml"); + $campaign_node = $content_node->addChild("Campaign"); + $campaign_node->addAttribute("xmlns", "http://ws.constantcontact.com/ns/1.0/"); + $campaign_node->addAttribute("id", $id); //[2nd *id] + $name_node = $campaign_node->addChild("Name", urldecode(htmlspecialchars($params['cmp_name'], ENT_QUOTES, 'UTF-8'))); + $campaign_status = !empty($params['cmp_status']) + ? ($params['cmp_status']) + : ('Draft'); + $status_node = $campaign_node->addChild("Status", urldecode(htmlentities($campaign_status))); + $campaign_date = !empty($params['cmp_date']) + ? ($params['cmp_date']) + : ($update_date); + $date_node = $campaign_node->addChild("Date", urldecode(htmlentities($campaign_date))); + $subj_node = $campaign_node->addChild("Subject", urldecode(htmlspecialchars($params['cmp_subject'], ENT_QUOTES, 'UTF-8'))); + $from_name_node = $campaign_node->addChild("FromName", urldecode(htmlspecialchars($params['cmp_from_name'], ENT_QUOTES, 'UTF-8'))); + $view_as_webpage = (!empty($params['cmp_as_webpage']) && $params['cmp_as_webpage'] == 'YES') + ? ('YES') + : ('NO'); + $as_webpage_node = $campaign_node->addChild("ViewAsWebpage", urldecode(htmlentities($view_as_webpage))); + #$as_web_lnk_txt = ($view_as_webpage == 'YES') ? ($params['cmp_as_weblink']) : (''); + $as_web_lnk_txt = $params['cmp_as_weblink']; + $as_weblink_node = $campaign_node->addChild("ViewAsWebpageLinkText", urldecode(htmlspecialchars(($as_web_lnk_txt), ENT_QUOTES, 'UTF-8'))); + #$as_web_txt = ($view_as_webpage == 'YES') ? ($params['cmp_as_webtxt']) : (''); + $as_web_txt = $params['cmp_as_webtxt']; + $as_webtxt_node = $campaign_node->addChild("ViewAsWebpageText", urldecode(htmlspecialchars(($as_web_txt), ENT_QUOTES, 'UTF-8'))); + $perm_reminder_node = $campaign_node->addChild("PermissionReminder", urldecode(htmlentities($params['cmp_perm_reminder']))); + $permission_reminder_text = ($params['cmp_perm_reminder'] == 'YES') + ? ($params['cmp_txt_reminder']) + : (''); + $text_reminder_node = $campaign_node->addChild("PermissionReminderText", urldecode(htmlspecialchars(($permission_reminder_text), ENT_QUOTES, 'UTF-8'))); + $grt_sal_node = $campaign_node->addChild("GreetingSalutation", htmlspecialchars(($params['cmp_grt_sal']), ENT_QUOTES, 'UTF-8')); + $grt_name_node = $campaign_node->addChild("GreetingName", htmlentities($params['cmp_grt_name'])); + $grt_str_node = $campaign_node->addChild("GreetingString", htmlspecialchars($params['cmp_grt_str'], ENT_QUOTES, 'UTF-8')); + $org_name_node = $campaign_node->addChild("OrganizationName", htmlspecialchars($params['cmp_org_name'], ENT_QUOTES, 'UTF-8')); + $org_addr1_node = $campaign_node->addChild("OrganizationAddress1", htmlspecialchars($params['cmp_org_addr1'], ENT_QUOTES, 'UTF-8')); + $org_addr2_node = $campaign_node->addChild("OrganizationAddress2", htmlspecialchars($params['cmp_org_addr2'], ENT_QUOTES, 'UTF-8')); + $org_addr3_node = $campaign_node->addChild("OrganizationAddress3", htmlspecialchars($params['cmp_org_addr3'], ENT_QUOTES, 'UTF-8')); + $org_city_node = $campaign_node->addChild("OrganizationCity", htmlspecialchars($params['cmp_org_city'], ENT_QUOTES, 'UTF-8')); + switch ($params['org_country']) { + case 'us': + $us_state = $params['org_state_us']; + break; + case 'ca': + $us_state = $params['org_state_us']; + break; + default: + $us_state = ''; + } + $org_state_us_node = $campaign_node->addChild("OrganizationState", htmlentities($us_state)); + switch ($params['org_country']) { + case 'us': + $international_state = ''; + break; + case 'ca': + $international_state = ''; + break; + default: + $international_state = htmlspecialchars($params['org_state'], ENT_QUOTES, 'UTF-8'); + } + $org_state_name = $campaign_node->addChild("OrganizationInternationalState", htmlentities($international_state)); + $org_country_node = $campaign_node->addChild("OrganizationCountry", htmlentities($params['org_country'])); + $org_zip_node = $campaign_node->addChild("OrganizationPostalCode", htmlspecialchars($params['org_zip'], ENT_QUOTES, 'UTF-8')); + $include_fwd_email = (!empty($params['cmp_forward']) && $params['cmp_forward'] == 'YES') + ? ('YES') + : ('NO'); + #$fwd_txt = ($include_fwd_email == 'YES') ? ($params['cmp_fwd_email']) :(''); + $fwd_txt = $params['cmp_fwd_email']; + $fwd_node = $campaign_node->addChild("IncludeForwardEmail", htmlentities($include_fwd_email)); + $fwd_email_node = $campaign_node->addChild("ForwardEmailLinkText", htmlspecialchars(($fwd_txt), ENT_QUOTES, 'UTF-8')); + $include_sub_link = (!empty($params['cmp_subscribe']) && $params['cmp_subscribe'] == 'YES') + ? ('YES') + : ('NO'); + $sub_node = $campaign_node->addChild("IncludeSubscribeLink", htmlentities($include_sub_link)); + #$sub_txt = ($include_sub_link == 'YES') ? ($params['cmp_sub_link']) : (''); + $sub_txt = $params['cmp_sub_link']; + $sub_link_node = $campaign_node->addChild("SubscribeLinkText", htmlspecialchars(($sub_txt), ENT_QUOTES, 'UTF-8')); + $email_format_node = $campaign_node->addChild("EmailContentFormat", $params['cmp_mail_type']); + if ($params['cmp_type'] != 'STOCK') { + $html_body_node = $campaign_node->addChild("EmailContent", htmlspecialchars($params['cmp_html_body'], ENT_QUOTES, 'UTF-8')); + $text_body_node = $campaign_node->addChild("EmailTextContent", "" . htmlspecialchars(strip_tags($params['cmp_text_body']), ENT_QUOTES, 'UTF-8') . ""); + $campaign_style_sheet = ($params['cmp_mail_type'] == 'XHTML') + ? ($params['cmp_style_sheet']) + : (''); + $style_sheet_node = $campaign_node->addChild("StyleSheet", htmlspecialchars($campaign_style_sheet, ENT_QUOTES, 'UTF-8')); + } + $campaignlists_node = $campaign_node->addChild("ContactLists"); + + if ($params['lists']) { + foreach ($params['lists'] as $list) { + $campaignlist_node = $campaignlists_node->addChild("ContactList"); + $campaignlist_node->addAttribute("id", $list); + $campaignlink_node = $campaignlist_node->addChild("link"); + $campaignlink_node->addAttribute("xmlns", "http://www.w3.org/2005/Atom"); + $campaignlink_node->addAttribute("href", str_replace("http://api.constantcontact.com", "", $list)); + $campaignlink_node->addAttribute("rel", "self"); + } + } + + $cmp_from_email = explode('|', $params['cmp_from_email']); + $fromemail_node = $campaign_node->addChild("FromEmail"); + $femail_node = $fromemail_node->addChild("Email"); + $femail_node->addAttribute("id", $cmp_from_email[1]); + $femail_node_link = $femail_node->addChild("link"); + $femail_node_link->addAttribute("xmlns", "http://www.w3.org/2005/Atom"); + $femail_node_link->addAttribute("href", str_replace("http://api.constantcontact.com", "", $cmp_from_email[1])); + $femail_node_link->addAttribute("rel", "self"); + $femail_addrs_node = $fromemail_node->addChild("EmailAddress", htmlentities($cmp_from_email[0])); + $cmp_reply_email = explode('|', $params['cmp_reply_email']); + $replyemail_node = $campaign_node->addChild("ReplyToEmail"); + $remail_node = $replyemail_node->addChild("Email"); + $remail_node->addAttribute("id", $cmp_reply_email[1]); + $remail_node_link = $remail_node->addChild("link"); + $remail_node_link->addAttribute("xmlns", "http://www.w3.org/2005/Atom"); + $remail_node_link->addAttribute("href", str_replace("http://api.constantcontact.com", "", $cmp_reply_email[1])); + $remail_node_link->addAttribute("rel", "self"); + $remail_addrs_node = $replyemail_node->addChild("EmailAddress", htmlentities($cmp_reply_email[0])); + $source_node = $xml_object->addChild("source"); + $sourceid_node = $source_node->addChild("id", $standard_id); //[3th *id] + $sourcetitle_node = $source_node->addChild("title", "Campaigns for customer: " . $this->login); + $sourcetitle_node->addAttribute("type", "text"); + $sourcelink1_node = $source_node->addChild("link"); + $sourcelink1_node->addAttribute("href", "campaigns"); //[2nd *href] + $sourcelink2_node = $source_node->addChild("link"); + $sourcelink2_node->addAttribute("href", "campaigns"); //[3th *href] + $sourcelink2_node->addAttribute("rel", "self"); + $sourceauthor_node = $source_node->addChild("author"); + $sauthor_name = $sourceauthor_node->addChild("name", $this->login); + $sourceupdate_node = $source_node->addChild("updated", htmlentities($update_date)); + + $entry = $xml_object->asXML(); + // $search = array('>', '\"', ' ', ' ', '"/>', '&', '&lt;', '�', '�'); + // $replace = array('>', '"', '', '', '" />', '&', '<', '&Yuml;', '&yuml;'); + // $entry = str_replace($search, $replace, $entry); + + if ($this->sent_recived_debug) { + echo "

    We sent the following XML:

    $entry

    "; + } + + return $entry; + } + +} diff --git a/Toolkit/LeadManager/Affiliates/StreamSend.php b/Toolkit/LeadManager/Affiliates/StreamSend.php new file mode 100755 index 0000000..8577319 --- /dev/null +++ b/Toolkit/LeadManager/Affiliates/StreamSend.php @@ -0,0 +1,212 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: StreamSend.php,v 1.5 2010/04/30 19:02:10 matrix Exp $ + * @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', 'false'); +/** + * 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', 'true'); +/** + * 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'); +/** + * URI for streamsend API + */ +define('STREAMSEND_BASE_URL', "https://app.streamsend.com"); + +/** + * Toolkit_Contacts_StreamSend + * + * Contact support class for inergration with StreamSend API + * + * @category Contacts + * @package LeadManager + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_LeadManager_Affiliates_StreamSend +{ + // {{{ Class Properties + + + /** + * Description for public + * @var boolean + * @access public + */ + public $debug = false; + + /** + * streamSendFields + * + * array with key values matching the gaslight contact tabel to the + * StreamSend field (normal fields) + * + * @var array + * @access protected + */ + protected $streamSendFields = array( + 'email' => 'email-address', + 'fname' => 'first-name', + 'lname' => 'last-name', + 'address' => 'address1', + 'address2' => 'address2', + 'city' => 'city', + 'state' => 'stateprovince', + 'zip' => 'postal-code', + 'phone' => 'phone-number', + 'interest' => 'interests', + 'contact_type' => 'contact-type' + ); + + /** + * contactInqTypes + * + * array with key values matching the gaslight contact_inq tabel to the + * StreamSend field (Radio fields) + * key = id from contact_inq table + * value = name from contact_inq_table + * value is same name as the StreamSend fieldname + * + * @var array + * @access protected + */ + protected $contactInqTypes = array(); + + /** + * booleanTypes + * + * StreamSend fields (boolean fields) an array of field names for the + * boolean field types + * + * @var array + * @access protected + */ + protected $booleanTypes = array(); + // }}} + // {{{ __construct() + + + /** + * __construct( + * + * @return void + * @access public + */ + public function __construct() + { + } + + + // }}} + // {{{ addContact() + + + /** + * addContact + * + * Given $values from a Toolkit_Contacts Form add Contact + * + * @param array $values Parameter description (if any) ... + * + * @return boolean Return true if successfull + * @access public + */ + public function addContact($values) + { + // check the array $values to make sure it is correct + if (is_array($values) && !empty($values)) { + include_once GLM_APP_BASE.'StreamSend/class_streamsend_api.inc'; + // initialize the streamsend object + $ss = new streamSend (STREAMSEND_BASE_URL, STREAMSEND_LOGIN_ID, + STREAMSEND_KEY); + $ss->debug = $this->debug; + $ret = $ss->contactSearch($values['email']); + + $contactData = array(); + $values[$type] = 1; + foreach ($this->streamSendFields as $glmName => $ssName) { + switch ($glmName) { + case "state": + $contactData[$ssName] = ($values[$glmName]) ? $GLOBALS['states'][$values[$glmName]]: ''; + break; + default: + $contactData[$ssName] = $values[$glmName]; + break; + } + } + foreach ($this->contactInqTypes as $contactInqId => $name) { + $slug = str_replace(" ", "-", strtolower($this->contactInqTypes[$contactInqId])); + if ($values['interest'][$contactInqId]) { + $contactData[$slug] = 'Yes'; + } else { + $contactData[$slug] = 'No'; + } + } + foreach ($this->booleanTypes as $name) { + if ($values[$name]) { + $contactData[$name] = 'Yes'; + } else { + $contactData[$name] = 'No'; + } + } + if ($ret->contact) { + $contacts = $ss->contactUpdate( + $ret->contact->id, + $contactData + ); + } else { + $contacts = $ss->contactCreate( + $contactData, + STREAMSEND_DEFAULT_ACTIVATE, + STREAMSEND_DEFAULT_DELIVER_ACTIVATION, + STREAMSEND_DEFAULT_DELIVER_WELCOME + ); + } + if (!$contacts) { + + // show errors if on development server + switch (GLM_HOST_ID) { + case "DEVELOPMENT": + echo "

    A total and complete failure occured."; + break; + case "PRODUCTION": + break; + } + } + if ($ss->debug == true) { + echo '

    Debug Results

    '.$ss->debugBuffer.'

    '; + } + return true; + } + return false; + } + + + // }}} +} +?> diff --git a/Toolkit/LeadManager/ConstantContact.php b/Toolkit/LeadManager/ConstantContact.php new file mode 100644 index 0000000..e609a1a --- /dev/null +++ b/Toolkit/LeadManager/ConstantContact.php @@ -0,0 +1,92 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +require_once BASE . 'Toolkit/LeadManager/Affiliates/ConstantContact.php'; +/** + * Require the Constant Contact Classes + */ +/** + * Toolkit_Package_ConstantContact + * + * Description of ConstantContact + * + * @category Toolkit + * @package LeadManager + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release SVN: $Id$ + * @link <> + */ +class Toolkit_LeadManager_ConstantContact + extends Toolkit_LeadManager_Observer +{ + /** + * Send LeadManager_Lead object (contact or customer) to ConstantContact + * + * @param type $subject Object Reference for LeadManager_Lead type + * + * @return void + */ + public function send(Toolkit_LeadManager_Lead $subject) + { + // have to convert the $subject Object to an array to be used + // in the streamsend call to addContact + $values = array( + 'email_address' => $subject->getEmail(), + 'first_name' => $subject->getFname(), + 'last_name' => $subject->getLname(), + 'city_name' => $subject->getCity(), + 'state_code' => $subject->getState(), + 'state_name' => $GLOBALS['states'][$subject->getState()], + 'zip_code' => $subject->getZip(), + 'home_number' => $subject->getPhone() + ); + if (is_a($subject, 'Toolkit_LeadManager_Contact')) { + $values['address_line_1'] = $subject->getAddress(); + $values['address_line_2'] = $subject->getAddress2(); + } else if (is_a($subject, 'Toolkit_LeadManager_Customer')) { + $values['address_line_1'] = $subject->getAdd1(); + $values['address_line_2'] = $subject->getAdd2(); + } + if (defined('CONSTANT_CONTACT_LIST') && CONSTANT_CONTACT_LIST) { + $lists = unserialize(CONSTANT_CONTACT_LIST); + } + $values["lists"] = $lists; + $ccContactOBJ = new CC_Contact(); + $constantContact = $ccContactOBJ->getSubscribers( + urlencode($values['email_address']) + ); + try { + if (!empty($constantContact['items'])) { + // update contact + $contactXML = $ccContactOBJ->createContactXML( + $constantContact['id'], + $values + ); + } else { + // add new contact to constant contact + $contactXML = $ccContactOBJ->createContactXML( + null, + $values + ); + $ccContactOBJ->addSubscriber($contactXML); + } + } catch(Exception $e) { + Toolkit_Common::handleError($e); + } + } +} diff --git a/Toolkit/LeadManager/Contact.php b/Toolkit/LeadManager/Contact.php new file mode 100644 index 0000000..523d503 --- /dev/null +++ b/Toolkit/LeadManager/Contact.php @@ -0,0 +1,292 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +/** + * Toolkit_Package_Contact + * + * Class Contact used for contact integration with Stream Send + * Contant Contact and Mail Chimp programs. + * + * @category Toolkit + * @package LeadManager + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release SVN: $Id$ + * @link <> + */ +class Toolkit_LeadManager_Contact + extends Toolkit_LeadManager_Lead +{ + public static $tableName = 'contact'; + public static $primaryKey = 'id'; + private $_id; + private $_address; + private $_address2; + private $_member_ok; + private $_members; + private $_gift_cer; + private $_comments; + private $_discover; + private $_password; + + /** + * Contructor for class Contact Objects + * + * @param type $values Array of Values to create object with + */ + public function __construct(Array $values) + { + parent::__construct($values); + extract($values); + $this->setAddress($address) + ->setAddress2($address2) + ->setComments($comments) + ->setDiscover($discover) + ->setGiftCert($gift_cert) + ->setMembers($members) + ->setMemberOk($member_ok) + ->setPassword($password); + if ($id) { + $this->setId($id); + } + } + + /** + * Creates a Contact class object with values given + * + * @param type $values Array of values for the contact + * + * @return Toolkit_Contacts_Admin_Contact + */ + public static function createByValues($values) + { + return new Toolkit_LeadManager_Contact($values); + } + + /** + * Returns the Contact Id + * + * @return type + */ + public function getId() + { + return $this->_id; + } + + /** + * sets the id of object + * + * @param Int $id set the id of object if not numeric throw Exception + * + * @return Toolkit_Table + */ + public function setId($id) + { + if (!is_numeric($id)) { + throw new Exception('id must be an integer'); + } + if (!$this->_id) { + $this->_id = $id; + } + return $this; + } + + /** + * Returns the Contact Address + * + * @return type + */ + public function getAddress() + { + return $this->_address; + } + + /** + * Sets the Contact Address + * + * @param type $address Cotnact Address + * + * @return Toolkit_Contacts_Admin_Contact + */ + public function setAddress($address) + { + $this->_address = $address; + return $this; + } + + /** + * Returns the Contact Address2 + * + * @return type + */ + public function getAddress2() + { + return $this->_address2; + } + + /** + * Sets the Contact Address2 + * + * @param type $address2 Contact Address2 + * + * @return Toolkit_Contacts_Admin_Contact + */ + public function setAddress2($address2) + { + $this->_address2 = $address2; + return $this; + } + + /** + * Returns the Contact Member OK + * + * @return type + */ + public function getMemberOk() + { + return $this->_member_ok; + } + + /** + * Sets the Contact Member OK + * + * @param type $member_ok Contacts Member Ok + * + * @return Toolkit_Contacts_Admin_Contact + */ + public function setMemberOk($member_ok) + { + $this->_member_ok = $member_ok; + return $this; + } + + /** + * Returns the Contact Member + * + * @return type + */ + public function getMembers() + { + return $this->_members; + } + + /** + * Sets the Contact Member + * + * @param type $members Contact Member + * + * @return Toolkit_Contacts_Admin_Contact + */ + public function setMembers($members) + { + $this->_members = $members; + return $this; + } + + /** + * Returns the Contact Gift Cert + * + * @return type + */ + public function getGiftCert() + { + return $this->_gift_cer; + } + + /** + * Sets the Contacts gift Cert + * + * @param type $gift_cert Contact gift_cert + * + * @return Toolkit_Contacts_Admin_Contact + */ + public function setGiftCert($gift_cert) + { + $this->_gift_cer = $gift_cert; + return $this; + } + + /** + * Returns the Contacts Comments + * + * @return type + */ + public function getComments() + { + return $this->_comments; + } + + /** + * Sets the Contacts Comments + * + * @param type $comments Contact Comments + * + * @return Toolkit_Contacts_Admin_Contact + */ + public function setComments($comments) + { + $this->_comments = $comments; + return $this; + } + + /** + * Returns Contacts Discover Field + * + * @return type + */ + public function getDiscover() + { + return $this->_discover; + } + + /** + * Sets the Contacts Discover field + * + * @param type $discover Contacts Discover field + * + * @return Toolkit_Contacts_Admin_Contact + */ + public function setDiscover($discover) + { + $this->_discover = $discover; + return $this; + } + + /** + * Returns the leads password + * + * @return type + */ + public function getPassword() + { + return $this->_password; + } + + /** + * Sets the leads password + * + * @param type $password led password + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setPassword($password) + { + $this->_password = $password; + return $this; + } + +} diff --git a/Toolkit/LeadManager/Customer.php b/Toolkit/LeadManager/Customer.php new file mode 100644 index 0000000..d8e28b9 --- /dev/null +++ b/Toolkit/LeadManager/Customer.php @@ -0,0 +1,461 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +/** + * Toolkit_Package_Customer + * + * Description of Customer + * + * @category Toolkit + * @package LeadManager + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release SVN: $Id$ + * @link <> + */ +class Toolkit_LeadManager_Customer + extends Toolkit_LeadManager_Lead +{ + public static $tableName = 'customer'; + public static $primaryKey = 'cust_id'; + private $_cust_id; + private $_userid; + private $_usernum; + private $_usergroup; + private $_add1; + private $_add2; + private $_org; + private $_access_date; + private $_purch_date; + private $_referred_by; + private $_promo; + private $_ship_type; + private $_club; + private $_wherefrom; + private $_addr_ext; + private $_salutation; + + /** + * Constructor for class Customer objects + * + * @param array $values Array of values + */ + public function __construct(array $values) + { + parent::__construct($values); + extract($values); + $this->setUserid($user_id) + ->setUsernum($usernum) + ->setUsergroup($usergroup) + ->setAdd1($add1) + ->setAdd2($add2) + ->setOrg($org) + ->setAccessDate($access_date) + ->setPurchDate($purch_date) + ->setReferredBy($referred_by) + ->setPromo($promo) + ->setShipType($ship_type) + ->setClub($club) + ->setWherefrom($wherefrom) + ->setAddrExt($addr_ext) + ->setSalutation($salutation); + if ($cust_id) { + $this->setCustId($cust_id); + } + } + + /** + * Creates a Contact class object with values given + * + * @param type $values Array of values for the contact + * + * @return Toolkit_Contacts_Admin_Contact + */ + public static function createByValues($values) + { + return new Toolkit_LeadManager_Customer($values); + } + + /** + * Returns cust_id + * + * @return type + */ + public function getCustId() + { + return $this->_cust_id; + } + + /** + * Sets the customer cust_id + * + * @param type $_cust_id Customer cust_id + * + * @return Toolkit_LeadManager_Customer + */ + public function setCustId($_cust_id) + { + $this->_cust_id = $_cust_id; + return $this; + } + + /** + * Returns Customer userid + * + * @return type + */ + public function getUserid() + { + return $this->_userid; + } + + /** + * Sets Customer userid + * + * @param type $_userid Customer Userid + * + * @return Toolkit_LeadManager_Customer + */ + public function setUserid($_userid) + { + $this->_userid = $_userid; + return $this; + } + + /** + * Returns Customer usernum + * + * @return type + */ + public function getUsernum() + { + return $this->_usernum; + } + + /** + * Sets Customer usernum + * + * @param type $_usernum Customer usernum + * + * @return Toolkit_LeadManager_Customer + */ + public function setUsernum($_usernum) + { + $this->_usernum = $_usernum; + return $this; + } + + /** + * Returns Customer Usergroup + * + * @return type + */ + public function getUsergroup() + { + return $this->_usergroup; + } + + /** + * Sets Customer usergroup + * + * @param type $_usergroup Customer usergroup + * + * @return Toolkit_LeadManager_Customer + */ + public function setUsergroup($_usergroup) + { + $this->_usergroup = $_usergroup; + return $this; + } + + /** + * Returns Customer add1 + * + * @return type + */ + public function getAdd1() + { + return $this->_add1; + } + + /** + * Sets Customer add1 + * + * @param type $_add1 Customer add1 + * + * @return Toolkit_LeadManager_Customer + */ + public function setAdd1($_add1) + { + $this->_add1 = $_add1; + return $this; + } + + /** + * Returns Customer add2 + * + * @return type + */ + public function getAdd2() + { + return $this->_add2; + } + + /** + * Sets Customer addr2 + * + * @param type $_add2 Customer add2 + * + * @return Toolkit_LeadManager_Customer + */ + public function setAdd2($_add2) + { + $this->_add2 = $_add2; + return $this; + } + + /** + * Returns Customer org + * + * @return type + */ + public function getOrg() + { + return $this->_org; + } + + /** + * Sets Customer org + * + * @param type $_org Customer org + * + * @return Toolkit_LeadManager_Customer + */ + public function setOrg($_org) + { + $this->_org = $_org; + return $this; + } + + /** + * Returns Customer access_date + * + * @return type + */ + public function getAccessDate() + { + return $this->_access_date; + } + + /** + * Sets Customer acces_date + * + * @param type $_access_date Customer access_date + * + * @return Toolkit_LeadManager_Customer + */ + public function setAccessDate($_access_date) + { + $this->_access_date = $_access_date; + return $this; + } + + /** + * Returns Customer purch_date + * + * @return type + */ + public function getPurchDate() + { + return $this->_purch_date; + } + + /** + * Sets Customer purch_date + * + * @param type $_purch_date Customer purch_date + * + * @return Toolkit_LeadManager_Customer + */ + public function setPurchDate($_purch_date) + { + $this->_purch_date = $_purch_date; + return $this; + } + + /** + * Returns Customer Referred_by + * + * @return type + */ + public function getReferredBy() + { + return $this->_referred_by; + } + + /** + * Sets Customer referred_by + * + * @param type $_referred_by Customer referred_by + * + * @return Toolkit_LeadManager_Customer + */ + public function setReferredBy($_referred_by) + { + $this->_referred_by = $_referred_by; + return $this; + } + + /** + * Returns Customer promo + * + * @return type + */ + public function getPromo() + { + return $this->_promo; + } + + /** + * Sets Customer promo + * + * @param type $_promo Customer promo + * + * @return Toolkit_LeadManager_Customer + */ + public function setPromo($_promo) + { + $this->_promo = $_promo; + return $this; + } + + /** + * Returns Customer ship_type + * + * @return type + */ + public function getShipType() + { + return $this->_ship_type; + } + + /** + * Sets Customer ship_type + * + * @param type $_ship_type Customer ship_type + * + * @return Toolkit_LeadManager_Customer + */ + public function setShipType($_ship_type) + { + $this->_ship_type = $_ship_type; + return $this; + } + + /** + * Returns Customer club + * + * @return type + */ + public function getClub() + { + return $this->_club; + } + + /** + * Sets Customer club + * + * @param type $_club Customer club + * + * @return Toolkit_LeadManager_Customer + */ + public function setClub($_club) + { + $this->_club = $_club; + return $this; + } + + /** + * Returns Customer wherefrom + * + * @return type + */ + public function getWherefrom() + { + return $this->_wherefrom; + } + + /** + * Sets Customer wherefrom + * + * @param type $_wherefrom Customer wherefrom + * + * @return Toolkit_LeadManager_Customer + */ + public function setWherefrom($_wherefrom) + { + $this->_wherefrom = $_wherefrom; + return $this; + } + + /** + * Returns Customer Addr_ext + * + * @return type + */ + public function getAddrExt() + { + return $this->_addr_ext; + } + + /** + * Sets Customer addr_ext + * + * @param type $_addr_ext Customer addr_ext + * + * @return Toolkit_LeadManager_Customer + */ + public function setAddrExt($_addr_ext) + { + $this->_addr_ext = $_addr_ext; + return $this; + } + + /** + * Returns Customer Salutation + * + * @return type + */ + public function getSalutation() + { + return $this->_salutation; + } + + /** + * Sets Customer salutation + * + * @param type $_salutation Customer Salutation + * + * @return Toolkit_LeadManager_Customer + */ + public function setSalutation($_salutation) + { + $this->_salutation = $_salutation; + return $this; + } + +} diff --git a/Toolkit/LeadManager/Lead.php b/Toolkit/LeadManager/Lead.php new file mode 100644 index 0000000..346cd43 --- /dev/null +++ b/Toolkit/LeadManager/Lead.php @@ -0,0 +1,659 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +/** + * Toolkit_Package_Lead + * + * Abstract class Lead used for contact integration with Stream Send + * Contant Contact and Mail Chimp programs. + * + * @category Toolkit + * @package LeadManager + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release SVN: $Id$ + * @link <> + */ +abstract class Toolkit_LeadManager_Lead + extends Toolkit_LeadManager_Subject +{ + private $_create_date; + private $_email; + private $_fname; + private $_lname; + private $_city; + private $_state; + private $_zip; + private $_country; + private $_phone; + private $_fax; + private $_user_agent; + private $_remote_addr; + private $_mail_ok; + private $_interest; + private $_contact_type; + + /** + * Constructor for Lead class objects + * + * @param type $values Array of Values for Lead + */ + public function __construct(Array $values) + { + extract($values); + $this->setCreateDate($create_date) + ->setEmail($email) + ->setFname($fname) + ->setLname($lname) + ->setCity($city) + ->setState($state) + ->setZip($zip) + ->setCountry($country) + ->setPhone($phone) + ->setFax($fax) + ->setUserAgent($user_agent) + ->setRemoteAddr($remote_addr) + ->setMailOk($mail_ok) + ->setInterest($interest) + ->setContactType($contact_type); + } + + /** + * Creates a Lead class object by passing in $values array + * into the Leads constructor method. Is static method + * + * @param type $values Array of values to create Lead with + * + * @return Toolkit_Contacts_Admin_Lead + */ + abstract static public function createByValues($values); + + /** + * Returns the Leads Create Date + * + * @return type + */ + public function getCreateDate() + { + return $this->_create_date; + } + + /** + * Sets the Leads Create Date + * + * @param type $create_date Leads Create Date + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setCreateDate($create_date) + { + $this->_create_date = $create_date; + return $this; + } + + /** + * Returs the Leads Email Address + * + * @return type + */ + public function getEmail() + { + return $this->_email; + } + + /** + * Sets the Leads Email Address + * + * @param type $email Leads email address + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setEmail($email) + { + $this->_email = $email; + return $this; + } + + /** + * Returns the Leads First Name + * + * @return type + */ + public function getFname() + { + return $this->_fname; + } + + /** + * Sets the Leads First Name + * + * @param type $fname Leads First Name + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setFname($fname) + { + $this->_fname = $fname; + return $this; + } + + /** + * Returns the Leads Last Name + * + * @return type + */ + public function getLname() + { + return $this->_lname; + } + + /** + * Sets the Leads Last Name + * + * @param type $lname Leads Last Name + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setLname($lname) + { + $this->_lname = $lname; + return $this; + } + + /** + * Returns the Leads city + * + * @return type + */ + public function getCity() + { + return $this->_city; + } + + /** + * Sets the Leads city + * + * @param type $city Leads city + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setCity($city) + { + $this->_city = $city; + return $this; + } + + /** + * Returns the Leads state + * + * @return type + */ + public function getState() + { + return $this->_state; + } + + /** + * Sets the Leads state + * + * @param type $state Leads state + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setState($state) + { + $this->_state = $state; + return $this; + } + + /** + * Returns the Leads zip code + * + * @return type + */ + public function getZip() + { + return $this->_zip; + } + + /** + * Sets the Leads zip code + * + * @param type $zip Leads Zip code + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setZip($zip) + { + $this->_zip = $zip; + return $this; + } + + /** + * Returns the Leads country + * + * @return type + */ + public function getCountry() + { + return $this->_country; + } + + /** + * Sets the Leads country + * + * @param type $country Leads country + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setCountry($country) + { + $this->_country = $country; + return $this; + } + + /** + * Returns the Leads phone number + * + * @return type + */ + public function getPhone() + { + return $this->_phone; + } + + /** + * Sets the Leads phone number + * + * @param type $phone Leads phone number + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setPhone($phone) + { + $this->_phone = $phone; + return $this; + } + + /** + * Returns the Leads fax number + * + * @return type + */ + public function getFax() + { + return $this->_fax; + } + + /** + * Sets the Leads fax number + * + * @param type $fax Leads fax number + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setFax($fax) + { + $this->_fax = $fax; + return $this; + } + + /** + * Returns the Leads user agent + * + * @return type + */ + public function getUserAgent() + { + return $this->_user_agent; + } + + /** + * Sets the Leads user agent + * + * @param type $user_agent Leads user agent + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setUserAgent($user_agent) + { + $this->_user_agent = $user_agent; + return $this; + } + + /** + * Returns the Leads remote address + * + * @return type + */ + public function getRemoteAddr() + { + return $this->_remote_addr; + } + + /** + * Sets the Leads remote address + * + * @param type $remote_addr Leads remote address + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setRemoteAddr($remote_addr) + { + $this->_remote_addr = $remote_addr; + return $this; + } + + /** + * Returns the Leads mail_ok + * + * @return type + */ + public function getMailOk() + { + return $this->_mail_ok; + } + + /** + * Sets the Leads mail_ok + * + * @param type $mail_ok Leads mail ok + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setMailOk($mail_ok) + { + $this->_mail_ok = $mail_ok; + return $this; + } + + /** + * Returns the Leads interests + * + * @return type + */ + public function getInterest() + { + return $this->_interest; + } + + /** + * Sets the leads interests + * + * @param type $interest Leads interest + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setInterest($interest) + { + $this->_interest = $interest; + return $this; + } + + /** + * Returns the leads contact type + * + * @return type + */ + public function getContactType() + { + return $this->_contact_type; + } + + /** + * Sets the leads contact type + * + * @param type $contact_type Leads contact type + * + * @return Toolkit_Contacts_Admin_Lead + */ + public function setContactType($contact_type) + { + $this->_contact_type = $contact_type; + return $this; + } + + /** + * Return primary key field value of table + * + * @return type + */ + public function getPrimaryKey() + { + $defaultVars = get_class_vars(get_class($this)); + $primaryKey + = ($defaultVars['primaryKey'] == 'cust_id') + ? 'CustId' + : ucfirst($defaultVars['primaryKey']); + $getPrimaryKey = "get$primaryKey"; + return $this->$getPrimaryKey(); + } + + /** + * Parse out the integer references for the interest into their + * string names + * + * @param PDO $dbh Database connection + * + * @return type + */ + public function getInterestsAsArray(PDO $dbh) + { + $interestArray = array(); + $interest = preg_replace('/^:|:$/', '', $this->_interest); + $intArray = explode(':', $interest); + if ($this->_interest && !empty($intArray)) { + try { + $sql = " + SELECT id,header + FROM contact_inq + WHERE id IN (".implode(',', $intArray).") + ORDER BY header"; + $stmt = $dbh->query($sql); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $interestArray[$row['id']] = $row['header']; + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + return $interestArray; + } + + /** + * Parse out the contact types and return array with their names + * + * @return type + */ + public function getContactTypesAsArray() + { + $contactTypesArray = array(); + $types = preg_replace('/^:|:$/', '', $this->_contact_type); + $typeArray = explode(':', $types); + if ($this->_contact_type && !empty($typeArray)) { + $conf = new Config(); + $root =& $conf->parseConfig( + BASE . 'Toolkit/Contacts/config.ini', + 'IniFile' + ); + // check for PEAR error + if (PEAR::isError($root)) { + Toolkit_Common::handleError($root); + } + $cTypes + = $root->getItem('section', 'contact_types') + ->toArray(); + foreach ($typeArray as $type) { + $contactTypesArray[$type] = $cTypes['contact_types'][$type]; + } + } + return $contactTypesArray; + } + + /** + * Checks the id of the object if it is set then calls update othervise + * calls insert function + * + * @param PDO $dbh Database connection + * @param boolean $saveNullFields To save nul fields or not + * + * @return viod + */ + public function save(PDO $dbh, $saveNullFields = true) + { + $id = $this->getPrimaryKey(); + if ($id) { + $this->update($dbh, $saveNullFields); + } else { + $this->insert($dbh); + } + $this->notify(); + } + + /** + * insert the object + * + * @param PDO $dbh Database Connection + * + * @return Toolkit_Table + */ + public function insert(PDO $dbh) + { + try { + $methods = get_class_methods(get_class($this)); + $values = array(); + if ($methods) { + $pattern = '/get(.*)/'; + foreach ($methods as $mName) { + if ( preg_match($pattern, $mName, $matches) + && !in_array( + $mName, + array( + 'getInterestsAsArray', + 'getContactTypesAsArray', + 'getPrimaryKey' + ) + ) + ) { + $func = create_function( + '$c', + 'return "_" . strtolower($c[1]);' + ); + $fieldName = preg_replace_callback( + '/([A-Z])/', + $func, + $matches[1] + ); + $fieldName = preg_replace('/^_/', '', $fieldName); + $values[$fieldName] = $this->$matches[0](); + } + } + } + $defaultVars = get_class_vars(get_class($this)); + $primaryKey = $defaultVars['primaryKey']; + $tableName = $defaultVars['tableName']; + unset($values[$primaryKey]); + $sql = Toolkit_Common::createSQLInsert( + $tableName, + array_keys($values) + ); + $sql .= " RETURNING $primaryKey"; + $stmt = Toolkit_Common::prepareQuery( + $dbh, + $tableName, + $sql, + $values + ); + $stmt->execute(); + $primaryKey + = ($primaryKey == 'cust_id') + ? 'custId' + : $primaryKey; + $setter = 'set'.ucfirst($primaryKey); + $this->$setter($stmt->fetchColumn()); + return $this; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * update the object + * + * @param PDO $dbh Database connection + * @param boolean $saveNullFields To save null fields or not + * + * @return Toolkit_Table + */ + public function update(PDO $dbh, $saveNullFields = true) + { + try { + $methods = get_class_methods(get_class($this)); + $values = array(); + if ($methods) { + $pattern = '/get(.*)/'; + foreach ($methods as $mName) { + if ( preg_match($pattern, $mName, $matches) + && !in_array( + $mName, + array( + 'getInterestsAsArray', + 'getContactTypesAsArray', + 'getPrimaryKey' + ) + ) + ) { + $func = create_function( + '$c', + 'return "_" . strtolower($c[1]);' + ); + $fieldName = preg_replace_callback( + '/([A-Z])/', + $func, + $matches[1] + ); + $fieldName = preg_replace('/^_/', '', $fieldName); + $fieldValue = $this->$matches[0](); + if (( $fieldValue === null && $saveNullFields) + || $fieldValue !== null + ) { + $values[$fieldName] = $fieldValue; + } + } + } + } + $defaultVars = get_class_vars(get_class($this)); + $primaryKey = $defaultVars['primaryKey']; + $tableName = $defaultVars['tableName']; + $sql = Toolkit_Common::createSQLUpdate( + $tableName, + array_keys($values), + array("$primaryKey = :$primaryKey") + ); + $stmt = Toolkit_Common::prepareQuery( + $dbh, + $tableName, + $sql, + $values + ); + $stmt->execute(); + return $this; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } +} diff --git a/Toolkit/LeadManager/Observer.php b/Toolkit/LeadManager/Observer.php new file mode 100644 index 0000000..6bdcb40 --- /dev/null +++ b/Toolkit/LeadManager/Observer.php @@ -0,0 +1,57 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +/** + * Toolkit_Package_Observer + * + * Description of Observer + * + * @category Toolkit + * @package LeadManager + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release SVN: $Id$ + * @link <> + */ +abstract class Toolkit_LeadManager_Observer +{ + /** + * abstract method send to be used to send the contact + * which is a Toolkit_LeadManager_Lead to appropiate wrapper + * + * @param Toolkit_LeadManager_Lead $subject Object Lead + * + * @return void + */ + abstract public function send(Toolkit_LeadManager_Lead $subject); + + /** + * Update method for the Observer Calls the send method. + * + * @param type $subject Observer Object Reference + * + * @return void + */ + public function update($subject) + { + // looks for an observer method with the send name + if (method_exists($this, 'send')) { + call_user_func_array(array($this, 'send'), array($subject)); + } + } + +} diff --git a/Toolkit/LeadManager/StreamSend.php b/Toolkit/LeadManager/StreamSend.php new file mode 100644 index 0000000..e34c472 --- /dev/null +++ b/Toolkit/LeadManager/StreamSend.php @@ -0,0 +1,69 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +/** + * Toolkit_Package_StreamSend + * + * StreamSend Observer pattern for LeadManager Contact class + * + * @category Toolkit + * @package LeadManager + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release SVN: $Id$ + * @link <> + */ +class Toolkit_LeadManager_StreamSend + extends Toolkit_LeadManager_Observer +{ + /** + * Send LeadManager_Lead object (contact or customer) to StreamSend + * + * @param type $subject Object Reference for LeadManager_Lead type + * + * @return void + */ + public function send(Toolkit_LeadManager_Lead $subject) + { + // have to convert the $subject Object to an array to be used + // in the streamsend call to addContact + $values = array( + 'email' => $subject->getEmail(), + 'fname' => $subject->getFname(), + 'lname' => $subject->getLname(), + 'city' => $subject->getCity(), + 'address' => $subject->getAddress(), + 'address2' => $subject->getAddress2(), + 'state' => $subject->getState(), + 'zip' => $subject->getZip(), + 'phone' => $subject->getPhone() + ); + + $contactTypes = $subject->getContactTypesAsArray(); + if ($contactTypes) { + $values['contact_type'] = implode('|', $contactTypes); + } + $interests + = $subject->getInterestsAsArray(Toolkit_Database::getInstance()); + if ($interests) { + $values['interest'] = implode('|', $interests); + } + // call the streamsends API to send contact to stream send + $streamSend = new Toolkit_LeadManager_Affiliates_StreamSend(); + $streamSend->addContact($values); + } +} diff --git a/Toolkit/LeadManager/Subject.php b/Toolkit/LeadManager/Subject.php new file mode 100644 index 0000000..7995f4b --- /dev/null +++ b/Toolkit/LeadManager/Subject.php @@ -0,0 +1,80 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +/** + * Toolkit_Package_Subject + * + * Description of Subject + * + * @category Toolkit + * @package LeadManager + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release SVN: $Id$ + * @link <> + */ +abstract class Toolkit_LeadManager_Subject +{ + protected $observers = array(); + + /** + * Sets the Observer into the observers array + * + * @param Toolkit_LeadManager_Observer $observer Observer object to add + * + * @return void + */ + public function attach(Toolkit_LeadManager_Observer $observer) + { + $i = array_search($observer, $this->observers); + if ($i === false) { + $this->observers[] = $observer; + } + } + + /** + * Unsets the Observer from the observers array + * + * @param Toolkit_LeadManager_Observer $observer Observer to delete + * + * @return void + */ + public function detach(Toolkit_LeadManager_Observer $observer) + { + if (!empty($this->observers)) { + $i = array_search($observer, $this->observers); + if ($i !== false) { + unset($this->observers[$i]); + } + } + } + + /** + * Call each Observers update method + * + * @return void + */ + public function notify() + { + if (!empty($this->observers)) { + foreach ($this->observers as $observer) { + $observer->update($this); + } + } + } + +} diff --git a/Toolkit/Logger.php b/Toolkit/Logger.php new file mode 100644 index 0000000..ede52f8 --- /dev/null +++ b/Toolkit/Logger.php @@ -0,0 +1,168 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Logger.php,v 1.6 2010/05/25 14:09:12 jamie Exp $ + * @link <> + * @see Log + */ + +/** + * Logging class used to handle system logs + */ +require_once 'Log.php'; + +/** + * Error handling logger for system + * + * @category Logger + * @package Toolkit_Logger + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see Log + */ +class Toolkit_Logger +{ + // {{{ &getLogger() + + /** + * Gets a concrete log subclass based on constant parameters set for server + * + * Define parameters in server setup block of bootstrap file + * + * @return Log concrete Log subclass + * @access public + * @static + */ + public static function &getLogger() + { + if (defined('ERROR_LOG_NAME') && constant('ERROR_LOG_NAME') != '') { + $errorLogName = constant('ERROR_LOG_NAME'); + } else { + $errorLogName = ''; + } + + $logger =& Log::singleton( + ERROR_LOG_TYPE, + $errorLogName, + constant('ERROR_LOG_IDENT'), + $GLOBALS['ERROR_LOG_CONF'], + constant('ERROR_LOG_LEVEL') + ); + + return $logger; + } + + // }}} + // {{{ errorHandler() + + /** + * User-defined error handler function + * + * handles errors in script. E_ERROR, E_WARNING, E_NOTICE are automatically + * logged when they occur. Fatal errors (E_ERROR) have a 404 page shown to + * user so script doesn't halt. + * + * @param int $errno Level of the error rasied + * @param string $errstr Error message + * @param string $errfile Filename that the error was raised in + * @param int $errline Line number the error was raised at + * @param Log $logger Logger to user for error loggin + * + * @return boolean false, allows the normal error handler to continue + * @access public + * @static + */ + public static function errorHandler( + $errno, + $errstr, + $errfile, + $errline, + $logger = null + ) { + if (!($logger instanceof Log)) { + $logger =& self::getLogger(); + } + + $msg = "$errstr in $errfile at line $errline"; + switch ($errno) { + case E_ERROR : + case E_USER_ERROR : + $logger->emerg($msg, PEAR_LOG_EMERG); + header("HTTP/1.0 404 Not Found"); + exit(1); + break; + + case E_WARNING : + CASE E_USER_WARNING : + $logger->warning($msg, PEAR_LOG_WARNING); + break; + + case E_NOTICE : + case E_USER_NOTICE : + $logger->notice($msg, PEAR_LOG_NOTICE); + break; + + default : + $logger->info($msg, PEAR_LOG_INFO); + break; + } + + return false; // let the normal error handler continue + } + + // }}} + // {{{ logException() + + /** + * Create a log for an exception + * + * @param string $type Type of error encountered that caused exception + * @param Exception $e Exception that was thrown + * + * @return void + * @static + */ + public static function logException($type, Exception $e) + { + $msg = $e->getMessage(); + $file = $e->getFile(); + $line = $e->getLine(); + + $lcType = strtolower($type); // uniformity in type when looking at log + $log = "[$lcType] $msg in $file at line $line"; + + $logger =& self::getLogger(); + + switch ($lcType) { + case 'db error' : + case 'invalid arg' : + case 'runtime error' : + $logger->emerg($log); + break; + + case 'image server' : + case 'file server' : + $logger->warning($log); + break; + + default : + $logger->err($log); + break; + } + } + + // }}} +} +?> diff --git a/Toolkit/NavigationAbstract.php b/Toolkit/NavigationAbstract.php new file mode 100644 index 0000000..7ff425d --- /dev/null +++ b/Toolkit/NavigationAbstract.php @@ -0,0 +1,89 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_NavigationAbstract + * + * Description of NavigationAbstract + * + * @category Toolkit + * @package None + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_NavigationAbstract +{ + // {{{ properties + + /** + * Default nav index + * @param integer + * @access protected + */ + protected $currIndex; + + /** + * page menu + * @param HTML_Menu + * @access protected + */ + protected $menu; + + /** + * menu rendering engine + * @param HTML_Menu_DirectRenderer + * @access protected + */ + protected $rEngine; + + // }}} + // {{{ renderPageNav() + + /** + * Render the page navigation that is defined in the navStructure + * + * @param array $navStructure Page navigation structure + * @param string $type Type of menu to render + * + * @return string Page navigation structure + * @access public + */ + public function renderPageNav(array $navStructure, $type) + { + $this->menu->setMenu($navStructure); + $this->menu->setMenuType($type); + + $this->setCurrentIndex(); + $this->setNavTemplates(); + + $this->menu->render($this->rEngine); + return $this->rEngine->toHtml(); + } + + // }}} + // {{{ setNavTemplates() + /** + * set nav templates + * + * @return void + */ + abstract protected function setNavTemplates(); + + // }}} +} +?> diff --git a/Toolkit/NavigationFactoryAbstract.php b/Toolkit/NavigationFactoryAbstract.php new file mode 100644 index 0000000..b260f12 --- /dev/null +++ b/Toolkit/NavigationFactoryAbstract.php @@ -0,0 +1,48 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +/** + * Toolkit_BaseControllerAbstract + * + * Generate a sitemap for the site + * need to remove members only pages and other pages you + * don't want viewed by public + * + * @category Toolkit + * @package Toolkit_NavigationFactoryAbstract + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +abstract class Toolkit_NavigationFactoryAbstract +{ + /** + * create side nav + * + * @return void + */ + abstract public function createSideNav(); + + /** + * create side nav + * + * @return void + */ + abstract public function createMainNav(); +} +?> diff --git a/Toolkit/PHPImageEditor/classes/phpimageeditor.php b/Toolkit/PHPImageEditor/classes/phpimageeditor.php new file mode 100644 index 0000000..1abe15b --- /dev/null +++ b/Toolkit/PHPImageEditor/classes/phpimageeditor.php @@ -0,0 +1,843 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + + + /* + Copyright 2008, 2009, 2010 Patrik Hultgren + + YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR. + OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT: + http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F + + This file is part of PHP Image Editor. + + PHP Image Editor is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + PHP Image Editor is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with PHP Image Editor. If not, see . + */ + + + //Requires + //PHP: 4.3 + //GD: 2.0.28 + + /*PHP FUNCTIONS REQUIRES THESE VERSIONS + getimagesize PHP 4 + image_type_to_mime_type PHP 4.3 + imagecopyresized PHP 4 + file_exists PHP 4 + copy PHP 4 + imagecreatetruecolor PHP 4.0.6, GD 2.0.1 + imagecopyresized PHP 4 + imagecopy PHP 4 + imagecreatefromjpeg PHP 4, GD 1.8 + imagecreatefromgif PHP 4, GD 2.0.28 + imagecreatefrompng PHP 4 + imagefilter PHP 5, GD + imagejpeg PHP 4, GD-1.8 + imagepng PHP 4 + imagegif PHP 4 + imagerotate PHP 4.3 GD + imagesx PHP 4 + imagesy PHP 4 + */ + + + /** + * Description of PHPImageEditor + * + * @category Toolkit + * @package PHPImageEditor/Classes + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class PHPImageEditor +{ + public $srcEdit = ""; + public $srcOriginal = ""; + public $srcPng = ""; + public $srcWorkWith = ""; + public $resourceWorkWith = false; + public $mimeType = ""; + public $actionSaveAndClose = "save"; + public $actionRotateLeft = "rotate:90"; + public $actionRotateRight = "rotate:-90"; + public $actionGrayscale = "grayscale"; + public $actionContrast = "contrast"; + public $actionBrightness = "brightness"; + public $actionUndo = "undo"; + public $actionUpdate = "update"; + public $actionRotateIsSelected = false; + public $actionRotate = ""; + public $actionSeparatorSign = "#"; + public $fieldNameKeepProportions = "keepproportions"; + public $errorMessages = array(); + public $formName = "phpimageeditor"; + public $inputImageName = ''; + public $inputWidth = -1; + public $inputHeight = -1; + public $inputCropLeft = 0; + public $inputCropRight = 0; + public $inputCropTop = 0; + public $inputCropBottom = 0; + public $inputKeepProportions = true; + public $inputCropKeepProportions = false; + public $inputCropKeepProportionsRatio = 1; + public $inputPanel = MENU_RESIZE; + public $inputLanguage = DEFUALT_LANGUAGE; + public $inputContrast = 0; + public $inputBrightness = 0; + public $inputContrastLast = 0; + public $inputBrightnessLast = 0; + public $inputGrayscale = false; + public $httpImageKey = "imagesrc"; + public $texts = array(); + public $actions = ""; + public $isPostBack = false; + public $isAjaxPost = false; + public $finalWidth = -1; + public $finalHeight = -1; + public $widthKeepProportions = -1; + public $heightKeepProportions = -1; + public $userId = ""; + + public $contrastMax = 100; + public $brightnessMax = 255; + + + function PHPImageEditor() + { + $this->LoadLanguage(); + + if (version_compare(phpversion(), PHP_VERSION_MINIMUM, "<")) + { + $this->errorMessages[] = phpversion()." ".$this->texts["OLD PHP VERSION"]." ".PHP_VERSION_MINIMUM; + return; + } + + $this->isPostBack = isset($_POST["actiontype"]); + + $srcEdit = ""; + + if ($_GET[$this->httpImageKey] != NULL) + { + $srcEdit = $_GET[$this->httpImageKey]; + } + + if ($srcEdit == "") + { + $this->errorMessages[] = $this->texts["NO PROVIDED IMAGE"]; + return; + } + + $this->srcEdit = urldecode($srcEdit); + $this->inputImageName = urlencode($_GET['image_name']); + + if (isset($_POST["userid"])) + $this->userId = $_POST["userid"]; + else + $this->userId = "_".time()."_".str_replace(".", "_", $_SERVER['REMOTE_ADDR']); + + $this->SetSrcOriginal(); + $this->SetSrcPng(); + $this->SetSrcWorkWith(); + + if (!file_exists($this->srcEdit)) + { + $this->errorMessages[] = $this->texts["IMAGE DOES NOT EXIST"]; + return; + } + + $info = getimagesize($this->srcEdit); + + if (!$info) + { + $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"]; + return; + } + + $this->mimeType = image_type_to_mime_type($info[2]); + + if ($this->mimeType == image_type_to_mime_type(IMAGETYPE_JPEG) || $this->mimeType == image_type_to_mime_type(IMAGETYPE_GIF) || $this->mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + if (!$this->isPostBack) + $this->SaveOriginal(); + + $this->resourceWorkWith = $this->CreateImage($this->srcOriginal); + $this->SavePng(); + copy($this->srcPng, $this->srcWorkWith); + + $this->resourceWorkWith = $this->CreateImage($this->srcPng); + } + else + { + $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"]; + return; + } + + $this->finalWidth = $this->GetWidth(); + $this->finalHeight = $this->GetHeight(); + $this->widthKeepProportions = $this->GetWidth(); + $this->heightKeepProportions = $this->GetHeight(); + + $this->GrantAllAccess($this->srcOriginal); + $this->GrantAllAccess($this->srcPng); + $this->GrantAllAccess($this->srcWorkWith); + + if ($this->isPostBack) + { + $this->actionRotateIsSelected = ($_POST["rotate"] != "-1"); + $this->actionRotate = $_POST["rotate"]; + $this->actions = $_POST["actions"]; + $this->isAjaxPost = ($_POST["isajaxpost"] == "true"); + +// $this->inputImageName = $_POST['image_name']; + $this->inputWidth = (int)$_POST["width"]; + $this->inputHeight = (int)$_POST["height"]; + $this->inputCropLeft = (int)$_POST["cropleft"]; + $this->inputCropRight = (int)$_POST["cropright"]; + $this->inputCropTop = (int)$_POST["croptop"]; + $this->inputCropBottom = (int)$_POST["cropbottom"]; + $this->inputPanel = (int)$_POST["panel"]; + $this->inputLanguage = $_POST["language"]; + $this->inputKeepProportions = ($_POST["keepproportionsval"] == "1"); + $this->inputCropKeepProportions = ($_POST["cropkeepproportionsval"] == "1"); + $this->inputCropKeepProportionsRatio = (float)$_POST["cropkeepproportionsratio"]; + $this->inputGrayscale = ($_POST["grayscaleval"] == "1"); + $this->inputBrightness = (int)$_POST["brightness"]; + $this->inputContrast = (int)$_POST["contrast"]; + $this->inputBrightnessLast = (int)$_POST["brightnesslast"]; + $this->inputContrastLast = (int)$_POST["contrastlast"]; + + $this->Action($_POST["actiontype"]); + } + } + + function LoadLanguage() + { + $language = ""; + + if (isset($_POST["language"])) + { + $this->inputLanguage = $_POST["language"]; + $language = $this->inputLanguage; + } + else if (isset($_GET["language"])) + { + $this->inputLanguage = $_GET["language"]; + $language = $this->inputLanguage; + } + else + $language = DEFUALT_LANGUAGE; + + $tryLanguage = "language/".$language."/".$language.".com_admin.ini"; + if (file_exists($tryLanguage)) + $this->texts = PIE_GetTexts("language/".$language."/".$language.".com_admin.ini"); + else + $this->texts = PIE_GetTexts("language/".DEFUALT_LANGUAGE."/".DEFUALT_LANGUAGE.".com_admin.ini"); + } + + function SetSrcOriginal() + { + $arr = explode("/", $this->srcEdit); + $this->srcOriginal = IMAGE_ORIGINAL_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + } + + function SetSrcWorkWith() + { + $arr = explode("/", $this->srcEdit); + $srcWorkWith = IMAGE_WORK_WITH_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + $srcWorkWith = substr($srcWorkWith, 0, strripos($srcWorkWith, ".")).".png"; + $this->srcWorkWith = $srcWorkWith; + } + + function SetSrcPng() + { + $arr = explode("/", $this->srcEdit); + $srcPng = IMAGE_PNG_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + $srcPng = substr($srcPng, 0, strripos($srcPng, ".")).".png"; + $this->srcPng = $srcPng; + } + + function SaveOriginal() + { + copy($this->srcEdit, $this->srcOriginal); + + //Resize to fit in max width/height. + $imageTmp = $this->CreateImage($this->srcOriginal); + $finalWidth = $this->GetWidthFromImage($imageTmp); + $finalHeight = $this->GetHeightFromImage($imageTmp); + + $doSave = false; + + if ($finalWidth > IMAGE_MAX_WIDTH) + { + $widthProp = IMAGE_MAX_WIDTH/$finalWidth; + $finalWidth = IMAGE_MAX_WIDTH; + $finalHeight = round($finalHeight*$widthProp); + $doSave = true; + } + + if ($finalHeight > IMAGE_MAX_HEIGHT) + { + $heightProp = IMAGE_MAX_HEIGHT/$finalHeight; + $finalHeight = IMAGE_MAX_HEIGHT; + $finalWidth = round($finalWidth*$heightProp); + $doSave = true; + } + + if ($doSave) + { + $imageTmp = $this->ActionResize($finalWidth, $finalHeight, $imageTmp); + $this->SaveImage($imageTmp, $this->srcOriginal); + } + } + + function SavePng() + { + $this->SaveImage($this->resourceWorkWith, $this->srcPng, image_type_to_mime_type(IMAGETYPE_PNG)); + } + + function ErrorHasOccurred() + { + return (count($this->errorMessages) > 0); + } + + function GetWidthFinal() + { + return $this->finalWidth; + } + + function GetHeightFinal() + { + return $this->finalHeight; + } + + function GetWidth() + { + return $this->GetWidthFromImage($this->resourceWorkWith); + } + + function GetWidthLast() + { + if ($this->isPostBack) + return (int)$_POST["widthlast"]; + + return $this->GetWidth(); + } + + function GetHeight() + { + return $this->GetHeightFromImage($this->resourceWorkWith); + } + + function GetHeightLast() + { + if ($this->isPostBack) + return (int)$_POST["heightlast"]; + + return $this->GetWidth(); + } + + function GetImageNameFinal() + { + if ($this->isPostBack) + return $_POST["image_name"]; + + return $this->inputImageName; + } + + function getImageName() + { + return $this->inputImageName; + } + + function GetWidthFromImage($image) + { + return imagesx($image); + } + + function GetHeightFromImage($image) + { + return imagesy($image); + } + + function Action($actionType) + { + $doSave = false; + + if ($actionType == $this->actionUndo) { + $this->ActionUndo(); + $doSave = true; + } + + if ( $actionType == $this->actionUpdate + || $actionType == $this->actionSaveAndClose) { + if ( $this->inputWidth != $this->GetWidthLast() + || $this->inputHeight != $this->GetHeightLast()) { + $this->actions .= $this->GetActionSeparator()."resize:".$this->inputWidth.",".$this->inputHeight; + } + + if ( $this->inputCropLeft != 0 || $this->inputCropRight != 0 + || $this->inputCropTop != 0 || $this->inputCropBottom != 0) { + $this->actions + .= $this->GetActionSeparator() + ."crop:".$this->inputCropLeft."," + .$this->inputCropRight."," + .$this->inputCropTop."," + .$this->inputCropBottom; + } +// var_dump($this->inputImageName); +// var_dump($this->getImageNameFinal()); +// var_dump($_POST); +// var_dump($_GET); +// exit; + if (urldecode($this->inputImageName) != $this->GetImageNameFinal()) { + $this->actions .= $this->GetActionSeparator ()."imageName:".$this->GetImageNameFinal(); + } + $doSave = true; + } + + if ($actionType == $this->actionUpdate && $this->inputGrayscale) { + if (strpos($this->actions, $this->actionGrayscale) === false) { + $this->actions .= $this->GetActionSeparator().$this->actionGrayscale.":0"; + $doSave = true; + } + } else if ($actionType == $this->actionUpdate && !$this->inputGrayscale) { + if (!(strpos($this->actions, $this->actionGrayscale) === false)) { + $this->actions = str_replace($this->actionGrayscale.":0".$this->GetActionSeparator(), "", $this->actions); + $this->actions = str_replace($this->GetActionSeparator().$this->actionGrayscale.":0", "", $this->actions); + $this->actions = str_replace($this->actionGrayscale.":0", "", $this->actions); + $doSave = true; + } + } + + if ($this->inputContrast != $this->inputContrastLast) { + $this->actions .= $this->GetActionSeparator().$this->actionContrast.":".$this->inputContrast; + $doSave = true; + } + + if ($this->inputBrightness != $this->inputBrightnessLast) { + $this->actions .= $this->GetActionSeparator().$this->actionBrightness.":".$this->inputBrightness; + $doSave = true; + } + + if ($this->actionRotateIsSelected) { + if ($this->actionRotate == $this->actionRotateLeft) { + $this->actions .= $this->GetActionSeparator().$this->actionRotateLeft; + $doSave = true; + } else if ($this->actionRotate == $this->actionRotateRight) { + $this->actions .= $this->GetActionSeparator().$this->actionRotateRight; + $doSave = true; + } + } + + $finalContrast = 0; + $finalBrightness = 0; + $finalContrastFound = false; + $finalBrightnessFound = false; + $finalGrayscale = false; + + if ($doSave && $this->actions != "") { + $allActions = explode($this->actionSeparatorSign, $this->actions); + + $finalRotate = 0; + $finalCropLeft = 0; + $finalCropRight = 0; + $finalCropTop = 0; + $finalCropBottom = 0; + + $doSwitch = false; + + foreach ($allActions as $loopAction) { + $actionDetail = explode(":", $loopAction); + $actionValues = explode(",", $actionDetail[1]); + + if ($actionDetail[0] == "resize") { + $this->finalWidth = (int)$actionValues[0]; + $this->finalHeight = (int)$actionValues[1]; + } else if ($actionDetail[0] == "crop") { + $actionValueLeft = (int)$actionValues[0]; + $actionValueRight = (int)$actionValues[1]; + $actionValueTop = (int)$actionValues[2]; + $actionValueBottom = (int)$actionValues[3]; + + $widthProp = 1; + $heightProp = 1; + + if ($doSwitch) { + $widthProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalWidth); + $heightProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalHeight); + } else { + $widthProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalWidth); + $heightProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalHeight); + } + + $cropLeft = $actionValueLeft * $widthProp; + $cropRight = $actionValueRight * $widthProp; + $cropTop = $actionValueTop * $heightProp; + $cropBottom = $actionValueBottom * $heightProp; + + $cropValues = array(); + $cropValues[] = $cropRight; + $cropValues[] = $cropBottom; + $cropValues[] = $cropLeft; + $cropValues[] = $cropTop; + + if ($finalRotate != 0) + $cropValues = $this->RotateArray(($finalRotate/-90), $cropValues); + + $finalCropRight += $cropValues[0]; + $finalCropBottom += $cropValues[1]; + $finalCropLeft += $cropValues[2]; + $finalCropTop += $cropValues[3]; + + $this->finalWidth -= ($actionValueLeft + $actionValueRight); + $this->finalHeight -= ($actionValueTop + $actionValueBottom); + } else if ($actionDetail[0] == $this->actionGrayscale && $this->inputGrayscale) { + $finalGrayscale = true; + } else if ($actionDetail[0] == "contrast") { + $finalContrastFound = true; + $finalContrast = $actionValues[0]; + } else if ($actionDetail[0] == "brightness") { + $finalBrightnessFound = true; + $finalBrightness = $actionValues[0]; + } else if ($actionDetail[0] == "rotate") { + $finalRotate += (int)$actionValues[0]; + $finalWidthTmp = $this->finalWidth; + $this->finalWidth = $this->finalHeight; + $this->finalHeight = $finalWidthTmp; + } + + if ($finalRotate == -360 || $finalRotate == 360) { + $finalRotate = 0; + } + + $doSwitch = ($finalRotate != 0 && ($finalRotate == 90 || $finalRotate == 270 || $finalRotate == -90 || $finalRotate == -270)); + } + + //1. All effects. + if ($finalGrayscale) { + $this->ActionGrayscale(); + } + + if ($finalBrightnessFound) { + $this->ActionBrightness($finalBrightness); + } + + if ($finalContrastFound) { + $this->ActionContrast($finalContrast*-1); + } + + //2. Do cropping. + $finalCropLeft = round($finalCropLeft); + $finalCropRight = round($finalCropRight); + $finalCropTop = round($finalCropTop); + $finalCropBottom = round($finalCropBottom); + if ($finalCropLeft != 0 || $finalCropRight != 0 || $finalCropTop != 0 || $finalCropBottom != 0) { + $this->ActionCrop($finalCropLeft, $finalCropRight, $finalCropTop, $finalCropBottom); + } + + //3. Rotate + if ($finalRotate != 0) { + $this->ActionRotate($finalRotate); + } + + //Calculate keep proportions values. + if (round($this->finalWidth/$this->finalHeight,1) == round($this->GetWidth()/$this->GetHeight(),1)) { + //It seems to have the same proportions as the original. Use the original proportions value. + $this->widthKeepProportions = $this->GetWidth(); + $this->heightKeepProportions = $this->GetHeight(); + } else { + //The proportions has been changed. Use the new width and height instead. + $this->widthKeepProportions = $this->finalWidth; + $this->heightKeepProportions = $this->finalHeight; + } + + //4. Resize + if ($this->finalWidth > 0 && $this->finalHeight > 0) + $this->resourceWorkWith = $this->ActionResize($this->finalWidth, $this->finalHeight, $this->resourceWorkWith); + + $this->SaveImage($this->resourceWorkWith, $this->srcWorkWith, image_type_to_mime_type(IMAGETYPE_PNG)); + } + + $this->inputBrightness = $finalBrightness; + $this->inputContrast = $finalContrast; + $this->inputGrayscale = $finalGrayscale; + + if ($actionType == $this->actionSaveAndClose) { + $this->SaveImage($this->resourceWorkWith, $this->srcEdit, $this->mimeType); + + /*** GLM stuff ***/ + require_once '../../setup.phtml'; + $CKUpdater = new Toolkit_CKImages_ImageUpdater(Toolkit_Database::getInstance()); + $CKUpdater->load(basename($_GET['imagesrc'])); + $CKUpdater->update(new Toolkit_FileServer_ImageAdapter()); + /*****************/ + + unlink($this->srcOriginal); + unlink($this->srcPng); + unlink($this->srcWorkWith); + $this->DeleteOldImages(IMAGE_ORIGINAL_PATH); + $this->DeleteOldImages(IMAGE_PNG_PATH); + $this->DeleteOldImages(IMAGE_WORK_WITH_PATH); + $reloadParentBrowser = RELOAD_PARENT_BROWSER_ON_SAVE ? 'window.opener.location.reload();' : ''; + PIE_Echo(''); + } + } + + function ActionResize($width, $height, $image) + { + $newImage = @imagecreatetruecolor($width, $height); + imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $this->GetWidthFromImage($image), $this->GetHeightFromImage($image)); + return $newImage; + } + + function ActionCrop($cropLeft, $cropRight, $cropTop, $cropBottom) + { + $cropWidth = $this->GetWidth() - $cropLeft - $cropRight; + $cropHeight = $this->GetHeight() - $cropTop - $cropBottom; + + $newImageCropped = @imagecreatetruecolor($cropWidth, $cropHeight); + imagecopy($newImageCropped, $this->resourceWorkWith, 0, 0, $cropLeft, $cropTop, $cropWidth, $cropHeight); + + $this->resourceWorkWith = $newImageCropped; + } + + function ActionUndo() + { + $separatorPos = strrpos($this->actions, $this->actionSeparatorSign); + if (!($separatorPos === false)) + { + $this->actions = substr($this->actions, 0, $separatorPos); + } + else + { + $this->actions = ""; + } + } + + function CreateImage($srcEdit) + { + $info = getimagesize($srcEdit); + + if (!$info) + return NULL; + + $mimeType = image_type_to_mime_type($info[2]); + + if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG)) + { + return imagecreatefromjpeg($srcEdit); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF)) + { + return imagecreatefromgif($srcEdit); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + return imagecreatefrompng($srcEdit); + } + + return NULL; + } + + function ActionRotate($Degrees) + { + $this->resourceWorkWith = imagerotate($this->resourceWorkWith, $Degrees, 0); + } + + function ActionGrayscale() + { + imagefilter($this->resourceWorkWith, IMG_FILTER_GRAYSCALE); + } + + function ActionContrast($contrast) + { + //-100 = max contrast, 0 = no change, +100 = min contrast + imagefilter($this->resourceWorkWith, IMG_FILTER_CONTRAST, $contrast); + } + + function ActionBrightness($light) + { + //-255 = min brightness, 0 = no change, +255 = max brightness + imagefilter($this->resourceWorkWith, IMG_FILTER_BRIGHTNESS, $light); + } + + function GetErrorMessages() + { + if (count($this->errorMessages)) + { + PIE_Echo('
    '); + PIE_Echo('
      '); + + foreach ($this->errorMessages as $errorMessage) + PIE_Echo ('
    • '.$errorMessage.'
    • '); + + PIE_Echo("
    "); + PIE_Echo('
    '); + } + } + + function GetActions() + { + PIE_Echo($this->actions); + } + + function GetActionSeparator() + { + if ($this->actions != "") + return $this->actionSeparatorSign; + + return ""; + } + + function SaveImage($image, $toSrc, $mimeType = -1) + { + if ($mimeType == -1) + $mimeType = $this->mimeType; + + if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG)) + { + imagejpeg($image, $toSrc); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF)) + { + imagegif($image, $toSrc); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + imagepng($image, $toSrc); + } + } + + function CleanUp() + { + if ($this->resourceWorkWith) + imagedestroy($this->resourceWorkWith); + } + + function RotateArray($numberOfSteps, $arr) + { + $finalArray = array(); + + //-3 to 3 + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 0)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 1)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 2)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 3)]; + + return $finalArray; + } + + function NumberOfStepsCalculator($sum) + { + $maxIndex = 3; + if ($sum > $maxIndex) + return ($sum-$maxIndex)-1; + else if ($sum < 0) + { + return ($sum+$maxIndex)+1; + } + + return $sum; + } + + function AddUserIdToImageSrc($imageSrc) + { + return str_replace(".", $this->userId.".", $imageSrc); + } + + function IsPHP5OrHigher() + { + return version_compare(phpversion(), "5", ">="); + } + + function GetFormAction() + { + return "index.php?" + . $this->httpImageKey . "=" . $this->srcEdit + . '&image_name=' . $this->inputImageName; + } + + function GetWidthKeepProportions() + { + return $this->widthKeepProportions; + } + + function GetHeightKeepProportions() + { + return $this->heightKeepProportions; + } + + function DeleteOldImages($srcdir) + { + if($curdir = opendir($srcdir)) + { + while($file = readdir($curdir)) + { + if($file != '.' && $file != '..') + { + //$srcfile = $srcdir . '\\' . $file; + //$srcfile = $srcdir.'/'.$file; + $srcfile = $srcdir.$file; + $srcfileLower = strtolower($srcfile); + + if (stripos($srcfile, ".svn") === false) + { + if(is_file($srcfile)) + { + $doDelete = true; + + if (substr_count($srcfile, "sample.jpg") > 0 || substr_count($srcfile, "sample.png") > 0 || (substr_count($srcfileLower, ".jpg") == 0 && substr_count($srcfileLower, ".gif") == 0 && substr_count($srcfileLower, ".png") == 0)) + $doDelete = false; + + if ($doDelete) + { + + $deleteTime = mktime(0, 0, 0, date("m"), date("d")-2, date("Y")); + if (fileatime($srcfile) < $deleteTime) + { + //Image is old and will be deleted. Or else the server space will be filled up with not needed images. + //echo "

    DELETE $srcfile".date("F d Y H:i:s.", fileatime($srcfile))."

    "; + unlink($srcfile); + } + } + } + } + } + } + closedir($curdir); + } + } + + function GrantAllAccess($fileName) + { + chmod($fileName, 0777); + } + } +?> diff --git a/Toolkit/PHPImageEditor/config.php b/Toolkit/PHPImageEditor/config.php new file mode 100644 index 0000000..2714cb2 --- /dev/null +++ b/Toolkit/PHPImageEditor/config.php @@ -0,0 +1,33 @@ +. + */ + + + define("IMAGE_MAX_WIDTH", 700); + define("IMAGE_MAX_HEIGHT", 500); + define("DEFUALT_LANGUAGE", "en-GB"); + define("RELOAD_PARENT_BROWSER_ON_SAVE", true); + define("AJAX_POST_TIMEOUT_MS", 20000); +?> diff --git a/Toolkit/PHPImageEditor/css/jquery.jcrop.css b/Toolkit/PHPImageEditor/css/jquery.jcrop.css new file mode 100644 index 0000000..da9bffb --- /dev/null +++ b/Toolkit/PHPImageEditor/css/jquery.jcrop.css @@ -0,0 +1,45 @@ +/* Fixes issue here http://code.google.com/p/jcrop/issues/detail?id=1 */ +.jcrop-holder +{ + text-align: left; +} + +.jcrop-vline, .jcrop-hline +{ + font-size: 0; + position: absolute; + background: white url('../images/jcrop.gif') top left repeat; + /* + opacity: .5; + *filter:alpha(opacity=50); + */ +} +.jcrop-vline { height: 100%; width: 1px !important; } +.jcrop-hline { width: 100%; height: 1px !important; } +.jcrop-handle { + font-size: 1px; + width: 7px !important; + height: 7px !important; + border: 1px #eee solid; + background-color: #333; + *width: 9px; + *height: 9px; +} + +.jcrop-tracker { + *background-color: gray; + width: 100%; height: 100%; +} + +.custom .jcrop-vline, +.custom .jcrop-hline +{ + background: yellow; +} +.custom .jcrop-handle +{ + border-color: black; + background-color: #C7BB00; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; +} \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/css/style.css b/Toolkit/PHPImageEditor/css/style.css new file mode 100644 index 0000000..94976f4 --- /dev/null +++ b/Toolkit/PHPImageEditor/css/style.css @@ -0,0 +1,228 @@ +body +{ + margin: 0; + padding: 0; + font-family: Arial; + font-size: 80%; +} + +form +{ + margin: 0; + padding: 0; + background-color: #ffffff; +} + +label +{ + display: block; +} + +label.checkbox +{ + display: inline; +} + +div.field +{ + clear: both; + padding: 17px; +} + +div.col-1, +div.col-2 +{ + float: left; +} + +div.col-1 +{ + margin-right: 10px; +} + +input.checkbox +{ +} + +input.input-number +{ + width: 70px; + margin-bottom: 10px; + border: 1px solid #cbcbcb; + background-color: #ffffff; +} + +.main-actions +{ + background-color: #eaeaea; + border-top: 1px solid white; + border-bottom: 1px solid #d6d6d6; + padding: 0 10px 0 10px; + padding: 12px 10px 12px 10px; +} + +#editimage +{ + margin: 0 10px 10px 10px; + position: relative; + top: 0px; + left: 0px; +} + +div.error, +div.info +{ + background-color: #ffc1c1; + padding: 5px; + margin: 0 10px 10px 10px; +} + +div.error ul, +div.info ul +{ + list-style-type: square; +} + +div.error li, +div.info li +{ + font-weight: bold; + margin-bottom: 5px; +} + +div.croparea +{ + background-color: #ffffff; + filter:alpha(opacity=80); + -moz-opacity:.80; + opacity:.80; + overflow: hidden; +} + +div#actionContainer +{ + background-color: #e1f3ff; + background-image: url('../images/tab_body.png'); + background-repeat: repeat-x; +} + +div#menu +{ + height: 30px; + overflow: hidden; + font-weight: bold; +} + +.selected +{ + float: left; + color: #000000; + border-right: 1px solid #ffffff; + line-height: 30px; + padding: 0 20px 0 20px; + cursor: pointer; + height: 30px; + background-image: url('../images/tab_selected.png'); + background-repeat: repeat-x; +} + +.not-selected +{ + float: left; + color: #ffffff; + border-right: 1px solid #ffffff; + border-bottom: 1px solid #ffffff; + line-height: 30px; + padding: 0 20px 0 20px; + cursor: pointer; + height: 29px; + background-image: url('../images/tab_not_selected.png'); + background-repeat: repeat-x; +} + +.panel +{ + filter:alpha(opacity=0); + -moz-opacity:0; + opacity:0; + display: none; +} + +.tabs +{ + margin: 10px; +} + +.widthAndHeight +{ + height: 23px; + overflow: hidden; +} + +#image +{ + position: absolute; + top: 0; + left: 0; +} + +#loading +{ + border-top: 1px solid white; + background-color: #c7e7fc; + padding: 15px; + font-weight: bold; +} + +#loading_bar +{ + margin-top: 3px; + background-color: #3d7ab0; + height: 3px; +} + +#imageResizerKeepProportions, +#imageResizerNoProportions +{ + background-color: #d6d6d6; + position: absolute; + left: 0px; + top: 0px; + filter:alpha(opacity=0); + -moz-opacity:.0; + opacity:.0; +} + +.help +{ + background-color: #fffcd1; + line-height: 1.5em; + padding: 10px; + border: 1px solid #d8d8d8; +} + +.help-header +{ + font-weight: bold; + text-transform: uppercase; +} + +.help-content +{ +} + +#crophelp +{ +} + +.crop-settings +{ + background-color: #cde3f2; +} + +.crop-top +{ + border-bottom: 1px solid #a8c6da; + padding-bottom: 8px; + margin-bottom: 8px; +} \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/css/ui.resizable.css b/Toolkit/PHPImageEditor/css/ui.resizable.css new file mode 100644 index 0000000..44efeb2 --- /dev/null +++ b/Toolkit/PHPImageEditor/css/ui.resizable.css @@ -0,0 +1,13 @@ +/* Resizable +----------------------------------*/ +.ui-resizable { position: relative;} +.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block;} +.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } +.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0px; } +.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0px; } +.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0px; height: 100%; } +.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0px; height: 100%; } +.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } +.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } +.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } +.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;} \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/css/ui.slider.css b/Toolkit/PHPImageEditor/css/ui.slider.css new file mode 100644 index 0000000..5d47af0 --- /dev/null +++ b/Toolkit/PHPImageEditor/css/ui.slider.css @@ -0,0 +1,19 @@ +/* Slider +----------------------------------*/ +.ui-slider { position: relative; text-align: left; top: 15px; } +.ui-slider .ui-slider-handle { background: url(../images/slider_pointer.gif) 0 0 no-repeat; position: absolute; z-index: 2; width: 11px; height: 17px; cursor: default; background-color: none; border: 0; } +.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: 1%; display: block; border: 0; } + + + +.ui-slider-horizontal { background: url(../images/slider_track.gif) 0 0 repeat-x; height: 7px; background-color: none; border: 0; width: 401px;} +.ui-slider-horizontal .ui-slider-handle { top: -.6em; margin-left: -5px; } +.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } +.ui-slider-horizontal .ui-slider-range-min { left: 0; } +.ui-slider-horizontal .ui-slider-range-max { right: 0; } + +.ui-slider-vertical { width: .8em; height: 100px; } +.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } +.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } +.ui-slider-vertical .ui-slider-range-min { bottom: 0; } +.ui-slider-vertical .ui-slider-range-max { top: 0; } \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/images/crop_view.png b/Toolkit/PHPImageEditor/images/crop_view.png new file mode 100644 index 0000000000000000000000000000000000000000..3589e8b8346c07208748d175ccce03e8f523fdaa GIT binary patch literal 931 zcmV;U16=%xP)`t{ipc zs4GWZIaKPNPv3sFE!y+<-+v(c{OzZh3fdO$<>FuiGHmn|{cW@d#+7_r?9!tAK&RkR zu5ic7XC*2PRyZs2nd zFr20p1+lU)V@d&oIV;d=u;g)IXjMd`r#xT)16@A=B@r;AymUVG$HIOE`jdju0GFlbHGWiZtM^#V-*nnT+dfBWfMM8o3l z z%7C$)-M5ycAbh@|o@)JZJh4xCEK|96hAZ~bVtKUXMg%Adw_ni^i`nl6iU7rdvIE?5 zBba-DO^wn>2Vl)aYVIN6%I+*5JgTRyKX(85J9w=KZ0rDAWoRwVJ!ftO+36w+0===P zKO?5LW^lY~|5Tz@S1?kT+rdzH@hgjsO;%$l^fH ztZPl^T)J=a+9N=&r~nUsizrQ(zzSw@O;lB^Go}+~Zalv8)Xm?2{$}*7`S9gCX6yrX z0rg_7+^OkG6AhU?{ppxh3#3QU3Ts0=dikMX(nhQ%0QCY*0GdNXSJuY6Vr}pOLoT&z zHS*XMFi?Ss7^@*b6M*InKzW%vVg1wBAJGImmhOXRmw_)Yfnm1i%xz3@V9;jut)sAR zq>d|rq1Co{4=!0?00V=0fL#d;CtxXvtEmA2`_J8hls*Gi_W)ZGF2-s=#`fa@mqR68o;h=7kh>BfzyOxsTT=JZj*I{R002ovPDHLk FV1kG^r+NSY literal 0 HcmV?d00001 diff --git a/Toolkit/PHPImageEditor/images/edit.gif b/Toolkit/PHPImageEditor/images/edit.gif new file mode 100644 index 0000000000000000000000000000000000000000..1a5a0afb0a0caa2a61167dff9d54a75b96d3e55c GIT binary patch literal 417 zcmV;S0bc$`Nk%w1VGaNh0M!5h=a~ocwK4SBr1A6i@#DSmsuKMD{qpki@$~ui)X47c z@cR1t^!E1a>gn(E`^U$}?(p~B-r@NC|LpGc?(XjJ@bK*H?Cb08^YrxW?eFjJ@$m2N z?(OUM)O_pg?eOpL%dmj*^6})@$=uo3=j7V;`~T(M*Y@1g;l!HVnkV+$m)O3v`uqIw z@bBp5bv>gnk5@$m8S^7HfZ@$&TT?CSXV`1||&@9*#T_xJDc z^Zot(A^8LV00000EC2ui01f~V000KQK*MiHEE0E&8wPW*Icq@39b#5NV>2k zBC~b@b~P=nNfWAe-b%_i6tS^-1y(h@EsB~1TqDA_h@fkxG$bHgvj}VxE1JLgr!*!^ ILUxTc0Q$^Q5C8xG literal 0 HcmV?d00001 diff --git a/Toolkit/PHPImageEditor/images/slider_pointer.gif b/Toolkit/PHPImageEditor/images/slider_pointer.gif new file mode 100644 index 0000000000000000000000000000000000000000..8e8fdcdb809dbf36e09e3dedf327e9c5112d0eee GIT binary patch literal 347 zcmZ?wbhEHb^>y zUAlDX>({UE-@jkFbm^BbUv})+@!`XVty{PL`SWM`^ywQmZ20)`V}5@A)2B~&?b`L} z)2Cm*e%-rw@7uR;j~_qYzJ2?{hYx#ud)wRF*REZA=gytBwzhfm<~@1xgKxe+fVL(q-I>7#P{ttYv3pP-KeT63Zm6tXi_WL|n;{!5RSRqLCf| literal 0 HcmV?d00001 diff --git a/Toolkit/PHPImageEditor/images/slider_track.gif b/Toolkit/PHPImageEditor/images/slider_track.gif new file mode 100644 index 0000000000000000000000000000000000000000..e1dc8e0d89ab40cbaee10ea10b16e86e55697ba6 GIT binary patch literal 176 zcmV;h08jr%Nk%w1VUYm`0FeU#=j!UPu(0y-^8f$;A^8LW00093EC2ui0FeO)0007k zjE||y?GK}zwAzca-n{$20pduO=82~2%C_zc$MUQO^o{5G&iDQg3<`%o8}W!tDrbVG z^9hYgr_`$Tip^@b+^)A8_=?BmviXd@4%Y0p`wfrF=k&V$j?e4&{CS`c7$`VMSZH{N en5ekOi1^nC87VnQS!sERdH0yf+3A^A0029RMO?W6 literal 0 HcmV?d00001 diff --git a/Toolkit/PHPImageEditor/images/tab_body.png b/Toolkit/PHPImageEditor/images/tab_body.png new file mode 100644 index 0000000000000000000000000000000000000000..6e164fe392b12f25ca90a4472f43c321f2c44ce9 GIT binary patch literal 198 zcmeAS@N?(olHy`uVBq!ia0vp^oIq^E!2~23{n9jnlw^r(L`iUdT1k0gQ7VIDN`6wR zf@f}GdTLN=VoGJ<$y6Jlq6|+L$B>F!cP?7;H8}7vA25CNfBqw09dm9`+4S=t8J8O{ zabD_sqro*Pu{|6H_V+Po~-c6fkP)6WDOn)q$eaESlC*!xZt+q wuGJEfFB90`Hn()y$p`RXI;=709|MO0gH{nUM-GQF56}z-Pgg&ebxsLQ0M@`T2><{9 literal 0 HcmV?d00001 diff --git a/Toolkit/PHPImageEditor/includes/constants.php b/Toolkit/PHPImageEditor/includes/constants.php new file mode 100644 index 0000000..0a7a255 --- /dev/null +++ b/Toolkit/PHPImageEditor/includes/constants.php @@ -0,0 +1,49 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + /* + Copyright 2008, 2009, 2010 Patrik Hultgren + + YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR. + OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT: + http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F + + This file is part of PHP Image Editor. + + PHP Image Editor is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + PHP Image Editor is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with PHP Image Editor. If not, see . + */ + + + define("PHP_VERSION_MINIMUM", "5"); + define("GD_VERSION_MINIMUM", "2.0.28"); + define("IMAGE_ORIGINAL_PATH", "editimagesoriginal/"); + define("IMAGE_WORK_WITH_PATH", "editimagesworkwith/"); + define("IMAGE_PNG_PATH", "editimagespng/"); + define("MENU_RESIZE", "0"); + define("MENU_ROTATE", "1"); + define("MENU_CROP", "2"); + define("MENU_EFFECTS", "3"); +?> \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/includes/functions.php b/Toolkit/PHPImageEditor/includes/functions.php new file mode 100644 index 0000000..5fa5bbb --- /dev/null +++ b/Toolkit/PHPImageEditor/includes/functions.php @@ -0,0 +1,50 @@ +. + */ + + + function PIE_GetTexts($filePath) + { + $texts = array(); + $lines = file($filePath); + + foreach($lines as $line_num => $line) + { + if (substr_count($line, "#") == 0) + { + $keyAndText = explode("=", trim($line)); + $texts[$keyAndText[0]] = $keyAndText[1]; + } + } + + return $texts; + } + + function PIE_Echo($text) + { + echo $text; + //echo utf8_encode($text); + } +?> \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/index.php b/Toolkit/PHPImageEditor/index.php new file mode 100644 index 0000000..99b3f7f --- /dev/null +++ b/Toolkit/PHPImageEditor/index.php @@ -0,0 +1,250 @@ +. + */ + + + + header("Cache-Control: no-store"); + header('content-type: text/html; charset: utf-8'); + include 'includes/constants.php'; + include 'config.php'; + include 'includes/functions.php'; + include 'classes/phpimageeditor.php'; + global $objPHPImageEditor; + $objPHPImageEditor = new PHPImageEditor(); +?> +isAjaxPost) { ?> + + + + PHP Image Editor + + + + + + + + + + + + + + + + + + + +
    + + +
    + ErrorHasOccurred()) { ?> + +
    + + + +
    + +
    + + + + + +
    +
    +
    + + + +
    +
    + + + +
    +
    +
    + inputKeepProportions ? 'checked="checked"' : ''); ?>/> + + +
    +
    +
    +
    texts["INSTRUCTIONS"]); ?>
    +
    texts["RESIZE HELP"]); ?>
    +
    +
    +
    + +
    +
    + "/> + "/> + +
    +
    + +
    +
    + + + + +
    +
    texts["INSTRUCTIONS"]); ?>
    +
    texts["CROP HELP"]); ?>
    +
    +
    +
    +
    + texts["CROP WIDTH"]); ?>: 0 + texts["CROP HEIGHT"]); ?>: 0 +
    + inputCropKeepProportions ? 'checked="checked"' : ''); ?>/> + + + +
    +
    +
    +
    + +
    +
    + +
    + +
    +
    + +
    + inputGrayscale ? 'checked="checked"' : ''); ?>/> + + +
    +
    + + +
    + +
    + "/> + actions == "" ? 'disabled="disabled"' : ''); ?> id="btnsave" name="btnsave" value="texts["SAVE AND CLOSE"]); ?>"/> + actions == "" ? 'disabled="disabled"' : ''); ?> id="btnundo" name="btnundo" value="texts["UNDO"]); ?>"/> +
    +
    + +
    + +
    + + + + + + + + + + + + + + +
    + GetErrorMessages(); ?> + +
    + ErrorHasOccurred()) { ?> +
    + +
    +
    +
    + + +isAjaxPost) { ?> +
    + + + + +CleanUp(); ?> \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/effects.core.js b/Toolkit/PHPImageEditor/javascript/effects.core.js new file mode 100644 index 0000000..9c983c1 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/effects.core.js @@ -0,0 +1,543 @@ +/* + * jQuery UI Effects 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Effects/ + */ +;jQuery.effects || (function($) { + +$.effects = { + version: "1.7", + + // Saves a set of properties in a data storage + save: function(element, set) { + for(var i=0; i < set.length; i++) { + if(set[i] !== null) element.data("ec.storage."+set[i], element[0].style[set[i]]); + } + }, + + // Restores a set of previously saved properties from a data storage + restore: function(element, set) { + for(var i=0; i < set.length; i++) { + if(set[i] !== null) element.css(set[i], element.data("ec.storage."+set[i])); + } + }, + + setMode: function(el, mode) { + if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle + return mode; + }, + + getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value + // this should be a little more flexible in the future to handle a string & hash + var y, x; + switch (origin[0]) { + case 'top': y = 0; break; + case 'middle': y = 0.5; break; + case 'bottom': y = 1; break; + default: y = origin[0] / original.height; + }; + switch (origin[1]) { + case 'left': x = 0; break; + case 'center': x = 0.5; break; + case 'right': x = 1; break; + default: x = origin[1] / original.width; + }; + return {x: x, y: y}; + }, + + // Wraps the element around a wrapper that copies position properties + createWrapper: function(element) { + + //if the element is already wrapped, return it + if (element.parent().is('.ui-effects-wrapper')) + return element.parent(); + + //Cache width,height and float properties of the element, and create a wrapper around it + var props = { width: element.outerWidth(true), height: element.outerHeight(true), 'float': element.css('float') }; + element.wrap('
    '); + var wrapper = element.parent(); + + //Transfer the positioning of the element to the wrapper + if (element.css('position') == 'static') { + wrapper.css({ position: 'relative' }); + element.css({ position: 'relative'} ); + } else { + var top = element.css('top'); if(isNaN(parseInt(top,10))) top = 'auto'; + var left = element.css('left'); if(isNaN(parseInt(left,10))) left = 'auto'; + wrapper.css({ position: element.css('position'), top: top, left: left, zIndex: element.css('z-index') }).show(); + element.css({position: 'relative', top: 0, left: 0 }); + } + + wrapper.css(props); + return wrapper; + }, + + removeWrapper: function(element) { + if (element.parent().is('.ui-effects-wrapper')) + return element.parent().replaceWith(element); + return element; + }, + + setTransition: function(element, list, factor, value) { + value = value || {}; + $.each(list, function(i, x){ + unit = element.cssUnit(x); + if (unit[0] > 0) value[x] = unit[0] * factor + unit[1]; + }); + return value; + }, + + //Base function to animate from one class to another in a seamless transition + animateClass: function(value, duration, easing, callback) { + + var cb = (typeof easing == "function" ? easing : (callback ? callback : null)); + var ea = (typeof easing == "string" ? easing : null); + + return this.each(function() { + + var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || ''; + if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */ + if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; } + + //Let's get a style offset + var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle)); + if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove); + var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle)); + if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove); + + // The main function to form the object for animation + for(var n in newStyle) { + if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */ + && n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */ + && newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */ + && (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */ + && (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */ + ) offset[n] = newStyle[n]; + } + + that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object + // Change style attribute back to original. For stupid IE, we need to clear the damn object. + if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr); + if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove); + if(cb) cb.apply(this, arguments); + }); + + }); + } +}; + + +function _normalizeArguments(a, m) { + + var o = a[1] && a[1].constructor == Object ? a[1] : {}; if(m) o.mode = m; + var speed = a[1] && a[1].constructor != Object ? a[1] : (o.duration ? o.duration : a[2]); //either comes from options.duration or the secon/third argument + speed = $.fx.off ? 0 : typeof speed === "number" ? speed : $.fx.speeds[speed] || $.fx.speeds._default; + var callback = o.callback || ( $.isFunction(a[1]) && a[1] ) || ( $.isFunction(a[2]) && a[2] ) || ( $.isFunction(a[3]) && a[3] ); + + return [a[0], o, speed, callback]; + +} + +//Extend the methods of jQuery +$.fn.extend({ + + //Save old methods + _show: $.fn.show, + _hide: $.fn.hide, + __toggle: $.fn.toggle, + _addClass: $.fn.addClass, + _removeClass: $.fn.removeClass, + _toggleClass: $.fn.toggleClass, + + // New effect methods + effect: function(fx, options, speed, callback) { + return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: options || {}, duration: speed, callback: callback }) : null; + }, + + show: function() { + if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0]))) + return this._show.apply(this, arguments); + else { + return this.effect.apply(this, _normalizeArguments(arguments, 'show')); + } + }, + + hide: function() { + if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0]))) + return this._hide.apply(this, arguments); + else { + return this.effect.apply(this, _normalizeArguments(arguments, 'hide')); + } + }, + + toggle: function(){ + if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])) || (arguments[0].constructor == Function)) + return this.__toggle.apply(this, arguments); + else { + return this.effect.apply(this, _normalizeArguments(arguments, 'toggle')); + } + }, + + addClass: function(classNames, speed, easing, callback) { + return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames); + }, + removeClass: function(classNames,speed,easing,callback) { + return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames); + }, + toggleClass: function(classNames,speed,easing,callback) { + return ( (typeof speed !== "boolean") && speed ) ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames, speed); + }, + morph: function(remove,add,speed,easing,callback) { + return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]); + }, + switchClass: function() { + return this.morph.apply(this, arguments); + }, + + // helper functions + cssUnit: function(key) { + var style = this.css(key), val = []; + $.each( ['em','px','%','pt'], function(i, unit){ + if(style.indexOf(unit) > 0) + val = [parseFloat(style), unit]; + }); + return val; + } +}); + +/* + * jQuery Color Animations + * Copyright 2007 John Resig + * Released under the MIT and GPL licenses. + */ + +// We override the animation for all of these color styles +$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){ + $.fx.step[attr] = function(fx) { + if ( fx.state == 0 ) { + fx.start = getColor( fx.elem, attr ); + fx.end = getRGB( fx.end ); + } + + fx.elem.style[attr] = "rgb(" + [ + Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0],10), 255), 0), + Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1],10), 255), 0), + Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2],10), 255), 0) + ].join(",") + ")"; + }; +}); + +// Color Conversion functions from highlightFade +// By Blair Mitchelmore +// http://jquery.offput.ca/highlightFade/ + +// Parse strings looking for color tuples [255,255,255] +function getRGB(color) { + var result; + + // Check if we're already dealing with an array of colors + if ( color && color.constructor == Array && color.length == 3 ) + return color; + + // Look for rgb(num,num,num) + if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) + return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)]; + + // Look for rgb(num%,num%,num%) + if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) + return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; + + // Look for #a0b1c2 + if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) + return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; + + // Look for #fff + if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) + return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; + + // Look for rgba(0, 0, 0, 0) == transparent in Safari 3 + if (result = /rgba\(0, 0, 0, 0\)/.exec(color)) + return colors['transparent']; + + // Otherwise, we're most likely dealing with a named color + return colors[$.trim(color).toLowerCase()]; +} + +function getColor(elem, attr) { + var color; + + do { + color = $.curCSS(elem, attr); + + // Keep going until we find an element that has color, or we hit the body + if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") ) + break; + + attr = "backgroundColor"; + } while ( elem = elem.parentNode ); + + return getRGB(color); +}; + +// Some named colors to work with +// From Interface by Stefan Petre +// http://interface.eyecon.ro/ + +var colors = { + aqua:[0,255,255], + azure:[240,255,255], + beige:[245,245,220], + black:[0,0,0], + blue:[0,0,255], + brown:[165,42,42], + cyan:[0,255,255], + darkblue:[0,0,139], + darkcyan:[0,139,139], + darkgrey:[169,169,169], + darkgreen:[0,100,0], + darkkhaki:[189,183,107], + darkmagenta:[139,0,139], + darkolivegreen:[85,107,47], + darkorange:[255,140,0], + darkorchid:[153,50,204], + darkred:[139,0,0], + darksalmon:[233,150,122], + darkviolet:[148,0,211], + fuchsia:[255,0,255], + gold:[255,215,0], + green:[0,128,0], + indigo:[75,0,130], + khaki:[240,230,140], + lightblue:[173,216,230], + lightcyan:[224,255,255], + lightgreen:[144,238,144], + lightgrey:[211,211,211], + lightpink:[255,182,193], + lightyellow:[255,255,224], + lime:[0,255,0], + magenta:[255,0,255], + maroon:[128,0,0], + navy:[0,0,128], + olive:[128,128,0], + orange:[255,165,0], + pink:[255,192,203], + purple:[128,0,128], + violet:[128,0,128], + red:[255,0,0], + silver:[192,192,192], + white:[255,255,255], + yellow:[255,255,0], + transparent: [255,255,255] +}; + +/* + * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ + * + * Uses the built in easing capabilities added In jQuery 1.1 + * to offer multiple easing options + * + * TERMS OF USE - jQuery Easing + * + * Open source under the BSD License. + * + * Copyright 2008 George McGinley Smith + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * Neither the name of the author nor the names of contributors may be used to endorse + * or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * +*/ + +// t: current time, b: begInnIng value, c: change In value, d: duration +$.easing.jswing = $.easing.swing; + +$.extend($.easing, +{ + def: 'easeOutQuad', + swing: function (x, t, b, c, d) { + //alert($.easing.default); + return $.easing[$.easing.def](x, t, b, c, d); + }, + easeInQuad: function (x, t, b, c, d) { + return c*(t/=d)*t + b; + }, + easeOutQuad: function (x, t, b, c, d) { + return -c *(t/=d)*(t-2) + b; + }, + easeInOutQuad: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t + b; + return -c/2 * ((--t)*(t-2) - 1) + b; + }, + easeInCubic: function (x, t, b, c, d) { + return c*(t/=d)*t*t + b; + }, + easeOutCubic: function (x, t, b, c, d) { + return c*((t=t/d-1)*t*t + 1) + b; + }, + easeInOutCubic: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t + b; + return c/2*((t-=2)*t*t + 2) + b; + }, + easeInQuart: function (x, t, b, c, d) { + return c*(t/=d)*t*t*t + b; + }, + easeOutQuart: function (x, t, b, c, d) { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + }, + easeInOutQuart: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t*t + b; + return -c/2 * ((t-=2)*t*t*t - 2) + b; + }, + easeInQuint: function (x, t, b, c, d) { + return c*(t/=d)*t*t*t*t + b; + }, + easeOutQuint: function (x, t, b, c, d) { + return c*((t=t/d-1)*t*t*t*t + 1) + b; + }, + easeInOutQuint: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; + return c/2*((t-=2)*t*t*t*t + 2) + b; + }, + easeInSine: function (x, t, b, c, d) { + return -c * Math.cos(t/d * (Math.PI/2)) + c + b; + }, + easeOutSine: function (x, t, b, c, d) { + return c * Math.sin(t/d * (Math.PI/2)) + b; + }, + easeInOutSine: function (x, t, b, c, d) { + return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; + }, + easeInExpo: function (x, t, b, c, d) { + return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; + }, + easeOutExpo: function (x, t, b, c, d) { + return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; + }, + easeInOutExpo: function (x, t, b, c, d) { + if (t==0) return b; + if (t==d) return b+c; + if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; + return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; + }, + easeInCirc: function (x, t, b, c, d) { + return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; + }, + easeOutCirc: function (x, t, b, c, d) { + return c * Math.sqrt(1 - (t=t/d-1)*t) + b; + }, + easeInOutCirc: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; + return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; + }, + easeInElastic: function (x, t, b, c, d) { + var s=1.70158;var p=0;var a=c; + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + }, + easeOutElastic: function (x, t, b, c, d) { + var s=1.70158;var p=0;var a=c; + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; + }, + easeInOutElastic: function (x, t, b, c, d) { + var s=1.70158;var p=0;var a=c; + if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); + if (a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + }, + easeInBack: function (x, t, b, c, d, s) { + if (s == undefined) s = 1.70158; + return c*(t/=d)*t*((s+1)*t - s) + b; + }, + easeOutBack: function (x, t, b, c, d, s) { + if (s == undefined) s = 1.70158; + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + }, + easeInOutBack: function (x, t, b, c, d, s) { + if (s == undefined) s = 1.70158; + if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + }, + easeInBounce: function (x, t, b, c, d) { + return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b; + }, + easeOutBounce: function (x, t, b, c, d) { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } else { + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + } + }, + easeInOutBounce: function (x, t, b, c, d) { + if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; + return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; + } +}); + +/* + * + * TERMS OF USE - EASING EQUATIONS + * + * Open source under the BSD License. + * + * Copyright 2001 Robert Penner + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * Neither the name of the author nor the names of contributors may be used to endorse + * or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/joomla_editimagelink.js b/Toolkit/PHPImageEditor/javascript/joomla_editimagelink.js new file mode 100644 index 0000000..2270ab6 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/joomla_editimagelink.js @@ -0,0 +1,167 @@ +String.prototype.phpimageeditor_add_editlink_endswith = function(str) +{ + return (this.match(str+"$")==str); +} + +function phpimageeditor_add_editlink(pathToEditor, pathToPlugin, hostPath, editImageText, language) +{ + var mediamanagerForm = document.getElementById("mediamanager-form"); + if (mediamanagerForm != null) + { + var trs = mediamanagerForm.getElementsByTagName("tr"); + var modeDetailed = (trs.length > 0); + + if (modeDetailed) + { + var isTableHeader = true; + + for(var i=0;i'+editImageText+''; + foundDetailedImage = true; + break; + } + } + } + } + + if (!foundDetailedImage) + td.innerHTML = " "; + + trs[i].appendChild(td); + } + + isTableHeader = false; + } + } + else + { + var e = mediamanagerForm.getElementsByTagName("div"); + + for(var i=0;i 0) + { + imageSrc = phpimageeditor_urlencode(images[0].src.replace(hostPath,'../../../')); + + if (phpimageeditor_file_is_image(imageSrc)) + e[i].innerHTML += ''+editImageText+''; + } + } + } + } + } + else + { + var articledivs = document.getElementsByTagName("div"); + var foundManager = false; + var foundItem = false; + for(var i=0;i 0 && imagesArticle[0].src.indexOf('folder.gif') == -1 && phpimageeditor_file_is_image(imagesArticle[0].src)) + { + imageSrcArticle = phpimageeditor_urlencode(imagesArticle[0].src.replace(hostPath,'../../../')); + articledivs[i].innerHTML = ''+editImageText+'' + articledivs[i].innerHTML; + } + } + } + } + } +} + +function phpimageeditor_urlencode(str) +{ + // http://kevin.vanzonneveld.net + // + original by: Philip Peterson + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + input by: AJ + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // % note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/ + // * example 1: urlencode('Kevin van Zonneveld!'); + // * returns 1: 'Kevin+van+Zonneveld%21' + // * example 2: urlencode('http://kevin.vanzonneveld.net/'); + // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F' + // * example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'); + // * returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a' + + var histogram = {}, histogram_r = {}, code = 0, tmp_arr = []; + var ret = str.toString(); + + var replacer = function(search, replace, str) { + var tmp_arr = []; + tmp_arr = str.split(search); + return tmp_arr.join(replace); + }; + + // The histogram is identical to the one in urldecode. + histogram['!'] = '%21'; + histogram['%20'] = '+'; + + // Begin with encodeURIComponent, which most resembles PHP's encoding functions + ret = encodeURIComponent(ret); + + for (search in histogram) { + replace = histogram[search]; + ret = replacer(search, replace, ret) // Custom replace. No regexing + } + + // Uppercase for full PHP compatibility + return ret.replace('/(\%([a-z0-9]{2}))/g', function(full, m1, m2) { + return "%"+m2.toUpperCase(); + }); + + return ret; +} + +function phpimageeditor_file_is_image(filePath) +{ + filePath = filePath.toLowerCase(); + return (filePath.indexOf('com_media') == -1 && (filePath.phpimageeditor_add_editlink_endswith("jpg") || filePath.phpimageeditor_add_editlink_endswith("gif") || filePath.phpimageeditor_add_editlink_endswith("png"))); +} \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/jquery-1.3.2.min.js b/Toolkit/PHPImageEditor/javascript/jquery-1.3.2.min.js new file mode 100644 index 0000000..b1ae21d --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/jquery-1.3.2.min.js @@ -0,0 +1,19 @@ +/* + * jQuery JavaScript Library v1.3.2 + * http://jquery.com/ + * + * Copyright (c) 2009 John Resig + * Dual licensed under the MIT and GPL licenses. + * http://docs.jquery.com/License + * + * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + * Revision: 6246 + */ +(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("",""]||!O.indexOf("",""]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
    "]||!O.indexOf("",""]||(!O.indexOf("",""]||!O.indexOf("",""]||!o.support.htmlSerialize&&[1,"div
    ","
    "]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); +/* + * Sizzle CSS Selector Engine - v0.9.3 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return UT[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="

    ";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="
    ";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("
    ").append(M.responseText.replace(//g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='
    ';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js b/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js new file mode 100644 index 0000000..ad261f9 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js @@ -0,0 +1,1197 @@ +/** + * jquery.Jcrop.js v0.9.8 + * jQuery Image Cropping Plugin + * @author Kelly Hallman + * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{ + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + + * }}} + */ + +(function($) { + +$.Jcrop = function(obj,opt) +{ + // Initialization {{{ + + // Sanitize some options {{{ + var obj = obj, opt = opt; + + if (typeof(obj) !== 'object') obj = $(obj)[0]; + if (typeof(opt) !== 'object') opt = { }; + + // Some on-the-fly fixes for MSIE...sigh + if (!('trackDocument' in opt)) + { + opt.trackDocument = $.browser.msie ? false : true; + if ($.browser.msie && $.browser.version.split('.')[0] == '8') + opt.trackDocument = true; + } + + if (!('keySupport' in opt)) + opt.keySupport = $.browser.msie ? false : true; + + // }}} + // Extend the default options {{{ + var defaults = { + + // Basic Settings + trackDocument: false, + baseClass: 'jcrop', + addClass: null, + + // Styling Options + bgColor: 'black', + bgOpacity: .6, + borderOpacity: .4, + handleOpacity: .5, + + handlePad: 5, + handleSize: 9, + handleOffset: 5, + edgeMargin: 14, + + aspectRatio: 0, + keySupport: true, + cornerHandles: true, + sideHandles: true, + drawBorders: true, + dragEdges: true, + + boxWidth: 0, + boxHeight: 0, + + boundary: 8, + animationDelay: 20, + swingSpeed: 3, + + allowSelect: true, + allowMove: true, + allowResize: true, + + minSelect: [ 0, 0 ], + maxSize: [ 0, 0 ], + minSize: [ 0, 0 ], + + // Callbacks / Event Handlers + onChange: function() { }, + onSelect: function() { } + + }; + var options = defaults; + setOptions(opt); + + // }}} + // Initialize some jQuery objects {{{ + + var $origimg = $(obj); + var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' }); + + $img.width($origimg.width()); + $img.height($origimg.height()); + $origimg.after($img).hide(); + + presize($img,options.boxWidth,options.boxHeight); + + var boundx = $img.width(), + boundy = $img.height(), + + $div = $('
    ') + .width(boundx).height(boundy) + .addClass(cssClass('holder')) + .css({ + position: 'relative', + backgroundColor: options.bgColor + }).insertAfter($origimg).append($img); + ; + + if (options.addClass) $div.addClass(options.addClass); + //$img.wrap($div); + + var $img2 = $('')/*{{{*/ + .attr('src',$img.attr('src')) + .css('position','absolute') + .width(boundx).height(boundy) + ;/*}}}*/ + var $img_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css({ + zIndex: 310, + position: 'absolute', + overflow: 'hidden' + }) + .append($img2) + ;/*}}}*/ + var $hdl_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css('zIndex',320); + /*}}}*/ + var $sel = $('
    ')/*{{{*/ + .css({ + position: 'absolute', + zIndex: 300 + }) + .insertBefore($img) + .append($img_holder,$hdl_holder) + ;/*}}}*/ + + var bound = options.boundary; + var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2)) + .css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 }) + .mousedown(newSelection); + + /* }}} */ + // Set more variables {{{ + + var xlimit, ylimit, xmin, ymin; + var xscale, yscale, enabled = true; + var docOffset = getPos($img), + // Internal states + btndown, lastcurs, dimmed, animating, + shift_down; + + // }}} + + + // }}} + // Internal Modules {{{ + + var Coords = function()/*{{{*/ + { + var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy; + + function setPressed(pos)/*{{{*/ + { + var pos = rebound(pos); + x2 = x1 = pos[0]; + y2 = y1 = pos[1]; + }; + /*}}}*/ + function setCurrent(pos)/*{{{*/ + { + var pos = rebound(pos); + ox = pos[0] - x2; + oy = pos[1] - y2; + x2 = pos[0]; + y2 = pos[1]; + }; + /*}}}*/ + function getOffset()/*{{{*/ + { + return [ ox, oy ]; + }; + /*}}}*/ + function moveOffset(offset)/*{{{*/ + { + var ox = offset[0], oy = offset[1]; + + if (0 > x1 + ox) ox -= ox + x1; + if (0 > y1 + oy) oy -= oy + y1; + + if (boundy < y2 + oy) oy += boundy - (y2 + oy); + if (boundx < x2 + ox) ox += boundx - (x2 + ox); + + x1 += ox; + x2 += ox; + y1 += oy; + y2 += oy; + }; + /*}}}*/ + function getCorner(ord)/*{{{*/ + { + var c = getFixed(); + switch(ord) + { + case 'ne': return [ c.x2, c.y ]; + case 'nw': return [ c.x, c.y ]; + case 'se': return [ c.x2, c.y2 ]; + case 'sw': return [ c.x, c.y2 ]; + } + }; + /*}}}*/ + function getFixed()/*{{{*/ + { + if (!options.aspectRatio) return getRect(); + // This function could use some optimization I think... + var aspect = options.aspectRatio, + min_x = options.minSize[0]/xscale, + min_y = options.minSize[1]/yscale, + max_x = options.maxSize[0]/xscale, + max_y = options.maxSize[1]/yscale, + rw = x2 - x1, + rh = y2 - y1, + rwa = Math.abs(rw), + rha = Math.abs(rh), + real_ratio = rwa / rha, + xx, yy + ; + if (max_x == 0) { max_x = boundx * 10 } + if (max_y == 0) { max_y = boundy * 10 } + if (real_ratio < aspect) + { + yy = y2; + w = rha * aspect; + xx = rw < 0 ? x1 - w : w + x1; + + if (xx < 0) + { + xx = 0; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h: h + y1; + } + else if (xx > boundx) + { + xx = boundx; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h : h + y1; + } + } + else + { + xx = x2; + h = rwa / aspect; + yy = rh < 0 ? y1 - h : y1 + h; + if (yy < 0) + { + yy = 0; + w = Math.abs((yy - y1) * aspect); + xx = rw < 0 ? x1 - w : w + x1; + } + else if (yy > boundy) + { + yy = boundy; + w = Math.abs(yy - y1) * aspect; + xx = rw < 0 ? x1 - w : w + x1; + } + } + + // Magic %-) + if(xx > x1) { // right side + if(xx - x1 < min_x) { + xx = x1 + min_x; + } else if (xx - x1 > max_x) { + xx = x1 + max_x; + } + if(yy > y1) { + yy = y1 + (xx - x1)/aspect; + } else { + yy = y1 - (xx - x1)/aspect; + } + } else if (xx < x1) { // left side + if(x1 - xx < min_x) { + xx = x1 - min_x + } else if (x1 - xx > max_x) { + xx = x1 - max_x; + } + if(yy > y1) { + yy = y1 + (x1 - xx)/aspect; + } else { + yy = y1 - (x1 - xx)/aspect; + } + } + + if(xx < 0) { + x1 -= xx; + xx = 0; + } else if (xx > boundx) { + x1 -= xx - boundx; + xx = boundx; + } + + if(yy < 0) { + y1 -= yy; + yy = 0; + } else if (yy > boundy) { + y1 -= yy - boundy; + yy = boundy; + } + + return last = makeObj(flipCoords(x1,y1,xx,yy)); + }; + /*}}}*/ + function rebound(p)/*{{{*/ + { + if (p[0] < 0) p[0] = 0; + if (p[1] < 0) p[1] = 0; + + if (p[0] > boundx) p[0] = boundx; + if (p[1] > boundy) p[1] = boundy; + + return [ p[0], p[1] ]; + }; + /*}}}*/ + function flipCoords(x1,y1,x2,y2)/*{{{*/ + { + var xa = x1, xb = x2, ya = y1, yb = y2; + if (x2 < x1) + { + xa = x2; + xb = x1; + } + if (y2 < y1) + { + ya = y2; + yb = y1; + } + return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ]; + }; + /*}}}*/ + function getRect()/*{{{*/ + { + var xsize = x2 - x1; + var ysize = y2 - y1; + + if (xlimit && (Math.abs(xsize) > xlimit)) + x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit); + if (ylimit && (Math.abs(ysize) > ylimit)) + y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit); + + if (ymin && (Math.abs(ysize) < ymin)) + y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin); + if (xmin && (Math.abs(xsize) < xmin)) + x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin); + + if (x1 < 0) { x2 -= x1; x1 -= x1; } + if (y1 < 0) { y2 -= y1; y1 -= y1; } + if (x2 < 0) { x1 -= x2; x2 -= x2; } + if (y2 < 0) { y1 -= y2; y2 -= y2; } + if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; } + if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; } + if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; } + if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; } + + return makeObj(flipCoords(x1,y1,x2,y2)); + }; + /*}}}*/ + function makeObj(a)/*{{{*/ + { + return { x: a[0], y: a[1], x2: a[2], y2: a[3], + w: a[2] - a[0], h: a[3] - a[1] }; + }; + /*}}}*/ + + return { + flipCoords: flipCoords, + setPressed: setPressed, + setCurrent: setCurrent, + getOffset: getOffset, + moveOffset: moveOffset, + getCorner: getCorner, + getFixed: getFixed + }; + }(); + + /*}}}*/ + var Selection = function()/*{{{*/ + { + var start, end, dragmode, awake, hdep = 370; + var borders = { }; + var handle = { }; + var seehandles = false; + var hhs = options.handleOffset; + + /* Insert draggable elements {{{*/ + + // Insert border divs for outline + if (options.drawBorders) { + borders = { + top: insertBorder('hline') + .css('top',$.browser.msie?px(-1):px(0)), + bottom: insertBorder('hline'), + left: insertBorder('vline'), + right: insertBorder('vline') + }; + } + + // Insert handles on edges + if (options.dragEdges) { + handle.t = insertDragbar('n'); + handle.b = insertDragbar('s'); + handle.r = insertDragbar('e'); + handle.l = insertDragbar('w'); + } + + // Insert side handles + options.sideHandles && + createHandles(['n','s','e','w']); + + // Insert corner handles + options.cornerHandles && + createHandles(['sw','nw','ne','se']); + + /*}}}*/ + // Private Methods + function insertBorder(type)/*{{{*/ + { + var jq = $('
    ') + .css({position: 'absolute', opacity: options.borderOpacity }) + .addClass(cssClass(type)); + $img_holder.append(jq); + return jq; + }; + /*}}}*/ + function dragDiv(ord,zi)/*{{{*/ + { + var jq = $('
    ') + .mousedown(createDragger(ord)) + .css({ + cursor: ord+'-resize', + position: 'absolute', + zIndex: zi + }) + ; + $hdl_holder.append(jq); + return jq; + }; + /*}}}*/ + function insertHandle(ord)/*{{{*/ + { + return dragDiv(ord,hdep++) + .css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity }) + .addClass(cssClass('handle')); + }; + /*}}}*/ + function insertDragbar(ord)/*{{{*/ + { + var s = options.handleSize, + o = hhs, + h = s, w = s, + t = o, l = o; + + switch(ord) + { + case 'n': case 's': w = pct(100); break; + case 'e': case 'w': h = pct(100); break; + } + + return dragDiv(ord,hdep++).width(w).height(h) + .css({ top: px(-t+1), left: px(-l+1)}); + }; + /*}}}*/ + function createHandles(li)/*{{{*/ + { + for(i in li) handle[li[i]] = insertHandle(li[i]); + }; + /*}}}*/ + function moveHandles(c)/*{{{*/ + { + var midvert = Math.round((c.h / 2) - hhs), + midhoriz = Math.round((c.w / 2) - hhs), + north = west = -hhs+1, + east = c.w - hhs, + south = c.h - hhs, + x, y; + + 'e' in handle && + handle.e.css({ top: px(midvert), left: px(east) }) && + handle.w.css({ top: px(midvert) }) && + handle.s.css({ top: px(south), left: px(midhoriz) }) && + handle.n.css({ left: px(midhoriz) }); + + 'ne' in handle && + handle.ne.css({ left: px(east) }) && + handle.se.css({ top: px(south), left: px(east) }) && + handle.sw.css({ top: px(south) }); + + 'b' in handle && + handle.b.css({ top: px(south) }) && + handle.r.css({ left: px(east) }); + }; + /*}}}*/ + function moveto(x,y)/*{{{*/ + { + $img2.css({ top: px(-y), left: px(-x) }); + $sel.css({ top: px(y), left: px(x) }); + }; + /*}}}*/ + function resize(w,h)/*{{{*/ + { + $sel.width(w).height(h); + }; + /*}}}*/ + function refresh()/*{{{*/ + { + var c = Coords.getFixed(); + + Coords.setPressed([c.x,c.y]); + Coords.setCurrent([c.x2,c.y2]); + + updateVisible(); + }; + /*}}}*/ + + // Internal Methods + function updateVisible()/*{{{*/ + { if (awake) return update(); }; + /*}}}*/ + function update()/*{{{*/ + { + var c = Coords.getFixed(); + + resize(c.w,c.h); + moveto(c.x,c.y); + + options.drawBorders && + borders['right'].css({ left: px(c.w-1) }) && + borders['bottom'].css({ top: px(c.h-1) }); + + seehandles && moveHandles(c); + awake || show(); + + options.onChange(unscale(c)); + }; + /*}}}*/ + function show()/*{{{*/ + { + $sel.show(); + $img.css('opacity',options.bgOpacity); + awake = true; + }; + /*}}}*/ + function release()/*{{{*/ + { + disableHandles(); + $sel.hide(); + $img.css('opacity',1); + awake = false; + }; + /*}}}*/ + function showHandles()//{{{ + { + if (seehandles) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + } + }; + //}}} + function enableHandles()/*{{{*/ + { + seehandles = true; + if (options.allowResize) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + return true; + } + }; + /*}}}*/ + function disableHandles()/*{{{*/ + { + seehandles = false; + $hdl_holder.hide(); + }; + /*}}}*/ + function animMode(v)/*{{{*/ + { + (animating = v) ? disableHandles(): enableHandles(); + }; + /*}}}*/ + function done()/*{{{*/ + { + animMode(false); + refresh(); + }; + /*}}}*/ + + var $track = newTracker().mousedown(createDragger('move')) + .css({ cursor: 'move', position: 'absolute', zIndex: 360 }) + + $img_holder.append($track); + disableHandles(); + + return { + updateVisible: updateVisible, + update: update, + release: release, + refresh: refresh, + setCursor: function (cursor) { $track.css('cursor',cursor); }, + enableHandles: enableHandles, + enableOnly: function() { seehandles = true; }, + showHandles: showHandles, + disableHandles: disableHandles, + animMode: animMode, + done: done + }; + }(); + /*}}}*/ + var Tracker = function()/*{{{*/ + { + var onMove = function() { }, + onDone = function() { }, + trackDoc = options.trackDocument; + + if (!trackDoc) + { + $trk + .mousemove(trackMove) + .mouseup(trackUp) + .mouseout(trackUp) + ; + } + + function toFront()/*{{{*/ + { + $trk.css({zIndex:450}); + if (trackDoc) + { + $(document) + .mousemove(trackMove) + .mouseup(trackUp) + ; + } + } + /*}}}*/ + function toBack()/*{{{*/ + { + $trk.css({zIndex:290}); + if (trackDoc) + { + $(document) + .unbind('mousemove',trackMove) + .unbind('mouseup',trackUp) + ; + } + } + /*}}}*/ + function trackMove(e)/*{{{*/ + { + onMove(mouseAbs(e)); + }; + /*}}}*/ + function trackUp(e)/*{{{*/ + { + e.preventDefault(); + e.stopPropagation(); + + if (btndown) + { + btndown = false; + + onDone(mouseAbs(e)); + options.onSelect(unscale(Coords.getFixed())); + toBack(); + onMove = function() { }; + onDone = function() { }; + } + + return false; + }; + /*}}}*/ + + function activateHandlers(move,done)/* {{{ */ + { + btndown = true; + onMove = move; + onDone = done; + toFront(); + return false; + }; + /* }}} */ + + function setCursor(t) { $trk.css('cursor',t); }; + + $img.before($trk); + return { + activateHandlers: activateHandlers, + setCursor: setCursor + }; + }(); + /*}}}*/ + var KeyManager = function()/*{{{*/ + { + var $keymgr = $('') + .css({ position: 'absolute', left: '-30px' }) + .keypress(parseKey) + .blur(onBlur), + + $keywrap = $('
    ') + .css({ + position: 'absolute', + overflow: 'hidden' + }) + .append($keymgr) + ; + + function watchKeys()/*{{{*/ + { + if (options.keySupport) + { + $keymgr.show(); + $keymgr.focus(); + } + }; + /*}}}*/ + function onBlur(e)/*{{{*/ + { + $keymgr.hide(); + }; + /*}}}*/ + function doNudge(e,x,y)/*{{{*/ + { + if (options.allowMove) { + Coords.moveOffset([x,y]); + Selection.updateVisible(); + }; + e.preventDefault(); + e.stopPropagation(); + }; + /*}}}*/ + function parseKey(e)/*{{{*/ + { + if (e.ctrlKey) return true; + shift_down = e.shiftKey ? true : false; + var nudge = shift_down ? 10 : 1; + switch(e.keyCode) + { + case 37: doNudge(e,-nudge,0); break; + case 39: doNudge(e,nudge,0); break; + case 38: doNudge(e,0,-nudge); break; + case 40: doNudge(e,0,nudge); break; + + case 27: Selection.release(); break; + + case 9: return true; + } + + return nothing(e); + }; + /*}}}*/ + + if (options.keySupport) $keywrap.insertBefore($img); + return { + watchKeys: watchKeys + }; + }(); + /*}}}*/ + + // }}} + // Internal Methods {{{ + + function px(n) { return '' + parseInt(n) + 'px'; }; + function pct(n) { return '' + parseInt(n) + '%'; }; + function cssClass(cl) { return options.baseClass + '-' + cl; }; + function getPos(obj)/*{{{*/ + { + // Updated in v0.9.4 to use built-in dimensions plugin + var pos = $(obj).offset(); + return [ pos.left, pos.top ]; + }; + /*}}}*/ + function mouseAbs(e)/*{{{*/ + { + return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ]; + }; + /*}}}*/ + function myCursor(type)/*{{{*/ + { + if (type != lastcurs) + { + Tracker.setCursor(type); + //Handles.xsetCursor(type); + lastcurs = type; + } + }; + /*}}}*/ + function startDragMode(mode,pos)/*{{{*/ + { + docOffset = getPos($img); + Tracker.setCursor(mode=='move'?mode:mode+'-resize'); + + if (mode == 'move') + return Tracker.activateHandlers(createMover(pos), doneSelect); + + var fc = Coords.getFixed(); + var opp = oppLockCorner(mode); + var opc = Coords.getCorner(oppLockCorner(opp)); + + Coords.setPressed(Coords.getCorner(opp)); + Coords.setCurrent(opc); + + Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect); + }; + /*}}}*/ + function dragmodeHandler(mode,f)/*{{{*/ + { + return function(pos) { + if (!options.aspectRatio) switch(mode) + { + case 'e': pos[1] = f.y2; break; + case 'w': pos[1] = f.y2; break; + case 'n': pos[0] = f.x2; break; + case 's': pos[0] = f.x2; break; + } + else switch(mode) + { + case 'e': pos[1] = f.y+1; break; + case 'w': pos[1] = f.y+1; break; + case 'n': pos[0] = f.x+1; break; + case 's': pos[0] = f.x+1; break; + } + Coords.setCurrent(pos); + Selection.update(); + }; + }; + /*}}}*/ + function createMover(pos)/*{{{*/ + { + var lloc = pos; + KeyManager.watchKeys(); + + return function(pos) + { + Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]); + lloc = pos; + + Selection.update(); + }; + }; + /*}}}*/ + function oppLockCorner(ord)/*{{{*/ + { + switch(ord) + { + case 'n': return 'sw'; + case 's': return 'nw'; + case 'e': return 'nw'; + case 'w': return 'ne'; + case 'ne': return 'sw'; + case 'nw': return 'se'; + case 'se': return 'nw'; + case 'sw': return 'ne'; + }; + }; + /*}}}*/ + function createDragger(ord)/*{{{*/ + { + return function(e) { + if (options.disabled) return false; + if ((ord == 'move') && !options.allowMove) return false; + btndown = true; + startDragMode(ord,mouseAbs(e)); + e.stopPropagation(); + e.preventDefault(); + return false; + }; + }; + /*}}}*/ + function presize($obj,w,h)/*{{{*/ + { + var nw = $obj.width(), nh = $obj.height(); + if ((nw > w) && w > 0) + { + nw = w; + nh = (w/$obj.width()) * $obj.height(); + } + if ((nh > h) && h > 0) + { + nh = h; + nw = (h/$obj.height()) * $obj.width(); + } + xscale = $obj.width() / nw; + yscale = $obj.height() / nh; + $obj.width(nw).height(nh); + }; + /*}}}*/ + function unscale(c)/*{{{*/ + { + return { + x: parseInt(c.x * xscale), y: parseInt(c.y * yscale), + x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale), + w: parseInt(c.w * xscale), h: parseInt(c.h * yscale) + }; + }; + /*}}}*/ + function doneSelect(pos)/*{{{*/ + { + var c = Coords.getFixed(); + if (c.w > options.minSelect[0] && c.h > options.minSelect[1]) + { + Selection.enableHandles(); + Selection.done(); + } + else + { + Selection.release(); + } + Tracker.setCursor( options.allowSelect?'crosshair':'default' ); + }; + /*}}}*/ + function newSelection(e)/*{{{*/ + { + if (options.disabled) return false; + if (!options.allowSelect) return false; + btndown = true; + docOffset = getPos($img); + Selection.disableHandles(); + myCursor('crosshair'); + var pos = mouseAbs(e); + Coords.setPressed(pos); + Tracker.activateHandlers(selectDrag,doneSelect); + KeyManager.watchKeys(); + Selection.update(); + + e.stopPropagation(); + e.preventDefault(); + return false; + }; + /*}}}*/ + function selectDrag(pos)/*{{{*/ + { + Coords.setCurrent(pos); + Selection.update(); + }; + /*}}}*/ + function newTracker() + { + var trk = $('
    ').addClass(cssClass('tracker')); + $.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' }); + return trk; + }; + + // }}} + // API methods {{{ + + function animateTo(a)/*{{{*/ + { + var x1 = a[0] / xscale, + y1 = a[1] / yscale, + x2 = a[2] / xscale, + y2 = a[3] / yscale; + + if (animating) return; + + var animto = Coords.flipCoords(x1,y1,x2,y2); + var c = Coords.getFixed(); + var animat = initcr = [ c.x, c.y, c.x2, c.y2 ]; + var interv = options.animationDelay; + + var x = animat[0]; + var y = animat[1]; + var x2 = animat[2]; + var y2 = animat[3]; + var ix1 = animto[0] - initcr[0]; + var iy1 = animto[1] - initcr[1]; + var ix2 = animto[2] - initcr[2]; + var iy2 = animto[3] - initcr[3]; + var pcent = 0; + var velocity = options.swingSpeed; + + Selection.animMode(true); + + var animator = function() + { + return function() + { + pcent += (100 - pcent) / velocity; + + animat[0] = x + ((pcent / 100) * ix1); + animat[1] = y + ((pcent / 100) * iy1); + animat[2] = x2 + ((pcent / 100) * ix2); + animat[3] = y2 + ((pcent / 100) * iy2); + + if (pcent < 100) animateStart(); + else Selection.done(); + + if (pcent >= 99.8) pcent = 100; + + setSelectRaw(animat); + }; + }(); + + function animateStart() + { window.setTimeout(animator,interv); }; + + animateStart(); + }; + /*}}}*/ + function setSelect(rect)//{{{ + { + setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]); + }; + //}}} + function setSelectRaw(l) /*{{{*/ + { + Coords.setPressed([l[0],l[1]]); + Coords.setCurrent([l[2],l[3]]); + Selection.update(); + }; + /*}}}*/ + function setOptions(opt)/*{{{*/ + { + if (typeof(opt) != 'object') opt = { }; + options = $.extend(options,opt); + + if (typeof(options.onChange)!=='function') + options.onChange = function() { }; + + if (typeof(options.onSelect)!=='function') + options.onSelect = function() { }; + + }; + /*}}}*/ + function tellSelect()/*{{{*/ + { + return unscale(Coords.getFixed()); + }; + /*}}}*/ + function tellScaled()/*{{{*/ + { + return Coords.getFixed(); + }; + /*}}}*/ + function setOptionsNew(opt)/*{{{*/ + { + setOptions(opt); + interfaceUpdate(); + }; + /*}}}*/ + function disableCrop()//{{{ + { + options.disabled = true; + Selection.disableHandles(); + Selection.setCursor('default'); + Tracker.setCursor('default'); + }; + //}}} + function enableCrop()//{{{ + { + options.disabled = false; + interfaceUpdate(); + }; + //}}} + function cancelCrop()//{{{ + { + Selection.done(); + Tracker.activateHandlers(null,null); + }; + //}}} + function destroy()//{{{ + { + $div.remove(); + $origimg.show(); + }; + //}}} + + function interfaceUpdate(alt)//{{{ + // This method tweaks the interface based on options object. + // Called when options are changed and at end of initialization. + { + options.allowResize ? + alt?Selection.enableOnly():Selection.enableHandles(): + Selection.disableHandles(); + + Tracker.setCursor( options.allowSelect? 'crosshair': 'default' ); + Selection.setCursor( options.allowMove? 'move': 'default' ); + + $div.css('backgroundColor',options.bgColor); + + if ('setSelect' in options) { + setSelect(opt.setSelect); + Selection.done(); + delete(options.setSelect); + } + + if ('trueSize' in options) { + xscale = options.trueSize[0] / boundx; + yscale = options.trueSize[1] / boundy; + } + + xlimit = options.maxSize[0] || 0; + ylimit = options.maxSize[1] || 0; + xmin = options.minSize[0] || 0; + ymin = options.minSize[1] || 0; + + if ('outerImage' in options) + { + $img.attr('src',options.outerImage); + delete(options.outerImage); + } + + Selection.refresh(); + }; + //}}} + + // }}} + + $hdl_holder.hide(); + interfaceUpdate(true); + + var api = { + animateTo: animateTo, + setSelect: setSelect, + setOptions: setOptionsNew, + tellSelect: tellSelect, + tellScaled: tellScaled, + + disable: disableCrop, + enable: enableCrop, + cancel: cancelCrop, + + focus: KeyManager.watchKeys, + + getBounds: function() { return [ boundx * xscale, boundy * yscale ]; }, + getWidgetSize: function() { return [ boundx, boundy ]; }, + + release: Selection.release, + destroy: destroy + + }; + + $origimg.data('Jcrop',api); + return api; +}; + +$.fn.Jcrop = function(options)/*{{{*/ +{ + function attachWhenDone(from)/*{{{*/ + { + var loadsrc = options.useImg || from.src; + var img = new Image(); + img.onload = function() { $.Jcrop(from,options); }; + img.src = loadsrc; + }; + /*}}}*/ + if (typeof(options) !== 'object') options = { }; + + // Iterate over each object, attach Jcrop + this.each(function() + { + // If we've already attached to this object + if ($(this).data('Jcrop')) + { + // The API can be requested this way (undocumented) + if (options == 'api') return $(this).data('Jcrop'); + // Otherwise, we just reset the options... + else $(this).data('Jcrop').setOptions(options); + } + // If we haven't been attached, preload and attach + else attachWhenDone(this); + }); + + // Return "this" so we're chainable a la jQuery plugin-style! + return this; +}; +/*}}}*/ + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/jquery.numeric.js b/Toolkit/PHPImageEditor/javascript/jquery.numeric.js new file mode 100644 index 0000000..5c5aae7 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/jquery.numeric.js @@ -0,0 +1,127 @@ +/* + * + * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk) + * Licensed under the MIT License: + * http://www.opensource.org/licenses/mit-license.php + * + * Version 1.0 + * Demo: http://www.texotela.co.uk/code/jquery/numeric/ + * + * $LastChangedDate: 2007-05-29 11:31:36 +0100 (Tue, 29 May 2007) $ + * $Rev: 2005 $ + */ + +/* + * Allows only valid characters to be entered into input boxes. + * Note: does not validate that the final text is a valid number + * (that could be done by another script, or server-side) + * + * @name numeric + * @param decimal Decimal separator (e.g. '.' or ',' - default is '.') + * @param callback A function that runs if the number is not valid (fires onblur) + * @author Sam Collett (http://www.texotela.co.uk) + * @example $(".numeric").numeric(); + * @example $(".numeric").numeric(","); + * @example $(".numeric").numeric(null, callback); + * + */ +jQuery.fn.numeric = function(decimal, callback) +{ + decimal = decimal || "."; + callback = typeof callback == "function" ? callback : function(){}; + this.keypress( + function(e) + { + var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; + // allow enter/return key (only when in an input box) + if(key == 13 && this.nodeName.toLowerCase() == "input") + { + return true; + } + else if(key == 13) + { + return false; + } + var allow = false; + // allow Ctrl+A + if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true; + // allow Ctrl+X (cut) + if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true; + // allow Ctrl+C (copy) + if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true; + // allow Ctrl+Z (undo) + if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true; + // allow or deny Ctrl+V (paste), Shift+Ins + if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */ + || (e.shiftKey && key == 45)) return true; + // if a number was not pressed + if(key < 48 || key > 57) + { + /* '-' only allowed at start */ + if(key == 45 && this.value.length == 0) return true; + /* only one decimal separator allowed */ + if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) + { + allow = false; + } + // check for other keys that have special purposes + if( + key != 8 /* backspace */ && + key != 9 /* tab */ && + key != 13 /* enter */ && + key != 35 /* end */ && + key != 36 /* home */ && + key != 37 /* left */ && + key != 39 /* right */ && + key != 46 /* del */ + ) + { + allow = false; + } + else + { + // for detecting special keys (listed above) + // IE does not support 'charCode' and ignores them in keypress anyway + if(typeof e.charCode != "undefined") + { + // special keys have 'keyCode' and 'which' the same (e.g. backspace) + if(e.keyCode == e.which && e.which != 0) + { + allow = true; + } + // or keyCode != 0 and 'charCode'/'which' = 0 + else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0) + { + allow = true; + } + } + } + // if key pressed is the decimal and it is not already in the field + if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1) + { + allow = true; + } + } + else + { + allow = true; + } + return allow; + } + ) + .blur( + function() + { + var val = jQuery(this).val(); + if(val != "") + { + var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+"); + if(!re.exec(val)) + { + callback.apply(this); + } + } + } + ); + return this; +} \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/phpimageeditor.js b/Toolkit/PHPImageEditor/javascript/phpimageeditor.js new file mode 100644 index 0000000..bb37f83 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/phpimageeditor.js @@ -0,0 +1,711 @@ +var objCrop = null; + +function ajax_post() +{ + if ($('#loading').css('display') == 'none') { + $('#width').attr('disabled','disabled'); + $('#height').attr('disabled','disabled'); + $('#keepproportions').attr('disabled','disabled'); + $('#btnRotateLeft').attr('disabled','disabled'); + $('#btnRotateRight').attr('disabled','disabled'); + $('#croptop').attr('disabled','disabled'); + $('#cropbottom').attr('disabled','disabled'); + $('#cropleft').attr('disabled','disabled'); + $('#cropright').attr('disabled','disabled'); + $('#grayscale').attr('disabled','disabled'); + $('#btnupdate').attr('disabled','disabled'); + $('#btnsave').attr('disabled','disabled'); + $('#btnundo').attr('disabled','disabled'); + $('#brightness_slider_track').slider('disable'); + $('#contrast_slider_track').slider('disable'); + + $('#loading').css('display','block'); + $('#loading_bar').width(0); + $('#loading_bar').animate({width: document.getElementById('loading').offsetWidth-30}, document.getElementById('loading').offsetWidth*10); + + $.ajax({ + timeout: AjaxPostTimeoutMs, + type: "POST", + url: FormAction, + data: "grayscaleval="+$('#grayscaleval').val()+ + "&keepproportionsval="+$('#keepproportionsval').val()+ + "&image_name="+$('#image_name').val()+ + "&width="+$('#width').val()+ + "&widthoriginal="+$('#widthoriginal').val()+ + "&height="+$('#height').val()+ + "&heightoriginal="+$('#heightoriginal').val()+ + "&rotate="+$('#rotate').val()+ + "&croptop="+$('#croptop').val()+ + "&cropleft="+$('#cropleft').val()+ + "&cropright="+$('#cropright').val()+ + "&cropbottom="+$('#cropbottom').val()+ + "&contrast="+$('#contrast').val()+ + "&brightness="+$('#brightness').val()+ + "&actiontype="+$('#actiontype').val()+ + "&panel="+$('#panel').val()+ + "&language="+$('#language').val()+ + "&actions="+$('#actions').val()+ + "&widthlast="+$('#widthlast').val()+ + "&heightlast="+$('#heightlast').val()+ + "&userid="+$('#userid').val()+ + "&contrastlast="+$('#contrastlast').val()+ + "&brightnesslast="+$('#brightnesslast').val()+ + "&widthlastbeforeresize="+$('#widthlastbeforeresize').val()+ + "&heightlastbeforeresize="+$('#heightlastbeforeresize').val()+ + "&cropkeepproportionsval="+$('#cropkeepproportionsval').val()+ + "&cropkeepproportionsratio="+$('#cropkeepproportionsratio').val()+ + "&isajaxpost=true", + success: function(data) + { + $('#phpImageEditor').html(data); + activate_form(); + phpimageeditor_crop_activator(parseInt($('#panel').val())); + phpimageeditor_init(); + $('#loading_bar').stop(); + $('#loading').css('display','none'); + }, + error: function(XMLHttpRequest, textStatus, errorThrown) + { + activate_form(); + $('#ulJsErrors').html(""); + adderror(TextAnUnexpectedError); + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + phpimageeditor_crop_activator(parseInt($('#panel').val())); + $('#loading_bar').stop(); + $('#loading').css('display','none'); + } + }); + + } +} + +function isinteger(s) +{ + var i; + + if (isempty(s)) + if (isinteger.arguments.length == 1) return 0; + else return (isinteger.arguments[1] == true); + + for (i = 0; i < s.length; i++) + { + var c = s.charAt(i); + + if (!isdigit(c)) return false; + } + + return true; +} + +function focus_on_enter(element, event) +{ + if(event.keyCode == 13) + element.focus(); +} + +function reload_mouse_crop() +{ + objCrop.destroy(); + objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("#cropkeepproportionsratio").val() : 0}); + $(".jcrop-holder").css("display", "none"); + $("#image").css("display", "block"); +} + +function update_width(InputWidth, EditForm) +{ + if (isinteger(InputWidth.val())) + { + var Width = parseInt($('#width').val()); + var Height = parseInt($('#height').val()); + + $('#image').css('width',Width+'px'); + + if ($("input#keepproportions").attr('checked')) + { + $('#image').css('height', get_proportional_height(Width, EditForm) + "px"); + $('#height').val(get_proportional_height(Width, EditForm)); + } + + update_mouse_resizer(); + reload_mouse_crop(); + } +} + +function update_mouse_resizer() +{ + $('#imageResizerKeepProportions').css('width',$('#width').val()+'px'); + $('#imageResizerKeepProportions').css('height',$('#height').val()+'px'); + $('#imageResizerNoProportions').css('width',$('#width').val()+'px'); + $('#imageResizerNoProportions').css('height',$('#height').val()+'px'); +} + +function update_height(InputHeight, EditForm) +{ + if (isinteger(InputHeight.val())) + { + var Height = parseInt($('#height').val()); + var Width = parseInt($('#width').val()); + + $('#image').css('height',$('#height').val()+'px'); + + if ($("input#keepproportions").attr('checked')) + { + $('#image').css('width',get_proportional_width(Height, EditForm)+'px'); + $('#width').val(get_proportional_width(Height, EditForm)); + } + + update_mouse_resizer(); + reload_mouse_crop(); + } +} + +function isempty(s) +{ + return ((s == null) || (s.length == 0)) +} + +function isdigit (c) +{ + return ((c >= "0") && (c <= "9")) +} + +function isintegerinrange(s, a, b) +{ + if (isempty(s)) + if (isintegerinrange.arguments.length == 1) return false; + else return (isintegerinrange.arguments[1] == true); + + // Catch non-integer strings to avoid creating a NaN below, + // which isn't available on JavaScript 1.0 for Windows. + if (!isinteger(s, false)) return false; + + // Now, explicitly change the type to integer via parseInt + // so that the comparison code below will work both on + // JavaScript 1.2 (which typechecks in equality comparisons) + // and JavaScript 1.1 and before (which doesn't). + var num = parseInt (s); + return ((num >= a) && (num <= b)); +} + +function validate_form() +{ + var sendForm = true; + + var width = $('#width').val(); + var height = $('#height').val(); + var cropleft = $('#cropleft').val(); + var cropright = $('#cropright').val(); + var croptop = $('#croptop').val(); + var cropbottom = $('#cropbottom').val(); + var imageName = $('#image_name').val(); + + $('#divJsErrors').css('display','none'); + $('#ulJsErrors').css('display','none'); + + $('#ulJsErrors').html(""); + + if (imageName == "") { + adderror("\"Image Name\" is Required!" ); + sendForm = false; + } + + if (width == "") + { + adderror("\"" + TextWidth + "\" " + TextIsRequired) + sendForm = false; + } + + if (height == "") + { + adderror("\"" + TextHeight + "\" " + TextIsRequired) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + + return sendForm; + } + + if (!isinteger(width)) + { + adderror("\"" + TextWidth + "\" " + TextMustBeNumeric) + sendForm = false; + } + + if (!isinteger(height)) + { + adderror("\"" + TextHeight + "\" " + TextMustBeNumeric) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + return sendForm; + } + + width = parseInt(width); + height = parseInt(height); + + if (!isintegerinrange(width, 1, ImageMaxWidth)) + { + adderror("\"" + TextWidth + "\" " + TextNotInRange + ": 1 - " + ImageMaxWidth) + sendForm = false; + } + + if (!isintegerinrange(height, 1, ImageMaxHeight)) + { + adderror("\"" + TextHeight + "\" " + TextNotInRange + ": 1 - " + ImageMaxHeight) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + } + + return sendForm; +} + +function adderror(ErrorText) +{ + $('#ulJsErrors').html($('#ulJsErrors').html()+'
  • '+ErrorText+'
  • '); +} + +function get_proportional_width(Height, EditForm) +{ + var HeightOriginal = parseInt($("#heightlastbeforeresize").val()); + var WidthOriginal = parseInt($("#widthlastbeforeresize").val()); + + return Math.round((WidthOriginal/HeightOriginal)*Height); +} + +function get_proportional_height(Width, EditForm) +{ + var HeightOriginal = parseInt($("#heightlastbeforeresize").val()); + var WidthOriginal = parseInt($("#widthlastbeforeresize").val()); + + return Math.round((HeightOriginal/WidthOriginal)*Width); +} + +function remove_px(Value) +{ + return Value.replace("px",""); +} + +function activate_form() +{ + $('#width').removeAttr('disabled'); + $('#height').removeAttr('disabled'); + $('#keepproportions').removeAttr('disabled'); + $('#btnRotateLeft').removeAttr('disabled'); + $('#btnRotateRight').removeAttr('disabled'); + $('#croptop').removeAttr('disabled'); + $('#cropbottom').removeAttr('disabled'); + $('#cropleft').removeAttr('disabled'); + $('#cropright').removeAttr('disabled'); + $('#grayscale').removeAttr('disabled'); + $('#btnupdate').removeAttr('disabled'); + $('#btnsave').removeAttr('disabled'); + $('#btnundo').removeAttr('disabled'); + $('#brightness_slider_track').slider('enable'); + $('#contrast_slider_track').slider('enable'); + + if ($('#actions').val() == '') + { + $('#btnundo').attr('disabled','disabled'); + $('#btnsave').attr('disabled','disabled'); + } + else + { + $('#btnundo').removeAttr('disabled'); + $('#btnsave').removeAttr('disabled'); + } +} + + +function set_crop_values(c) +{ + if (isinteger($("#height").val()) && isinteger($("#width").val())) + { + $("#croptop").val(c.y); + $("#cropbottom").val(parseInt($("#height").val()) - (c.y + c.h)); + $("#cropleft").val(c.x); + $("#cropright").val(parseInt($("#width").val()) - (c.x + c.w)); + $("#cropwidth").html(c.w); + $("#cropheight").html(c.h); + } +} + +function phpimageeditor_resize_activator(selectedIndex) +{ + if (selectedIndex == MenuResize) + { + if ($('#keepproportionsval').val() == "1") + { + $("#imageResizerKeepProportions").css("display", "block"); + $("#imageResizerNoProportions").css("display", "none"); + } + else + { + $("#imageResizerKeepProportions").css("display", "none"); + $("#imageResizerNoProportions").css("display", "block"); + } + } + else + { + $("#imageResizerKeepProportions").css("display", "none"); + $("#imageResizerNoProportions").css("display", "none"); + } +} + +function phpimageeditor_panelfade(selectedIndex) +{ + for (i = 0; i < 4; i++) + { + if ($('#panel_'+i) != null) + { + $("#panel_"+i).css('opacity','0.0'); + + if (i == selectedIndex) + { + $("#menuitem_"+i).removeClass("not-selected"); + $("#menuitem_"+i).addClass("selected"); + $("#panel_"+i).css('display','block'); + $("#panel_"+i).fadeTo("normal", 1.0); + } + else + { + $("#menuitem_"+i).removeClass("selected"); + $("#menuitem_"+i).addClass("not-selected"); + $("#panel_"+i).css('display','none'); + } + } + } + + if (selectedIndex != MenuCrop) + { + $("#cropleft").val("0"); + $("#cropright").val("0"); + $("#croptop").val("0"); + $("#cropbottom").val("0"); + $("#cropwidth").html("0"); + $("#cropheight").html("0"); + } + + phpimageeditor_resize_activator(selectedIndex); + phpimageeditor_crop_activator(selectedIndex); + + $("#panel").val(selectedIndex); +} + +function phpimageeditor_crop_activator(selectedIndex) +{ + if (objCrop != null) + { + if (selectedIndex != MenuCrop) + { + objCrop.release(); + objCrop.disable(); + $(".jcrop-holder").css("display", "none"); + $("#image").css("display", "block"); + } + else + { + objCrop.release(); + objCrop.enable(); + $(".jcrop-holder").css("display", "block"); + $("#image").css("display", "block"); + } + } +} + +function phpimageeditor_init() +{ + objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("input#cropkeepproportionsratio").val() : 0}); + + $("#imageResizerKeepProportions").resizable( + { + aspectRatio: parseFloat($("input#widthlastbeforeresize").val()) / parseFloat($("input#heightlastbeforeresize").val()), + stop: function(event,ui) + { + var resize_width = parseInt(remove_px($("#imageResizerKeepProportions").css("width"))); + var resize_height = parseInt(remove_px($("#imageResizerKeepProportions").css("height"))); + + $("#image").css("width", resize_width+"px"); + $("#image").css("height", resize_height+"px"); + $("#width").val(resize_width); + $("#height").val(resize_height); + + update_mouse_resizer(); + + $("#imageResizerKeepProportions").css("opacity", "0.0"); + + reload_mouse_crop(); + }, + start: function(event,ui) + { + $("#imageResizerKeepProportions").css("opacity", "0.5"); + } + }); + + $("#imageResizerNoProportions").resizable( + { + aspectRatio: false, + stop: function(event,ui) + { + var resize_width = parseInt(remove_px($("#imageResizerNoProportions").css("width"))); + var resize_height = parseInt(remove_px($("#imageResizerNoProportions").css("height"))); + + $("#image").css("width", resize_width+"px"); + $("#image").css("height", resize_height+"px"); + $("#width").val(resize_width); + $("#height").val(resize_height); + + update_mouse_resizer(); + + $("#widthlastbeforeresize").val(resize_width); + $("#heightlastbeforeresize").val(resize_height); + $("#imageResizerKeepProportions").resizable('option','aspectRatio',parseFloat($('#widthlastbeforeresize').val())/parseFloat($('#heightlastbeforeresize').val())); + + $("#imageResizerNoProportions").css("opacity", "0.0"); + + reload_mouse_crop(); + }, + start: function(event,ui) + { + $("#imageResizerNoProportions").css("opacity", "0.5"); + } + }); + + $("#contrast_slider_track").slider({value: parseInt($("#contrast").val()) + ContrastMax, min: 1, max: ((ContrastMax*2)+1), step: 1, + stop: function(event,ui) + { + if (validate_form()) + ajax_post(); + }, + slide: function(event, ui) + { + $("#contrast").val(parseInt(ui.value)-((ContrastMax)+1)); + } + }); + + $("#brightness_slider_track").slider({value: (parseInt($("input#brightness").val())+BrightnessMax),min: 1,max: ((BrightnessMax*2)+1),step: 1, + stop: function(event,ui) + { + if (validate_form()) + ajax_post(); + }, + slide: function(event, ui) + { + $("#brightness").val(parseInt(ui.value)-(BrightnessMax+1)); + } + }); + + $("#grayscale").click(function() + { + if (validate_form()) + { + $("#grayscale").attr('checked') ? $('#grayscaleval').val('1') : $('#grayscaleval').val('0'); + ajax_post(); + } + }); + + $("#btnupdate").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionUpdate); + ajax_post(); + } + }); + + $("#btnundo").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionUndo); + ajax_post(); + } + }); + + $("#btnsave").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionSaveAndClose); + ajax_post(); + } + }); + + $("#btnRotateLeft").click(function() + { + if (validate_form()) + { + $("#rotate").val(ActionRotateLeft); + ajax_post(); + } + }); + + $("#btnRotateRight").click(function() + { + if (validate_form()) + { + $("#rotate").val(ActionRotateRight); + ajax_post(); + } + }); + + $("form#" + FormId).submit(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionSaveAndClose); + return true; + } + return false; + }); + + $("#width").keydown(function(event) + { + focus_on_enter($("input#btnupdate"), event); + }); + + $("#width").keyup(function() + { + update_width($(this),$("form#" + FormId)); + }); + + $("#height").keydown(function(event) + { + focus_on_enter($("input#btnupdate"), event); + }); + + $("#height").keyup(function() + { + update_height($(this),$("form#" + FormId)); + }); + + $("#keepproportions").click(function() + { + if ($(this).attr('checked')) + { + $('#keepproportionsval').val('1'); + $('#imageResizerKeepProportions').css('display','block'); + $('#imageResizerNoProportions').css('display','none'); + } + else + { + $('#keepproportionsval').val('0'); + $('#imageResizerKeepProportions').css('display','none'); + $('#imageResizerNoProportions').css('display','block'); + } + }); + + + $("#cropkeepproportions").click(function() + { + if ($(this).attr('checked')) + { + $('#cropkeepproportionsval').val('1'); + } + else + { + $('#cropkeepproportionsval').val('0'); + } + }); + + $("#menuitem_" + MenuResize).click(function() + { + if ($('#panel').val() != MenuResize) + { + phpimageeditor_panelfade(MenuResize); + } + }); + + $("#menuitem_" + MenuRotate).click(function() + { + if ($('#panel').val() != MenuRotate) + { + phpimageeditor_panelfade(MenuRotate); + } + }); + + $("#menuitem_" + MenuCrop).click(function() + { + if ($('#panel').val() != MenuCrop) + { + phpimageeditor_panelfade(MenuCrop); + } + }); + + if ($("#menuitem_" + MenuEffects) != null) + { + $("#menuitem_" + MenuEffects).click(function() + { + if ($('#panel').val() != MenuEffects) + { + phpimageeditor_panelfade(MenuEffects); + } + }); + } + + $('#cropkeepproportions').change(function(e) + { + if (objCrop != null) + { + if (this.checked && parseFloat($("#cropwidth").html()) != 0 && parseFloat($("#cropheight").html()) != 0) + { + var aspectRatio = parseFloat($("#cropwidth").html()) / parseFloat($("#cropheight").html()); + objCrop.setOptions({ aspectRatio: aspectRatio }); + $("#cropkeepproportionsratio").val(aspectRatio); + } + else if (this.checked && parseFloat($("#cropwidth").html()) == 0 && parseFloat($("#cropheight").html()) == 0) + { + objCrop.setOptions({ aspectRatio: $("#cropkeepproportionsratio").val() }); + } + else + { + objCrop.setOptions({ aspectRatio: 0 }); + } + } + }); + + $("input#width").numeric(); + $("input#height").numeric(); + + var selectedIndex = parseInt($('#panel').val()); + for (i = 0; i < 4; i++) + { + if ($('#panel_'+i) != null) + { + if (i == selectedIndex) + { + $("#panel_"+i).css('opacity','1.0'); + $("#panel_"+i).css('display','block'); + } + else + { + $("#panel_"+i).css('opacity','0.0'); + $("#panel_"+i).css('display','none'); + } + } + } + + phpimageeditor_crop_activator(selectedIndex); + phpimageeditor_resize_activator(selectedIndex); +} + +$(document).ready(function() +{ + phpimageeditor_init(); +});define('CKIMAGE_ORIGINAL', TOOLBOX_ORIGINAL); +define('CKIMAGE_RESIZED', TOOLBOX_RESIZED); +define('CKIMAGE_MIDSIZED', TOOLBOX_MIDSIZED); +define('CKIMAGE_THUMB', TOOLBOX_THUMB); \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/ui.core.js b/Toolkit/PHPImageEditor/javascript/ui.core.js new file mode 100644 index 0000000..89300d9 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.core.js @@ -0,0 +1,519 @@ +/* + * jQuery UI 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI + */ +;jQuery.ui || (function($) { + +var _remove = $.fn.remove, + isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); + +//Helper functions and ui object +$.ui = { + version: "1.7", + + // $.ui.plugin is deprecated. Use the proxy pattern instead. + plugin: { + add: function(module, option, set) { + var proto = $.ui[module].prototype; + for(var i in set) { + proto.plugins[i] = proto.plugins[i] || []; + proto.plugins[i].push([option, set[i]]); + } + }, + call: function(instance, name, args) { + var set = instance.plugins[name]; + if(!set || !instance.element[0].parentNode) { return; } + + for (var i = 0; i < set.length; i++) { + if (instance.options[set[i][0]]) { + set[i][1].apply(instance.element, args); + } + } + } + }, + + contains: function(a, b) { + return document.compareDocumentPosition + ? a.compareDocumentPosition(b) & 16 + : a !== b && a.contains(b); + }, + + hasScroll: function(el, a) { + + //If overflow is hidden, the element might have extra content, but the user wants to hide it + if ($(el).css('overflow') == 'hidden') { return false; } + + var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', + has = false; + + if (el[scroll] > 0) { return true; } + + // TODO: determine which cases actually cause this to happen + // if the element doesn't have the scroll set, see if it's possible to + // set the scroll + el[scroll] = 1; + has = (el[scroll] > 0); + el[scroll] = 0; + return has; + }, + + isOverAxis: function(x, reference, size) { + //Determines when x coordinate is over "b" element axis + return (x > reference) && (x < (reference + size)); + }, + + isOver: function(y, x, top, left, height, width) { + //Determines when x, y coordinates is over "b" element + return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); + }, + + keyCode: { + BACKSPACE: 8, + CAPS_LOCK: 20, + COMMA: 188, + CONTROL: 17, + DELETE: 46, + DOWN: 40, + END: 35, + ENTER: 13, + ESCAPE: 27, + HOME: 36, + INSERT: 45, + LEFT: 37, + NUMPAD_ADD: 107, + NUMPAD_DECIMAL: 110, + NUMPAD_DIVIDE: 111, + NUMPAD_ENTER: 108, + NUMPAD_MULTIPLY: 106, + NUMPAD_SUBTRACT: 109, + PAGE_DOWN: 34, + PAGE_UP: 33, + PERIOD: 190, + RIGHT: 39, + SHIFT: 16, + SPACE: 32, + TAB: 9, + UP: 38 + } +}; + +// WAI-ARIA normalization +if (isFF2) { + var attr = $.attr, + removeAttr = $.fn.removeAttr, + ariaNS = "http://www.w3.org/2005/07/aaa", + ariaState = /^aria-/, + ariaRole = /^wairole:/; + + $.attr = function(elem, name, value) { + var set = value !== undefined; + + return (name == 'role' + ? (set + ? attr.call(this, elem, name, "wairole:" + value) + : (attr.apply(this, arguments) || "").replace(ariaRole, "")) + : (ariaState.test(name) + ? (set + ? elem.setAttributeNS(ariaNS, + name.replace(ariaState, "aaa:"), value) + : attr.call(this, elem, name.replace(ariaState, "aaa:"))) + : attr.apply(this, arguments))); + }; + + $.fn.removeAttr = function(name) { + return (ariaState.test(name) + ? this.each(function() { + this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); + }) : removeAttr.call(this, name)); + }; +} + +//jQuery plugins +$.fn.extend({ + remove: function() { + // Safari has a native remove event which actually removes DOM elements, + // so we have to use triggerHandler instead of trigger (#3037). + $("*", this).add(this).each(function() { + $(this).triggerHandler("remove"); + }); + return _remove.apply(this, arguments ); + }, + + enableSelection: function() { + return this + .attr('unselectable', 'off') + .css('MozUserSelect', '') + .unbind('selectstart.ui'); + }, + + disableSelection: function() { + return this + .attr('unselectable', 'on') + .css('MozUserSelect', 'none') + .bind('selectstart.ui', function() { return false; }); + }, + + scrollParent: function() { + var scrollParent; + if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { + scrollParent = this.parents().filter(function() { + return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } else { + scrollParent = this.parents().filter(function() { + return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } + + return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; + } +}); + + +//Additional selectors +$.extend($.expr[':'], { + data: function(elem, i, match) { + return !!$.data(elem, match[3]); + }, + + focusable: function(element) { + var nodeName = element.nodeName.toLowerCase(), + tabIndex = $.attr(element, 'tabindex'); + return (/input|select|textarea|button|object/.test(nodeName) + ? !element.disabled + : 'a' == nodeName || 'area' == nodeName + ? element.href || !isNaN(tabIndex) + : !isNaN(tabIndex)) + // the element and all of its ancestors must be visible + // the browser may report that the area is hidden + && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; + }, + + tabbable: function(element) { + var tabIndex = $.attr(element, 'tabindex'); + return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); + } +}); + + +// $.widget is a factory to create jQuery plugins +// taking some boilerplate code out of the plugin code +function getter(namespace, plugin, method, args) { + function getMethods(type) { + var methods = $[namespace][plugin][type] || []; + return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); + } + + var methods = getMethods('getter'); + if (args.length == 1 && typeof args[0] == 'string') { + methods = methods.concat(getMethods('getterSetter')); + } + return ($.inArray(method, methods) != -1); +} + +$.widget = function(name, prototype) { + var namespace = name.split(".")[0]; + name = name.split(".")[1]; + + // create plugin method + $.fn[name] = function(options) { + var isMethodCall = (typeof options == 'string'), + args = Array.prototype.slice.call(arguments, 1); + + // prevent calls to internal methods + if (isMethodCall && options.substring(0, 1) == '_') { + return this; + } + + // handle getter methods + if (isMethodCall && getter(namespace, name, options, args)) { + var instance = $.data(this[0], name); + return (instance ? instance[options].apply(instance, args) + : undefined); + } + + // handle initialization and non-getter methods + return this.each(function() { + var instance = $.data(this, name); + + // constructor + (!instance && !isMethodCall && + $.data(this, name, new $[namespace][name](this, options))._init()); + + // method call + (instance && isMethodCall && $.isFunction(instance[options]) && + instance[options].apply(instance, args)); + }); + }; + + // create widget constructor + $[namespace] = $[namespace] || {}; + $[namespace][name] = function(element, options) { + var self = this; + + this.namespace = namespace; + this.widgetName = name; + this.widgetEventPrefix = $[namespace][name].eventPrefix || name; + this.widgetBaseClass = namespace + '-' + name; + + this.options = $.extend({}, + $.widget.defaults, + $[namespace][name].defaults, + $.metadata && $.metadata.get(element)[name], + options); + + this.element = $(element) + .bind('setData.' + name, function(event, key, value) { + if (event.target == element) { + return self._setData(key, value); + } + }) + .bind('getData.' + name, function(event, key) { + if (event.target == element) { + return self._getData(key); + } + }) + .bind('remove', function() { + return self.destroy(); + }); + }; + + // add widget prototype + $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); + + // TODO: merge getter and getterSetter properties from widget prototype + // and plugin prototype + $[namespace][name].getterSetter = 'option'; +}; + +$.widget.prototype = { + _init: function() {}, + destroy: function() { + this.element.removeData(this.widgetName) + .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') + .removeAttr('aria-disabled'); + }, + + option: function(key, value) { + var options = key, + self = this; + + if (typeof key == "string") { + if (value === undefined) { + return this._getData(key); + } + options = {}; + options[key] = value; + } + + $.each(options, function(key, value) { + self._setData(key, value); + }); + }, + _getData: function(key) { + return this.options[key]; + }, + _setData: function(key, value) { + this.options[key] = value; + + if (key == 'disabled') { + this.element + [value ? 'addClass' : 'removeClass']( + this.widgetBaseClass + '-disabled' + ' ' + + this.namespace + '-state-disabled') + .attr("aria-disabled", value); + } + }, + + enable: function() { + this._setData('disabled', false); + }, + disable: function() { + this._setData('disabled', true); + }, + + _trigger: function(type, event, data) { + var callback = this.options[type], + eventName = (type == this.widgetEventPrefix + ? type : this.widgetEventPrefix + type); + + event = $.Event(event); + event.type = eventName; + + // copy original event properties over to the new event + // this would happen if we could call $.event.fix instead of $.Event + // but we don't have a way to force an event to be fixed multiple times + if (event.originalEvent) { + for (var i = $.event.props.length, prop; i;) { + prop = $.event.props[--i]; + event[prop] = event.originalEvent[prop]; + } + } + + this.element.trigger(event, data); + + return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false + || event.isDefaultPrevented()); + } +}; + +$.widget.defaults = { + disabled: false +}; + + +/** Mouse Interaction Plugin **/ + +$.ui.mouse = { + _mouseInit: function() { + var self = this; + + this.element + .bind('mousedown.'+this.widgetName, function(event) { + return self._mouseDown(event); + }) + .bind('click.'+this.widgetName, function(event) { + if(self._preventClickEvent) { + self._preventClickEvent = false; + event.stopImmediatePropagation(); + return false; + } + }); + + // Prevent text selection in IE + if ($.browser.msie) { + this._mouseUnselectable = this.element.attr('unselectable'); + this.element.attr('unselectable', 'on'); + } + + this.started = false; + }, + + // TODO: make sure destroying one instance of mouse doesn't mess with + // other instances of mouse + _mouseDestroy: function() { + this.element.unbind('.'+this.widgetName); + + // Restore text selection in IE + ($.browser.msie + && this.element.attr('unselectable', this._mouseUnselectable)); + }, + + _mouseDown: function(event) { + // don't let more than one widget handle mouseStart + // TODO: figure out why we have to use originalEvent + event.originalEvent = event.originalEvent || {}; + if (event.originalEvent.mouseHandled) { return; } + + // we may have missed mouseup (out of window) + (this._mouseStarted && this._mouseUp(event)); + + this._mouseDownEvent = event; + + var self = this, + btnIsLeft = (event.which == 1), + elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); + if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { + return true; + } + + this.mouseDelayMet = !this.options.delay; + if (!this.mouseDelayMet) { + this._mouseDelayTimer = setTimeout(function() { + self.mouseDelayMet = true; + }, this.options.delay); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = (this._mouseStart(event) !== false); + if (!this._mouseStarted) { + event.preventDefault(); + return true; + } + } + + // these delegates are required to keep context + this._mouseMoveDelegate = function(event) { + return self._mouseMove(event); + }; + this._mouseUpDelegate = function(event) { + return self._mouseUp(event); + }; + $(document) + .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + // preventDefault() is used to prevent the selection of text here - + // however, in Safari, this causes select boxes not to be selectable + // anymore, so this fix is needed + ($.browser.safari || event.preventDefault()); + + event.originalEvent.mouseHandled = true; + return true; + }, + + _mouseMove: function(event) { + // IE mouseup check - mouseup happened when mouse was out of window + if ($.browser.msie && !event.button) { + return this._mouseUp(event); + } + + if (this._mouseStarted) { + this._mouseDrag(event); + return event.preventDefault(); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = + (this._mouseStart(this._mouseDownEvent, event) !== false); + (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); + } + + return !this._mouseStarted; + }, + + _mouseUp: function(event) { + $(document) + .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + if (this._mouseStarted) { + this._mouseStarted = false; + this._preventClickEvent = (event.target == this._mouseDownEvent.target); + this._mouseStop(event); + } + + return false; + }, + + _mouseDistanceMet: function(event) { + return (Math.max( + Math.abs(this._mouseDownEvent.pageX - event.pageX), + Math.abs(this._mouseDownEvent.pageY - event.pageY) + ) >= this.options.distance + ); + }, + + _mouseDelayMet: function(event) { + return this.mouseDelayMet; + }, + + // These are placeholder methods, to be overriden by extending plugin + _mouseStart: function(event) {}, + _mouseDrag: function(event) {}, + _mouseStop: function(event) {}, + _mouseCapture: function(event) { return true; } +}; + +$.ui.mouse.defaults = { + cancel: null, + distance: 1, + delay: 0 +}; + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/ui.resizable.js b/Toolkit/PHPImageEditor/javascript/ui.resizable.js new file mode 100644 index 0000000..0e4b894 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.resizable.js @@ -0,0 +1,800 @@ +/* + * jQuery UI Resizable 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Resizables + * + * Depends: + * ui.core.js + */ +(function($) { + +$.widget("ui.resizable", $.extend({}, $.ui.mouse, { + + _init: function() { + + var self = this, o = this.options; + this.element.addClass("ui-resizable"); + + $.extend(this, { + _aspectRatio: !!(o.aspectRatio), + aspectRatio: o.aspectRatio, + originalElement: this.element, + _proportionallyResizeElements: [], + _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null + }); + + //Wrap the element if it cannot hold child nodes + if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { + + //Opera fix for relative positioning + if (/relative/.test(this.element.css('position')) && $.browser.opera) + this.element.css({ position: 'relative', top: 'auto', left: 'auto' }); + + //Create a wrapper element and set the wrapper to the new current internal element + this.element.wrap( + $('
    ').css({ + position: this.element.css('position'), + width: this.element.outerWidth(), + height: this.element.outerHeight(), + top: this.element.css('top'), + left: this.element.css('left') + }) + ); + + //Overwrite the original this.element + this.element = this.element.parent().data( + "resizable", this.element.data('resizable') + ); + + this.elementIsWrapper = true; + + //Move margins to the wrapper + this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); + this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); + + //Prevent Safari textarea resize + this.originalResizeStyle = this.originalElement.css('resize'); + this.originalElement.css('resize', 'none'); + + //Push the actual element to our proportionallyResize internal array + this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); + + // avoid IE jump (hard set the margin) + this.originalElement.css({ margin: this.originalElement.css('margin') }); + + // fix handlers offset + this._proportionallyResize(); + + } + + this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' }); + if(this.handles.constructor == String) { + + if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw'; + var n = this.handles.split(","); this.handles = {}; + + for(var i = 0; i < n.length; i++) { + + var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; + var axis = $('
    '); + + // increase zIndex of sw, se, ne, nw axis + //TODO : this modifies original option + if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex }); + + //TODO : What's going on here? + if ('se' == handle) { + axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se'); + }; + + //Insert into internal handles object and append to element + this.handles[handle] = '.ui-resizable-'+handle; + this.element.append(axis); + } + + } + + this._renderAxis = function(target) { + + target = target || this.element; + + for(var i in this.handles) { + + if(this.handles[i].constructor == String) + this.handles[i] = $(this.handles[i], this.element).show(); + + //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) + if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { + + var axis = $(this.handles[i], this.element), padWrapper = 0; + + //Checking the correct pad and border + padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); + + //The padding type i have to apply... + var padPos = [ 'padding', + /ne|nw|n/.test(i) ? 'Top' : + /se|sw|s/.test(i) ? 'Bottom' : + /^e$/.test(i) ? 'Right' : 'Left' ].join(""); + + target.css(padPos, padWrapper); + + this._proportionallyResize(); + + } + + //TODO: What's that good for? There's not anything to be executed left + if(!$(this.handles[i]).length) + continue; + + } + }; + + //TODO: make renderAxis a prototype function + this._renderAxis(this.element); + + this._handles = $('.ui-resizable-handle', this.element) + .disableSelection(); + + //Matching axis name + this._handles.mouseover(function() { + if (!self.resizing) { + if (this.className) + var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); + //Axis, default = se + self.axis = axis && axis[1] ? axis[1] : 'se'; + } + }); + + //If we want to auto hide the elements + if (o.autoHide) { + this._handles.hide(); + $(this.element) + .addClass("ui-resizable-autohide") + .hover(function() { + $(this).removeClass("ui-resizable-autohide"); + self._handles.show(); + }, + function(){ + if (!self.resizing) { + $(this).addClass("ui-resizable-autohide"); + self._handles.hide(); + } + }); + } + + //Initialize the mouse interaction + this._mouseInit(); + + }, + + destroy: function() { + + this._mouseDestroy(); + + var _destroy = function(exp) { + $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") + .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); + }; + + //TODO: Unwrap at same DOM position + if (this.elementIsWrapper) { + _destroy(this.element); + var wrapper = this.element; + wrapper.parent().append( + this.originalElement.css({ + position: wrapper.css('position'), + width: wrapper.outerWidth(), + height: wrapper.outerHeight(), + top: wrapper.css('top'), + left: wrapper.css('left') + }) + ).end().remove(); + } + + this.originalElement.css('resize', this.originalResizeStyle); + _destroy(this.originalElement); + + }, + + _mouseCapture: function(event) { + + var handle = false; + for(var i in this.handles) { + if($(this.handles[i])[0] == event.target) handle = true; + } + + return this.options.disabled || !!handle; + + }, + + _mouseStart: function(event) { + + var o = this.options, iniPos = this.element.position(), el = this.element; + + this.resizing = true; + this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; + + // bugfix for http://dev.jquery.com/ticket/1749 + if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { + el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); + } + + //Opera fixing relative position + if ($.browser.opera && (/relative/).test(el.css('position'))) + el.css({ position: 'relative', top: 'auto', left: 'auto' }); + + this._renderProxy(); + + var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top')); + + if (o.containment) { + curleft += $(o.containment).scrollLeft() || 0; + curtop += $(o.containment).scrollTop() || 0; + } + + //Store needed variables + this.offset = this.helper.offset(); + this.position = { left: curleft, top: curtop }; + this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalPosition = { left: curleft, top: curtop }; + this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; + this.originalMousePosition = { left: event.pageX, top: event.pageY }; + + //Aspect Ratio + this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); + + var cursor = $('.ui-resizable-' + this.axis).css('cursor'); + $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor); + + el.addClass("ui-resizable-resizing"); + this._propagate("start", event); + return true; + }, + + _mouseDrag: function(event) { + + //Increase performance, avoid regex + var el = this.helper, o = this.options, props = {}, + self = this, smp = this.originalMousePosition, a = this.axis; + + var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0; + var trigger = this._change[a]; + if (!trigger) return false; + + // Calculate the attrs that will be change + var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff; + + if (this._aspectRatio || event.shiftKey) + data = this._updateRatio(data, event); + + data = this._respectSize(data, event); + + // plugins callbacks need to be called first + this._propagate("resize", event); + + el.css({ + top: this.position.top + "px", left: this.position.left + "px", + width: this.size.width + "px", height: this.size.height + "px" + }); + + if (!this._helper && this._proportionallyResizeElements.length) + this._proportionallyResize(); + + this._updateCache(data); + + // calling the user callback at the end + this._trigger('resize', event, this.ui()); + + return false; + }, + + _mouseStop: function(event) { + + this.resizing = false; + var o = this.options, self = this; + + if(this._helper) { + var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + if (!o.animate) + this.element.css($.extend(s, { top: top, left: left })); + + self.helper.height(self.size.height); + self.helper.width(self.size.width); + + if (this._helper && !o.animate) this._proportionallyResize(); + } + + $('body').css('cursor', 'auto'); + + this.element.removeClass("ui-resizable-resizing"); + + this._propagate("stop", event); + + if (this._helper) this.helper.remove(); + return false; + + }, + + _updateCache: function(data) { + var o = this.options; + this.offset = this.helper.offset(); + if (isNumber(data.left)) this.position.left = data.left; + if (isNumber(data.top)) this.position.top = data.top; + if (isNumber(data.height)) this.size.height = data.height; + if (isNumber(data.width)) this.size.width = data.width; + }, + + _updateRatio: function(data, event) { + + var o = this.options, cpos = this.position, csize = this.size, a = this.axis; + + if (data.height) data.width = (csize.height * this.aspectRatio); + else if (data.width) data.height = (csize.width / this.aspectRatio); + + if (a == 'sw') { + data.left = cpos.left + (csize.width - data.width); + data.top = null; + } + if (a == 'nw') { + data.top = cpos.top + (csize.height - data.height); + data.left = cpos.left + (csize.width - data.width); + } + + return data; + }, + + _respectSize: function(data, event) { + + var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis, + ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), + isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height); + + if (isminw) data.width = o.minWidth; + if (isminh) data.height = o.minHeight; + if (ismaxw) data.width = o.maxWidth; + if (ismaxh) data.height = o.maxHeight; + + var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; + var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); + + if (isminw && cw) data.left = dw - o.minWidth; + if (ismaxw && cw) data.left = dw - o.maxWidth; + if (isminh && ch) data.top = dh - o.minHeight; + if (ismaxh && ch) data.top = dh - o.maxHeight; + + // fixing jump error on top/left - bug #2330 + var isNotwh = !data.width && !data.height; + if (isNotwh && !data.left && data.top) data.top = null; + else if (isNotwh && !data.top && data.left) data.left = null; + + return data; + }, + + _proportionallyResize: function() { + + var o = this.options; + if (!this._proportionallyResizeElements.length) return; + var element = this.helper || this.element; + + for (var i=0; i < this._proportionallyResizeElements.length; i++) { + + var prel = this._proportionallyResizeElements[i]; + + if (!this.borderDif) { + var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], + p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; + + this.borderDif = $.map(b, function(v, i) { + var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; + return border + padding; + }); + } + + if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length))) + continue; + + prel.css({ + height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, + width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 + }); + + }; + + }, + + _renderProxy: function() { + + var el = this.element, o = this.options; + this.elementOffset = el.offset(); + + if(this._helper) { + + this.helper = this.helper || $('
    '); + + // fix ie6 offset TODO: This seems broken + var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0), + pxyoffset = ( ie6 ? 2 : -1 ); + + this.helper.addClass(this._helper).css({ + width: this.element.outerWidth() + pxyoffset, + height: this.element.outerHeight() + pxyoffset, + position: 'absolute', + left: this.elementOffset.left - ie6offset +'px', + top: this.elementOffset.top - ie6offset +'px', + zIndex: ++o.zIndex //TODO: Don't modify option + }); + + this.helper + .appendTo("body") + .disableSelection(); + + } else { + this.helper = this.element; + } + + }, + + _change: { + e: function(event, dx, dy) { + return { width: this.originalSize.width + dx }; + }, + w: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { left: sp.left + dx, width: cs.width - dx }; + }, + n: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { top: sp.top + dy, height: cs.height - dy }; + }, + s: function(event, dx, dy) { + return { height: this.originalSize.height + dy }; + }, + se: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + sw: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + }, + ne: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + nw: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + } + }, + + _propagate: function(n, event) { + $.ui.plugin.call(this, n, [event, this.ui()]); + (n != "resize" && this._trigger(n, event, this.ui())); + }, + + plugins: {}, + + ui: function() { + return { + originalElement: this.originalElement, + element: this.element, + helper: this.helper, + position: this.position, + size: this.size, + originalSize: this.originalSize, + originalPosition: this.originalPosition + }; + } + +})); + +$.extend($.ui.resizable, { + version: "1.7", + eventPrefix: "resize", + defaults: { + alsoResize: false, + animate: false, + animateDuration: "slow", + animateEasing: "swing", + aspectRatio: false, + autoHide: false, + cancel: ":input,option", + containment: false, + delay: 0, + distance: 1, + ghost: false, + grid: false, + handles: "e,s,se", + helper: false, + maxHeight: null, + maxWidth: null, + minHeight: 10, + minWidth: 10, + zIndex: 1000 + } +}); + +/* + * Resizable Extensions + */ + +$.ui.plugin.add("resizable", "alsoResize", { + + start: function(event, ui) { + + var self = $(this).data("resizable"), o = self.options; + + _store = function(exp) { + $(exp).each(function() { + $(this).data("resizable-alsoresize", { + width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10), + left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10) + }); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) { + if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } + else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); } + }else{ + _store(o.alsoResize); + } + }, + + resize: function(event, ui){ + var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition; + + var delta = { + height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0, + top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0 + }, + + _alsoResize = function(exp, c) { + $(exp).each(function() { + var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left']; + + $.each(css || ['width', 'height', 'top', 'left'], function(i, prop) { + var sum = (start[prop]||0) + (delta[prop]||0); + if (sum && sum >= 0) + style[prop] = sum || null; + }); + + //Opera fixing relative position + if (/relative/.test(el.css('position')) && $.browser.opera) { + self._revertToRelativePosition = true; + el.css({ position: 'absolute', top: 'auto', left: 'auto' }); + } + + el.css(style); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { + $.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); }); + }else{ + _alsoResize(o.alsoResize); + } + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"); + + //Opera fixing relative position + if (self._revertToRelativePosition && $.browser.opera) { + self._revertToRelativePosition = false; + el.css({ position: 'relative' }); + } + + $(this).removeData("resizable-alsoresize-start"); + } +}); + +$.ui.plugin.add("resizable", "animate", { + + stop: function(event, ui) { + var self = $(this).data("resizable"), o = self.options; + + var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + self.element.animate( + $.extend(style, top && left ? { top: top, left: left } : {}), { + duration: o.animateDuration, + easing: o.animateEasing, + step: function() { + + var data = { + width: parseInt(self.element.css('width'), 10), + height: parseInt(self.element.css('height'), 10), + top: parseInt(self.element.css('top'), 10), + left: parseInt(self.element.css('left'), 10) + }; + + if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height }); + + // propagating resize, and updating values for each animation step + self._updateCache(data); + self._propagate("resize", event); + + } + } + ); + } + +}); + +$.ui.plugin.add("resizable", "containment", { + + start: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, el = self.element; + var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; + if (!ce) return; + + self.containerElement = $(ce); + + if (/document/.test(oc) || oc == document) { + self.containerOffset = { left: 0, top: 0 }; + self.containerPosition = { left: 0, top: 0 }; + + self.parentData = { + element: $(document), left: 0, top: 0, + width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight + }; + } + + // i'm a node, so compute top, left, right, bottom + else { + var element = $(ce), p = []; + $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); + + self.containerOffset = element.offset(); + self.containerPosition = element.position(); + self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; + + var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width, + width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); + + self.parentData = { + element: ce, left: co.left, top: co.top, width: width, height: height + }; + } + }, + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, + ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position, + pRatio = o._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement; + + if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co; + + if (cp.left < (self._helper ? co.left : 0)) { + self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left)); + if (pRatio) self.size.height = self.size.width / o.aspectRatio; + self.position.left = o.helper ? co.left : 0; + } + + if (cp.top < (self._helper ? co.top : 0)) { + self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top); + if (pRatio) self.size.width = self.size.height * o.aspectRatio; + self.position.top = self._helper ? co.top : 0; + } + + self.offset.left = self.parentData.left+self.position.left; + self.offset.top = self.parentData.top+self.position.top; + + var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ), + hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height ); + + var isParent = self.containerElement.get(0) == self.element.parent().get(0), + isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position')); + + if(isParent && isOffsetRelative) woset -= self.parentData.left; + + if (woset + self.size.width >= self.parentData.width) { + self.size.width = self.parentData.width - woset; + if (pRatio) self.size.height = self.size.width / o.aspectRatio; + } + + if (hoset + self.size.height >= self.parentData.height) { + self.size.height = self.parentData.height - hoset; + if (pRatio) self.size.width = self.size.height * o.aspectRatio; + } + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options, cp = self.position, + co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement; + + var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height; + + if (self._helper && !o.animate && (/relative/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + if (self._helper && !o.animate && (/static/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + } +}); + +$.ui.plugin.add("resizable", "ghost", { + + start: function(event, ui) { + + var self = $(this).data("resizable"), o = self.options, cs = self.size; + + self.ghost = self.originalElement.clone(); + self.ghost + .css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) + .addClass('ui-resizable-ghost') + .addClass(typeof o.ghost == 'string' ? o.ghost : ''); + + self.ghost.appendTo(self.helper); + + }, + + resize: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width }); + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0)); + } + +}); + +$.ui.plugin.add("resizable", "grid", { + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey; + o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; + var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); + + if (/^(se|s|e)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + } + else if (/^(ne)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + } + else if (/^(sw)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.left = op.left - ox; + } + else { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + self.position.left = op.left - ox; + } + } + +}); + +var num = function(v) { + return parseInt(v, 10) || 0; +}; + +var isNumber = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/ui.slider.js b/Toolkit/PHPImageEditor/javascript/ui.slider.js new file mode 100644 index 0000000..a7b4d0c --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.slider.js @@ -0,0 +1,511 @@ +/* + * jQuery UI Slider 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Slider + * + * Depends: + * ui.core.js + */ + +(function($) { + +$.widget("ui.slider", $.extend({}, $.ui.mouse, { + + _init: function() { + + var self = this, o = this.options; + this._keySliding = false; + this._handleIndex = null; + this._detectOrientation(); + this._mouseInit(); + + this.element + .addClass("ui-slider" + + " ui-slider-" + this.orientation + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all"); + + this.range = $([]); + + if (o.range) { + + if (o.range === true) { + this.range = $('
    '); + if (!o.values) o.values = [this._valueMin(), this._valueMin()]; + if (o.values.length && o.values.length != 2) { + o.values = [o.values[0], o.values[0]]; + } + } else { + this.range = $('
    '); + } + + this.range + .appendTo(this.element) + .addClass("ui-slider-range"); + + if (o.range == "min" || o.range == "max") { + this.range.addClass("ui-slider-range-" + o.range); + } + + // note: this isn't the most fittingly semantic framework class for this element, + // but worked best visually with a variety of themes + this.range.addClass("ui-widget-header"); + + } + + if ($(".ui-slider-handle", this.element).length == 0) + $('') + .appendTo(this.element) + .addClass("ui-slider-handle"); + + if (o.values && o.values.length) { + while ($(".ui-slider-handle", this.element).length < o.values.length) + $('') + .appendTo(this.element) + .addClass("ui-slider-handle"); + } + + this.handles = $(".ui-slider-handle", this.element) + .addClass("ui-state-default" + + " ui-corner-all"); + + this.handle = this.handles.eq(0); + + this.handles.add(this.range).filter("a") + .click(function(event) { event.preventDefault(); }) + .hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); }) + .focus(function() { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); }) + .blur(function() { $(this).removeClass('ui-state-focus'); }); + + this.handles.each(function(i) { + $(this).data("index.ui-slider-handle", i); + }); + + this.handles.keydown(function(event) { + + var ret = true; + + var index = $(this).data("index.ui-slider-handle"); + + if (self.options.disabled) + return; + + switch (event.keyCode) { + case $.ui.keyCode.HOME: + case $.ui.keyCode.END: + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + ret = false; + if (!self._keySliding) { + self._keySliding = true; + $(this).addClass("ui-state-active"); + self._start(event, index); + } + break; + } + + var curVal, newVal, step = self._step(); + if (self.options.values && self.options.values.length) { + curVal = newVal = self.values(index); + } else { + curVal = newVal = self.value(); + } + + switch (event.keyCode) { + case $.ui.keyCode.HOME: + newVal = self._valueMin(); + break; + case $.ui.keyCode.END: + newVal = self._valueMax(); + break; + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + if(curVal == self._valueMax()) return; + newVal = curVal + step; + break; + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + if(curVal == self._valueMin()) return; + newVal = curVal - step; + break; + } + + self._slide(event, index, newVal); + + return ret; + + }).keyup(function(event) { + + var index = $(this).data("index.ui-slider-handle"); + + if (self._keySliding) { + self._stop(event, index); + self._change(event, index); + self._keySliding = false; + $(this).removeClass("ui-state-active"); + } + + }); + + this._refreshValue(); + + }, + + destroy: function() { + + this.handles.remove(); + + this.element + .removeClass("ui-slider" + + " ui-slider-horizontal" + + " ui-slider-vertical" + + " ui-slider-disabled" + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all") + .removeData("slider") + .unbind(".slider"); + + this._mouseDestroy(); + + }, + + _mouseCapture: function(event) { + + var o = this.options; + + if (o.disabled) + return false; + + this.elementSize = { + width: this.element.outerWidth(), + height: this.element.outerHeight() + }; + this.elementOffset = this.element.offset(); + + var position = { x: event.pageX, y: event.pageY }; + var normValue = this._normValueFromMouse(position); + + var distance = this._valueMax() + 1, closestHandle; + var self = this, index; + this.handles.each(function(i) { + var thisDistance = Math.abs(normValue - self.values(i)); + if (distance > thisDistance) { + distance = thisDistance; + closestHandle = $(this); + index = i; + } + }); + + // workaround for bug #3736 (if both handles of a range are at 0, + // the first is always used as the one with least distance, + // and moving it is obviously prevented by preventing negative ranges) + if(o.range == true && this.values(1) == o.min) { + closestHandle = $(this.handles[++index]); + } + + this._start(event, index); + + self._handleIndex = index; + + closestHandle + .addClass("ui-state-active") + .focus(); + + var offset = closestHandle.offset(); + var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle'); + this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { + left: event.pageX - offset.left - (closestHandle.width() / 2), + top: event.pageY - offset.top + - (closestHandle.height() / 2) + - (parseInt(closestHandle.css('borderTopWidth'),10) || 0) + - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0) + + (parseInt(closestHandle.css('marginTop'),10) || 0) + }; + + normValue = this._normValueFromMouse(position); + this._slide(event, index, normValue); + return true; + + }, + + _mouseStart: function(event) { + return true; + }, + + _mouseDrag: function(event) { + + var position = { x: event.pageX, y: event.pageY }; + var normValue = this._normValueFromMouse(position); + + this._slide(event, this._handleIndex, normValue); + + return false; + + }, + + _mouseStop: function(event) { + + this.handles.removeClass("ui-state-active"); + this._stop(event, this._handleIndex); + this._change(event, this._handleIndex); + this._handleIndex = null; + this._clickOffset = null; + + return false; + + }, + + _detectOrientation: function() { + this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal'; + }, + + _normValueFromMouse: function(position) { + + var pixelTotal, pixelMouse; + if ('horizontal' == this.orientation) { + pixelTotal = this.elementSize.width; + pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0); + } else { + pixelTotal = this.elementSize.height; + pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0); + } + + var percentMouse = (pixelMouse / pixelTotal); + if (percentMouse > 1) percentMouse = 1; + if (percentMouse < 0) percentMouse = 0; + if ('vertical' == this.orientation) + percentMouse = 1 - percentMouse; + + var valueTotal = this._valueMax() - this._valueMin(), + valueMouse = percentMouse * valueTotal, + valueMouseModStep = valueMouse % this.options.step, + normValue = this._valueMin() + valueMouse - valueMouseModStep; + + if (valueMouseModStep > (this.options.step / 2)) + normValue += this.options.step; + + // Since JavaScript has problems with large floats, round + // the final value to 5 digits after the decimal point (see #4124) + return parseFloat(normValue.toFixed(5)); + + }, + + _start: function(event, index) { + this._trigger("start", event, this._uiHash(index)); + }, + + _slide: function(event, index, newVal) { + + var handle = this.handles[index]; + + if (this.options.values && this.options.values.length) { + + var otherVal = this.values(index ? 0 : 1); + + if ((index == 0 && newVal >= otherVal) || (index == 1 && newVal <= otherVal)) + newVal = otherVal; + + if (newVal != this.values(index)) { + var newValues = this.values(); + newValues[index] = newVal; + // A slide can be canceled by returning false from the slide callback + var allowed = this._trigger("slide", event, this._uiHash(index, newVal, newValues)); + var otherVal = this.values(index ? 0 : 1); + if (allowed !== false) { + this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true); + } + } + + } else { + + if (newVal != this.value()) { + // A slide can be canceled by returning false from the slide callback + var allowed = this._trigger("slide", event, this._uiHash(index, newVal)); + if (allowed !== false) { + this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate )); + } + + } + + } + + }, + + _stop: function(event, index) { + this._trigger("stop", event, this._uiHash(index)); + }, + + _change: function(event, index) { + this._trigger("change", event, this._uiHash(index)); + }, + + value: function(newValue) { + + if (arguments.length) { + this._setData("value", newValue); + this._change(null, 0); + } + + return this._value(); + + }, + + values: function(index, newValue, animated, noPropagation) { + + if (arguments.length > 1) { + this.options.values[index] = newValue; + this._refreshValue(animated); + if(!noPropagation) this._change(null, index); + } + + if (arguments.length) { + if (this.options.values && this.options.values.length) { + return this._values(index); + } else { + return this.value(); + } + } else { + return this._values(); + } + + }, + + _setData: function(key, value, animated) { + + $.widget.prototype._setData.apply(this, arguments); + + switch (key) { + case 'orientation': + + this._detectOrientation(); + + this.element + .removeClass("ui-slider-horizontal ui-slider-vertical") + .addClass("ui-slider-" + this.orientation); + this._refreshValue(animated); + break; + case 'value': + this._refreshValue(animated); + break; + } + + }, + + _step: function() { + var step = this.options.step; + return step; + }, + + _value: function() { + + var val = this.options.value; + if (val < this._valueMin()) val = this._valueMin(); + if (val > this._valueMax()) val = this._valueMax(); + + return val; + + }, + + _values: function(index) { + + if (arguments.length) { + var val = this.options.values[index]; + if (val < this._valueMin()) val = this._valueMin(); + if (val > this._valueMax()) val = this._valueMax(); + + return val; + } else { + return this.options.values; + } + + }, + + _valueMin: function() { + var valueMin = this.options.min; + return valueMin; + }, + + _valueMax: function() { + var valueMax = this.options.max; + return valueMax; + }, + + _refreshValue: function(animate) { + + var oRange = this.options.range, o = this.options, self = this; + + if (this.options.values && this.options.values.length) { + var vp0, vp1; + this.handles.each(function(i, j) { + var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100; + var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; + $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); + if (self.options.range === true) { + if (self.orientation == 'horizontal') { + (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate); + (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); + } else { + (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate); + (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); + } + } + lastValPercent = valPercent; + }); + } else { + var value = this.value(), + valueMin = this._valueMin(), + valueMax = this._valueMax(), + valPercent = valueMax != valueMin + ? (value - valueMin) / (valueMax - valueMin) * 100 + : 0; + var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; + this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); + + (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate); + (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); + (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate); + (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); + } + + }, + + _uiHash: function(index, value, values) { + + var multiple = this.options.values && this.options.values.length; + return { + handle: this.handles[index], + value: value || (multiple ? this.values(index) : this.value()), + values: values || (multiple && this.values()) + }; + + } + +})); + +$.extend($.ui.slider, { + getter: "value values", + version: "1.7", + eventPrefix: "slide", + defaults: { + animate: false, + delay: 0, + distance: 0, + max: 100, + min: 0, + orientation: 'horizontal', + range: false, + step: 1, + value: 0, + values: null + } +}); + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini b/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini new file mode 100644 index 0000000..0217e7e --- /dev/null +++ b/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini @@ -0,0 +1,37 @@ +#PHP IMAGE EDITOR TEXTS +EDIT IMAGE=Edit Image +RESIZE IMAGE=Resize Image +WIDTH=Width +HEIGHT=Height +KEEP PROPORTIONS=Keep Proportions +ROTATE IMAGE=Rotate Image +LEFT 90 DEGREES=Left 90 Degrees +RIGHT 90 DEGREES=Right 90 Degrees +CROP IMAGE=Crop Image +EFFECTS=Effects +SELECT EFFECT=Select Effect +SAVE AND CLOSE=Save and Close +GRAYSCALE=Grayscale +CONTRAST=Contrast +BRIGHTNESS=Brightness +DARKER=Darker +IS REQUIRED=is required +MUST BE NUMERIC=must be numeric +NOT NEGATIVE=must be a positive number +NOT IN RANGE=is not in valid range +CANT BE LARGER THEN=can´t be larger then +NO PROVIDED IMAGE=No image has been provided. +IMAGE DOES NOT EXIST=The image doesn´t exist. +INVALID IMAGE TYPE=Image must be of type jpeg, png or gif. +OLD PHP VERSION=is too old php version. Minimum is: +OLD GD VERSION=is too old GD version. Minimum is: +UNDO=Undo +UPDATE=Update +LOADING=Loading +AN UNEXPECTED ERROR=An unexpected error has occured, please try again... +RESIZE HELP=Update Width and Height fields.
    Or drag and drop in the right or bottom side of the image. +CROP HELP=Drag and drop to create a crop area on the image. +CROP WIDTH=Crop Width +CROP HEIGHT=Crop Height +CROP KEEP PROPORTIONS=Keep Crop Proportions +INSTRUCTIONS=Instructions \ No newline at end of file diff --git a/Toolkit/Page.php b/Toolkit/Page.php new file mode 100755 index 0000000..ac0d17e --- /dev/null +++ b/Toolkit/Page.php @@ -0,0 +1,690 @@ + + * @copyright 2009 Gaslight Media + * @license http://demo.gaslightmedia.com Gaslight Media + * @version CVS: $Id: Page.php,v 1.80 2010/08/16 17:39:58 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ +/** + * Page for Error Doc + */ +define("ERROR_DOCUMENT", "404.html"); + +/** + * The home page template + */ +define("HOME_TEMPLATE", "template.html"); + +/** + * inside page template + */ +define("INSIDE_TEMPLATE", "template.html"); + +/** + * Template for the error doc + */ +define("ERROR_DOCUMENT_TEMPLATE", "404-template.html"); + +/** + * page title default + */ +define("PAGE_TITLE", SITENAME); + +/** + * Toolkit_Page + * + * A class Object for use with merging into the flexy template for output. + * Sets up the $page object used for merging with the flexy template + * to output the toolbox and members admin content + * + * @category Toolkit + * @package Page + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license http://demo.gaslightmedia.com Gaslight Media + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Page +{ + // {{{ properties + + /** + * used on img src and style href tags + * @var $baseURL + * @access public + */ + public $baseURL; + + /** + * meta tag description element + * @var $metaTags + * @access public + */ + public $metaTags; + + /** + * title tag node + * @var string + * @access public + */ + public $pageTitle; + + /** + * The main content of website + * @var $toolboxContent + * @access public + */ + public $toolboxContent; + private $_breadCrumbs; + private $_toolboxPage; + private $_pageGateway; + private $_paragraphGateway; + private $_navigationFactory; + private $_keywordReplacement; + private $_catid; + + /** + * Creates objects for class Page + * + * @param Toolkit_Template_Page $toolboxPage Toolbox Page + * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory BreadCrumbes + * @param Toolkit_Toolbox_GatewayFactoryAbstract $pageGatewayFactory Page Gateway + * @param Toolkit_Toolbox_GatewayFactoryAbstract $paragraphGatewayFactory Paragraph + * @param Toolkit_NavigationFactoryAbstract $navFactory Navigation + * @param Toolkit_Template_KeywordReplacement $keywordReplacement Keyword replacements + * @param type $catid catid + * + * @return void + */ + public function __construct( + Toolkit_Template_Page $toolboxPage, + Toolkit_BreadCrumbsFactory $breadCrumbsFactory, + Toolkit_Toolbox_GatewayFactoryAbstract $pageGatewayFactory, + Toolkit_Toolbox_GatewayFactoryAbstract $paragraphGatewayFactory, + Toolkit_NavigationFactoryAbstract $navFactory, + Toolkit_Template_KeywordReplacement $keywordReplacement, $catid + ) { + $this->_toolboxPage = $toolboxPage; + $this->_breadCrumbs = $breadCrumbsFactory; + $this->_pageGateway = $pageGatewayFactory->createGateway(); + $this->_paragraphGateway = $paragraphGatewayFactory->createGateway(); + $this->_navigationFactory = $navFactory; + $this->_keywordReplacement = $keywordReplacement; + $this->_catid = $catid; + + // determine the base url to use (for images and stylesheet urls) + $this->baseURL + = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') + ? BASE_SECURE_URL + : BASE_URL; + + // determine the base url to use (for GLM_APP_BASE_URL) + $this->glmAppBaseURL + = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') + ? GLM_APP_BASE_SECURE_URL + : GLM_APP_BASE_URL; + + $this->sitemapURL = $this->baseURL . 'site-map'; + + $this->homePageUrl + = ($_ENV['GLM_HOST_ID'] == 'PRODUCTION') + ? BASE_URL + : BASE_URL . 'index.php'; + + // Resources needed for every page. + $GLOBALS['styleSheets'] = array(); + // Resources needed for every page. + $GLOBALS['topScripts'][] = JQUERY_CDN_JS; + $GLOBALS['bottomScripts'][] + = $this->glmAppBaseURL . 'libjs/external.js'; + if($catid == 8) { + $GLOBALS['styleSheets'][] + = $this->glmAppBaseURL . 'libjs/jqueryui/1.8.13/development-bundle/themes/cupertino/jquery.ui.all.css'; + $GLOBALS['topScripts'][] + = $this->glmAppBaseURL . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js'; + $GLOBALS['bottomScripts'][] + = $this->baseURL . 'libjs/datepicker.js'; + } + $GLOBALS['bottomScripts'][] + = $this->baseURL . 'libjs/pagefunctions.js'; + } + + /** + * Add Banner module + * + * @param array $page toolbox page + * + * @return void + * @access public + */ + public function banners(array $page) + { + $bannerConf = new Config; + $bannerRoot = & $bannerConf->parseConfig( + BASE . 'Toolkit/Banners/config.ini', 'IniFile' + ); + + $dbh = Toolkit_Database::getInstance(); + $banners = & Toolkit_Banners_BannersIterator::create('Bottom'); + if (defined('MEMBERS_DB') && MEMBERS_DB) { + $categoriesIterator = Toolkit_Members_CategoriesIterator::create(); + $banners->fetchAllAvailable( + $dbh, $bannerRoot, $categoriesIterator, $page['id'] + ); + } else { + $banners->fetchAllAssignedToPage($dbh, $bannerRoot, $page['id']); + } + + $availableBanners = $banners->getAvailable(); + + // Are there any banners even available + if (count($availableBanners)) { + $decorators = Toolkit_Banners_StaticBannersDecorator::create(); + foreach ($availableBanners as $i) { + $decorator = Toolkit_Banners_HorizontalDecorator::create($i); + $decorators->add($decorator); + } + + // application configuration + $conf = new Config; + $bannersRoot = & $conf->parseConfig( + BASE . 'Toolkit/Banners/config.ini', 'IniFile' + ); + + $this->hasBanner = count($decorators->getIterator()); + if ($this->hasBanner) { + + $mailerFactory = new Toolkit_Banners_MailerFactory( + $bannersRoot, + $GLOBALS['flexyOptions'] + ); + + $notifier = new Toolkit_Banners_Notifier($mailerFactory, $dbh); + + $this->bannerAds = $decorators->toHtml( + $dbh, new Toolkit_Image_Server(), $notifier, $page['id'] + ); + } + } + } + + /** + * Create the error document page + * + * @return void + * @access public + */ + function createErrorDocument() + { + $this->baseURL = BASE_URL; + $this->homeURL = $this->toolbox->get_seo_url(HOME_ID); + ; + // Initiate HTML_Template_Flexy. + $template = new HTML_Template_Flexy($GLOBALS['flexyOptions']); + + // Create a template object for the 404 content part + $errorDocumentTemplate = new HTML_Template_Flexy($GLOBALS['flexyOptions']); + $errorDocumentTemplate->compile(ERROR_DOCUMENT_TEMPLATE); + $errorDocumentContents = $errorDocumentTemplate->bufferedOutputObject($this); + + // set defaults + $this->toolboxContent = $errorDocumentContents; + $this->pageTitle = '404 Not Found - ' . PAGE_TITLE; + $this->hasHeadlines = false; + $this->hasAreaEvents = false; + $this->hasNews = false; + $this->sideNav = null; + $this->mainNav = $this->toolbox->get_main_nav(); + $this->hasWeather = false; + $this->isHomePage = false; + $this->sitemapURL = false; + + // compile the flexy template + $template->compile(INSIDE_TEMPLATE); + + // Merge compiled template with the object. + $fileContents = $template->bufferedOutputObject($this); + file_put_contents(BASE . ERROR_DOCUMENT, $fileContents); + } + + /** + * Add Event module + * + * @param Toolkit_Template_Page $toolboxPage page template + * @param Toolkit_Toolbox_GatewayAbstract $pageGateway page gateway + * + * @return void + * @access private + */ + private function _events( + Toolkit_Template_Page $toolboxPage, + Toolkit_Toolbox_GatewayAbstract $pageGateway + ) { + $events = new Toolkit_Events_HomeEvents( + Toolkit_Database::getInstance() + ); + $this->events = $events->getHomeEvents(); + $this->hasEvents = !empty($this->events); + $this->eventsUrl = Toolkit_Template_Page::getSeoUrl( + $pageGateway, EVENT_PAGE + ); + } + + /** + * Setup the page with all applications (banners home events navigation) + * + * @return void + */ + public function fetchPage() + { + if (defined('MEMBERS_DB') && MEMBERS_DB) { + // check to see if this page is a member only page + $memberOnlyPage = Toolkit_Template_Page::isMemberOnly( + $this->_pageGateway, $this->_catid + ); + if ($memberOnlyPage + && !strpos($_SERVER['REQUEST_URI'], 'members-only-area') + ) { + header('Location: ' . $this->getToolboxUrl(MEMBERS_CATEGORY)); + } + } + $this->pageTitle = $this->_getPageTitle($this->_catid); + + $bodyFactory = new Toolkit_Template_Page_BodyFactory( + $this->_breadCrumbs, + $this->_pageGateway, + $this->_paragraphGateway, + $this->_keywordReplacement, + new Cache_Lite($GLOBALS['cacheOptions']) + ); + + $this->toolboxContent = $this->_toolboxPage->getBody( + $this->_catid, $bodyFactory + ); + $page = $this->_pageGateway->find($this->_catid); + + // set the metaTags + if ($page['meta_description']) { + $this->metaTags + = htmlentities( + strip_tags($page['meta_description']), ENT_QUOTES, 'UTF-8' + ); + } else { + $this->metaTags + = htmlentities( + substr( + trim(strip_tags($page['description'])), 0, 250 + ), ENT_QUOTES, 'UTF-8' + ); + } + + if (filter_input(INPUT_GET, 'sitemap', FILTER_VALIDATE_INT)) { + $this->isHomePage = false; + } elseif (HOME_ID == $page['id']) { + $this->isHomePage = true; + } else { + $this->isHomePage = false; + } + if ($this->_catid != HOME_ID) { + $this->parentPageId = $this->_pageGateway->findTopParent($this->_catid); + $this->pageId = $this->_catid; + } + $this->_navigationFactory->setGateway($this->_pageGateway); + $this->mainNav = $this->_getMainNav($this->_catid); + $this->sideNav = $this->_getSideNav($this->_catid); + + $this->newsletterAction = Toolkit_Template_Page::getSeoUrl( + $this->_pageGateway, 10 + ); + + $this->tripPlannerCount = isset($_SESSION['wish_list']) + ? count($_SESSION['wish_list']) + : 0; + $this->tripPlannerUrl = Toolkit_Template_Page::getSeoUrl( + $this->_pageGateway, MEMBER_SESSION_PAGE + ); + + // check if define for GOOGLE_SEARCH is set + if (defined("GOOGLE_SEARCH") + && GOOGLE_SEARCH + && isset($_GET['query']) + ) { + $this->_googleSearch(); + } + + // check if define for HOME_EVENTS is set + if (defined("HOME_EVENTS") + && HOME_EVENTS + && $this->isHomePage + ) { + $this->_events($this->_toolboxPage, $this->_pageGateway); + } + + if ( defined("GLM_BLOCKS") + && GLM_BLOCKS + && !filter_input(INPUT_GET, 'sitemap') + && !isset($_GET['query']) + ) { + $this->_getBlocks(); + } + + // check if define for HOME_HEADLINES is set + if (defined("HOME_HEADLINES") + && HOME_HEADLINES + && $this->isHomePage + ) { + $this->_headlines(); + } + + if ( defined("PRESS_DB") + && PRESS_DB + && $page['id'] == PRESS_PAGE_ID + ) { + $this->_getNewsPage(); + } + // check if define for WEATHER is set + if (defined("WEATHER") && WEATHER) { + $this->hasWeather = true; + $this->_weather(); + } + + // check if define for BANNERS is set + if (defined("BANNERS") && BANNERS && is_array($page)) { + $this->banners($page); + } + + if (defined("ROTATING_IMAGES") + && ROTATING_IMAGES + && !filter_input(INPUT_GET, 'sitemap') + && !isset($_GET['query']) + && in_array($page['id'], array(HOME_ID)) + ) { + $this->_rotatingImages(); + } + } + + /** + * Returns page main navigation + * + * @param type $catid page catid + * + * @return type + */ + private function _getMainNav($catid) + { + $nav = $this->_navigationFactory->createMainNav(); + $mainNavArray = $nav->getNavStructure($this->_pageGateway, $catid); + + return $nav->renderPageNav($mainNavArray, 'tree'); + } + + /** + * Returns page title + * + * @param type $id page id + * + * @return string + */ + private function _getPageTitle($id) + { + if (filter_input(INPUT_GET, 'member_id', FILTER_VALIDATE_INT)) { + // Member profile pages can't have search page title tags + return SITENAME; + } + + $page = $this->_pageGateway->find($id); + + if (!empty($page['meta_title'])) { + $title = $page['meta_title']; + } elseif (!empty($page['title'])) { + $title = $page['title']; + } elseif (!empty($page['navigation_name'])) { + $title = $page['navigation_name']; + } + + $title = strip_tags($title); + + $title = isset($title) + ? htmlentities("$title - ", ENT_QUOTES, 'UTF-8') . SITENAME + : SITENAME; + + return $title; + } + + /** + * Returns side navigation + * + * @param type $catid page catid + * + * @return type + */ + private function _getSideNav($catid) + { + if ($catid == HOME_ID) { + return; + } else { + // side nav + $nav + = $this->_navigationFactory->createSideNav($this->_pageGateway); + $sideNavArray = $nav->getNavStructure( + $this->_pageGateway, $catid + ); + return (!empty($sideNavArray)) + ? $nav->renderPageNav($sideNavArray, 'tree') + : ''; + } + } + + /** + * Add Google Search module + * + * @return void + * @access private + */ + private function _googleSearch() + { + $this->gSearchOn = false; + $this->isHomePage = false; + if (isset($_REQUEST['query']) && $_REQUEST['query']) { + $this->gSearchOn = true; + $query = urlencode($_REQUEST['query']); + $GLOBALS['styleSheets'][] = BASE_URL . 'css/gsearch.css'; + $GLOBALS['bottomScripts'][] + = 'http://www.google.com/uds/api?file=uds.js&v=1.0&key=' . + GSEARCH_API; + $GLOBALS['bottomScripts'][] + = BASE_URL . 'libjs/gsearch.php?query=' . $query; + } + } + + /** + * create code for conditional styles + * + * @return type + */ + public function getConditionalStyles() + { + return ' + '; + } + + /** + * grab the navigation name for the id + * + * @param integer $id id for pages table + * + * @return string page nav name + * @access public + */ + function getToolboxName($id) + { + $page = $this->_pageGateway->find($id); + return $page['navigation_name']; + } + + /** + * grab the navigation url for the id + * + * @param integer $id id for pages table + * + * @return string url + * @access public + */ + public function getToolboxUrl($id) + { + return Toolkit_Template_Page::getSeoUrl($this->_pageGateway, $id); + } + + /** + * grab the home page headlines + * + * @return void + * @access private + */ + private function _headlines() + { + // get headlines aka 'Quick Links' + $this->headlines = $this->_pageGateway->getHomePageHeadlines(); + // boolean for if toolbox has headlines + $this->hasHeadlines = !empty($this->headlines); + } + + /** + * grab the GLM Blocks + * + * @return void + * @access private + */ + private function _getBlocks() + { + $cache = new Cache_Lite($GLOBALS['cacheOptions']); + if ($blockContent = $cache->get($this->_catid, 'Block')) { + $this->headlines = unserialize($blockContent); + } else { + $blocks = new Toolkit_Blocks_Display( + Toolkit_Database::getInstance() + ); + $this->headlines + = $blocks->getPageBlocksAsArray((int)$this->_catid); + $cache->save(serialize($this->headlines), $this->_catid, 'Block'); + } + $this->hasHeadlines = !empty($this->headlines); + } + + /** + * Check if this page has photo gallery in it + * + * @return boolean If this page has a photo gallery assigned to it + * @access public + */ + function isPhotoGalleryPage() + { + $sql = " + SELECT photocat_id + FROM photo_category_bus + WHERE buscat_id = {$this->toolbox->catid}"; + if ($pData = $this->toolbox->DB->select($sql)) { + return true; + } + return false; + } + + /** + * grab the home page newsletter/press info + * + * @param object $toolbox Toolbox object + * + * @return void + * @access public + */ + public function news($toolbox) + { + if (HOME_ID == $toolbox->catid) { + $this->news = $toolbox->get_news(); + $this->hasNews = (!empty($this->news)); + } else { + $this->hasNews = false; + } + } + + /** + * Sets toolboxContent with news + * + * @return void + */ + private function _getNewsPage() + { + $dbh = Toolkit_Database::getInstance(); + $press = new Toolkit_Press_Newsletter(); + $this->toolboxContent = $press->toHtml($dbh); + } + + /** + * Sets rotatingImages + * + * @return void + */ + private function _rotatingImages() + { + $gateway = new Toolkit_RotatingImages_Gateway( + Toolkit_Database::getInstance() + ); + $nodesIterator = new Toolkit_RotatingImages_NodesIterator(); + $images = $gateway->findAll(); + foreach ($images as $image) { + $nodesIterator->addImage($image); + } + $is = new Toolkit_FileServer_ImageAdapter(); + $decorator = new Toolkit_RotatingImages_Decorator_User(); + foreach ($nodesIterator as $v) { + if ($v->getActive()) { + $imgDecorator = new Toolkit_RotatingImages_Decorator_Image($v); + if ($v->isAnchor()) { + $imgDecorator = new Toolkit_RotatingImages_Decorator_Anchor( + $imgDecorator, + $v + ); + } + $decorator->add($imgDecorator); + } + } + $this->rotatingImages = $decorator->toHtml($is); + } + + /** + * Add Weather module + * + * @return void + * @access private + */ + private function _weather() + { + $weather = new Toolkit_Weather(); + if (PEAR::isError($weather->currentCond)) { + return false; + } + + $this->weather = $weather->currentCond['weather']; + $this->tempF = $weather->currentCond['temp_f']; + $this->iconUrlName = $weather->currentCond['icon_url_name']; + $this->location = $weather->currentCond['location']; + $iconUrl + = ($_SERVER['HTTPS'] == 'on') + ? 'https://app.gaslightmedia.com/weather/' + : 'http://app.gaslightmedia.com/weather/'; + $this->fullIconUrl = $iconUrl . $this->iconUrlName; + } + +} diff --git a/Toolkit/Photos/Admin/FileUploader.php b/Toolkit/Photos/Admin/FileUploader.php new file mode 100644 index 0000000..947a3d2 --- /dev/null +++ b/Toolkit/Photos/Admin/FileUploader.php @@ -0,0 +1,423 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +define('YAHOO_YUI_BASE', GLM_APP_BASE_URL . 'yui/build/'); +define('PHOTOS_UPLOAD_PATH', BASE . 'admin/Photos/uploads/'); + +/** + * Toolkit_Photos_Admin_FileUploader + * + * Description of Toolkit_Photos_Admin_FileUploader + * + * @category Toolkit + * @package Photos/Admin + * @author Leif Hanson + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Photos_Admin_FileUploader extends Toolkit_FormBuilder +{ + // {{{ Class Properties + /** + * Description of $debug + * @var boolean + */ + public $debug = true; + + /** + * Message for successful upload + * @var string + */ + protected $successMsg = '
    You have successfully uploaded the files to your photo album.
    '; + // }}} + + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + $defaults = array('catid' => $_REQUEST['catid']); + $this->setupDefaults($defaults); + } + // }}} + // {{{ configureElements() + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + $categories = $this->getPhotoCategories(); + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'name' => 'albumHdr_rmv', + 'display' => '

    USE: Hold down the Ctrl key to select or unselect more than one photo at a time. Hold down the Shift key to select a range.

    + +
    This feature (Multiple Uploads) is only supported in certain modern browsers: +
      +
    • Internet Explorer 10
    • +
    • FireFox 8 and up
    • +
    • Safari 5 and up
    • +
    • Google Chrome 17 and up
    • +
    +
    ' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'catid' + ); + $e[] = array( + 'type' => 'file', + 'name' => 'files[]', + 'display' => 'Files to Upload', + 'opts' => array('id' => 'myuploader','multiple' => 'multiple') + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit_rmv', + 'display' => 'Submit Form' + ); + + $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' + ); + $this->setupFilters($f); + } + // }}} + // {{{ configureForm() + + /** + * Helper function, configures the entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + $this->setupRules($r); + } + + // }}} + + // {{{ getFileData() + /** + * Get file data + * + * @param string $fileName Filename + * @param string $path File path + * + * @return array|boolean + * @access public + */ + function getFileData($fileName, $path) + { + $filename = $path . '/' . $fileName; + if (is_file($filename) && is_readable($filename)) { + return array( + 'name' => $fileName, + 'tmp_name' => $filename, + 'size' => filesize($filename), + 'type' => mime_content_type($filename) + ); + } else { + return false; + } + } + // }}} + // {{{ getPhotoCategorieso() + + /** + * Get photo categories + * + * @return array + * @access public + */ + function getPhotoCategories() + { + try { + $sql = " + SELECT id, category + FROM photo_category + ORDER BY category"; + $stmt = $this->dbh->query($sql); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $categories[$row['id']] = $row['category']; + } + return $categories; + } catch(PDOExecption $e) { + Toolkit_Common::handleError($e); + } + }// }}} + // {{{ getCategoryMaxPos() + /** + * get max pos plus one + * + * @param mixed $id photo category id + * + * @access public + * @return string + */ + function getCategoryMaxPos($id) + { + try { + $sql = " + SELECT COALESCE(max(pos) + 1, 1) + FROM photo + WHERE catid = :catid"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":catid", $id, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + 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 public + */ + public function processData($values) + { + if ( is_array($values['files']) && !empty($values['files'])) { + $this->processFilesArray($values); + } else { + $this->processFolder($values); + } + return true; + } + + // }}} + + /** + * Process files array + * + * @param array $values Values array + * + * @return void + * @access public + */ + public function processFilesArray($values) + { + $images = array(); + $photos = array(); + $is = new Toolkit_FileServer_ImageAdapter(IS_OWNER_ID, IS_OWNER_PW); + $pos = $this->getCategoryMaxPos($values['catid']); + if (is_array($values['files']['name'])) { + for ($i = 0; $i < count($values['files']['name']); ++$i) { + if (!$values['files']['error'][$i]) { + $images[] = array( + 'name' => $values['files']['name'][$i], + 'tmp_name' => $values['files']['tmp_name'][$i], + 'size' => $values['files']['size'][$i] + ); + } + } + } + if (!empty($images)) { + foreach ($images as $img) { + $imgData = $is->uploadImageFile($img['tmp_name']); + $photos[] = Toolkit_Photos_Factory::createPhotoFromValues( + array( + 'image' => $imgData['name'], + 'catid' => $values['catid'], + 'pos' => $pos + ) + )->save($this->dbh); + ++$pos; + } + } + } + + /** + * Process folder + * + * @param array $values Values array + * + * @throws Exception + * @return void + * @access public + */ + public function processFolder($values) + { + $is = new Toolkit_Image_Server(); + try { + if (!is_dir($_SESSION['uploadFolder'])) { + throw new Exception('No Folder exists'); + } + } catch (Exception $e) { + Toolkit_Common::handleError($e); + } + + $d = dir($_SESSION['uploadFolder']); + $pos = $this->getCategoryMaxPos($_REQUEST['catid']); + $i = 0; + while (false !== ($entry = $d->read())) { + if (!in_array($entry, array('.','..','.svn','CVS'))) { + // before we can send the image to the image class we need + // to inject the data for the images into the $_FILES array + $_FILES['img' . $i] = $this->getFileData($entry, $_SESSION['uploadFolder']); + // send to image server and insert values + $image_name = $is->imageUpload('img' . $i, $_SESSION['uploadFolder']); + $insertValues = array( + 'image' => $image_name, + 'catid' => $_REQUEST['catid'], + 'pos' => $pos + ); + ++$pos; + try { + $sql = Toolkit_Common::createSQLInsert( + 'photo', + array_keys($insertValues) + ); + Toolkit_Common::processQuery($this->dbh, 'photo', $sql, $insertValues); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + unlink($_SESSION['uploadFolder'] . '/'. $entry); + ++$i; + } + } + $d->close(); + if (is_dir($_SESSION['uploadFolder'])) { + rmdir($_SESSION['uploadFolder']); + } + } + + // {{{ setupRenderers() + // @codeCoverageIgnoreStart + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = ' * '; + $error = '
    {error}
    '; + } + + // @codeCoverageIgnoreEnd + // }}} + + // {{{ 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() + { + $this->setupRenderers(); + if ($this->validate()) { + $this->cleanForm(); + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + HTTP_Session2::unregister('uploadFolder'); + header("Location: list_photo.phtml?catid=" . $_REQUEST['catid']); + exit; + } + + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHTML(); + $output = '
    '.print_r($this, true).'
    '; + } else { + // $oldumask = umask(0); + // if (!HTTP_Session2::get('uploadFolder')) { + // HTTP_Session2::set( + // 'uploadFolder', + // PHOTOS_UPLOAD_PATH . mktime() + // ); + // mkdir($_SESSION['uploadFolder'], 0777, true); + // } + // if (!is_dir($_SESSION['uploadFolder'])) { + // mkdir($_SESSION['uploadFolder'], 0777, true); + // } + $output = parent::toHTML(); + // umask($oldumask); + } + return $output; + } + + // }}} +} +?> \ No newline at end of file diff --git a/Toolkit/Photos/Database/application.sql b/Toolkit/Photos/Database/application.sql new file mode 100644 index 0000000..3ed1c11 --- /dev/null +++ b/Toolkit/Photos/Database/application.sql @@ -0,0 +1,9 @@ +CREATE SCHEMA photos; +GRANT ALL ON SCHEMA photos TO nobody; +-- +-- Tables +-- +\i ./tables/photo_category.sql +\i ./tables/photo.sql +\i ./tables/photo_category_bus.sql +\i ./tables/photo_default.sql diff --git a/Toolkit/Photos/Database/removeApplication.sql b/Toolkit/Photos/Database/removeApplication.sql new file mode 100644 index 0000000..7428041 --- /dev/null +++ b/Toolkit/Photos/Database/removeApplication.sql @@ -0,0 +1,8 @@ +-- +-- This will drop everything in the photos schema. +-- Nothing better be in here except photos related objects +-- or it will be dropped +-- +-- The force is strong w/ this one, use it wisely. +-- +DROP SCHEMA IF EXISTS photos CASCADE; diff --git a/Toolkit/Photos/Database/tables/photo.sql b/Toolkit/Photos/Database/tables/photo.sql new file mode 100755 index 0000000..ad1478b --- /dev/null +++ b/Toolkit/Photos/Database/tables/photo.sql @@ -0,0 +1,16 @@ +DROP TABLE IF EXISTS photos.photo CASCADE; + +CREATE TABLE photos.photo +(id SERIAL, + title TEXT, + description TEXT, + image TEXT, + catid INTEGER NOT NULL + REFERENCES photos.photo_category (id) + ON UPDATE CASCADE + ON DELETE CASCADE, + pos INTEGER, + PRIMARY KEY (id)); + +GRANT ALL on photos.photo_id_seq to nobody; +GRANT ALL on photos.photo to nobody; diff --git a/Toolkit/Photos/Database/tables/photo_category.sql b/Toolkit/Photos/Database/tables/photo_category.sql new file mode 100755 index 0000000..b1afa76 --- /dev/null +++ b/Toolkit/Photos/Database/tables/photo_category.sql @@ -0,0 +1,11 @@ +DROP TABLE IF EXISTS photos.photo_category CASCADE; + +CREATE TABLE photos.photo_category +(id SERIAL, + category TEXT, + image TEXT, + pos INTEGER, + PRIMARY KEY (id)); + +GRANT ALL ON photos.photo_category_id_seq TO nobody; +GRANT ALL ON photos.photo_category TO nobody; diff --git a/Toolkit/Photos/Database/tables/photo_category_bus.sql b/Toolkit/Photos/Database/tables/photo_category_bus.sql new file mode 100755 index 0000000..41592ec --- /dev/null +++ b/Toolkit/Photos/Database/tables/photo_category_bus.sql @@ -0,0 +1,20 @@ +DROP TABLE IF EXISTS photos.photo_category_bus CASCADE; + +CREATE TABLE photos.photo_category_bus +(id SERIAL, + photocat_id INTEGER + REFERENCES photos.photo_category (id) + ON UPDATE CASCADE + ON DELETE CASCADE, + buscat_id INTEGER + REFERENCES toolbox.pages (id) + ON UPDATE CASCADE + ON DELETE CASCADE, + pos INTEGER, + PRIMARY KEY (id) +); + +GRANT ALL ON photos.photo_category_bus_id_seq TO nobody; +GRANT ALL ON photos.photo_category_bus TO nobody; + +CREATE UNIQUE INDEX photo_category_bus_bus_phot_indx on photos.photo_category_bus (buscat_id ,photocat_id); diff --git a/Toolkit/Photos/Database/tables/photo_default.sql b/Toolkit/Photos/Database/tables/photo_default.sql new file mode 100755 index 0000000..8dc9467 --- /dev/null +++ b/Toolkit/Photos/Database/tables/photo_default.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS photos.photo_default CASCADE; + +CREATE TABLE photos.photo_default +(id SERIAL, + header TEXT, + description TEXT, + PRIMARY KEY (id)); + +GRANT ALL ON photos.photo_default_id_seq TO nobody; +GRANT ALL ON photos.photo_default TO nobody; diff --git a/Toolkit/Photos/Display.php b/Toolkit/Photos/Display.php new file mode 100755 index 0000000..9196b80 --- /dev/null +++ b/Toolkit/Photos/Display.php @@ -0,0 +1,271 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: Display.php,v 1.10 2010/07/04 23:55:12 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Photos_Display + * + * Display the Photo Gallery assoc to a toolbox page + * + * @category Toolkit + * @package Photos + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_Photos_Display +{ + // {{{ Properties + + /** + * PDO + * @var PDO + * @access private + */ + private $_dbh; + + /** + * Options for Flexy Templates + * @var array + * @access protected + */ + protected $flexyOptions = array( + 'templateDir' => '/templates', + 'compileDir' => '/templates/compiled', + 'forceCompile' => false, + 'allowPHP' => true, + ); + + /** + * page name for form action and links + * @var unknown + * @access protected + */ + protected $pageName; + + /** + * Photo Table Name + * @var string + * @access protected + */ + protected $photoTable = 'photo'; + + /** + * Photo Category Table Name + * @var string + * @access protected + */ + protected $categoryTable = 'photo_category'; + + /** + * rowCount + * + * @var float + * @access protected + */ + protected $rowCount = 4; + // }}} + // {{{ __construct() + + /** + * Class Contructor + * + * @param PDO $dbh Database Connection + * + * @return void + * @access public + */ + function __construct(PDO $dbh) + { + $this->_dbh = $dbh; + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = BASE . 'Toolkit/Photos/templates/'; + $this->flexyOptions['compileDir'] = BASE . 'Toolkit/Photos/templates/compiled/'; + // the main display page for events to link to + $this->pageName = BASE_URL.'index.php?catid='.$_REQUEST['catid']; + } + + // }}} + // {{{ listPhotoCategories() + + /** + * listPhotoCategories() + * + * Display Photo Categories + * + * @param int $pageId id of the toolbox page + * + * @return mixed Return description (if any) ... + * @access public + */ + function listPhotoCategories($pageId) + { + $sql = " + SELECT pc.* + FROM photo_category pc + JOIN photo_category_bus pcb + ON (pcb.photocat_id = pc.id) + WHERE pcb.buscat_id = :pageId + AND pc.id IN (SELECT distinct(catid) FROM photo) + ORDER BY pcb.pos"; + try { + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':pageId', $pageId, PDO::PARAM_INT); + $stmt->execute(); + $data = $stmt->fetchAll(PDO::FETCH_ASSOC); + if (is_array($data)) { + $i = 0; + foreach ($data as &$row) { + unset($row['image']); + // use the first one from its photos + $sql = " + SELECT image + FROM photo + WHERE catid = :catid + AND image != '' + ORDER BY pos + LIMIT 1 + OFFSET 0"; + try { + $stmt2 = $this->_dbh->prepare($sql); + $stmt2->bindParam(":catid", $row['id'], PDO::PARAM_INT); + $stmt2->execute(); + $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); + $data[$i]['image'] = $row2['image']; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + ++$i; + } + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass; + $page->appbase = GLM_APP_BASE_URL; + $page->page = BASE_URL.'index.php?catid='.$pageId.'&photo_catid='; + $page->cats = $data; + $page->imgPath = PHOTO_SMALL_URL; + $template->compile('photoCats.html'); + return $template->bufferedOutputObject($page); + } else { + return ''; + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ listPhotos() + + /** + * listPhotos() + * + * Display Photos + * + * @param int $photoCatId Photo Category ID + * + * @return mixed Return description (if any) ... + * @access public + */ + function listPhotos($photoCatId) + { + // where clauses + if ($photoCatId) { + // grab photo album name for display + try { + $sql = " + SELECT category + FROM photo_category + WHERE id = :id"; + $stmt1 = $this->_dbh->prepare($sql); + $stmt1->bindParam(":id", $photoCatId, PDO::PARAM_INT); + $stmt1->execute(); + $albumName = $stmt1->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + $where[] = "catid = $photoCatId"; + } + // query + $sql = " + SELECT * + FROM {$this->photoTable}"; + if (is_array($where)) { + $sql .= " WHERE ".implode(" AND ", $where); + } + $sql .= " ORDER BY pos"; + try { + $data = $this->_dbh->query($sql)->fetchAll(); + $count = 1; + $trueCount = 1; + $num = count($data); + foreach ($data as &$row) { + $row['firstInRow'] = ($count == 1); + if ($count == $this->rowCount || $trueCount == $num) { + $row['lastInRow'] = true; + $count = 0; + } else { + $row['lastInRow'] = false; + } + ++$count; + ++$trueCount; + } + if (is_array($data)) { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + $page->album = ($albumName) ? $albumName : 'Photo Gallery'; + $page->appbase = GLM_APP_BASE_URL; + $page->photos = $data; + $page->imgPath = PHOTO_SMALL_URL; + $page->orgPath = PHOTO_LARGE_URL; + $template->compile('photos.html'); + return $template->bufferedOutputObject($page); + } else { + return ''; + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ toHTML() + + /** + * toHTML() + * + * call to listPhotos function for display of Photos + * + * @param array $photoCatIds All catid's for this page + * + * @return mixed + * @access public + */ + public function toHTML(array $photoCatIds) + { + $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'; + + if (count($photoCatIds) > 1) { + return $this->listPhotoCategories($_GET['catid']); + } else { + return $this->listPhotos($photoCatIds[0]); + } + } + + // }}} +} diff --git a/Toolkit/Photos/Exception.php b/Toolkit/Photos/Exception.php new file mode 100644 index 0000000..2dd8695 --- /dev/null +++ b/Toolkit/Photos/Exception.php @@ -0,0 +1,30 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ +/** + * Toolkit_Photos_Exception + * + * @category Toolkit + * @package Photos + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version Release: 2.0 + * @link <> + */ +class Toolkit_Photos_Exception + extends Exception +{ + +} diff --git a/Toolkit/Photos/Factory.php b/Toolkit/Photos/Factory.php new file mode 100644 index 0000000..4bf4056 --- /dev/null +++ b/Toolkit/Photos/Factory.php @@ -0,0 +1,47 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ +/** + * Toolkit_Photos_Factory + * + * Factory to create Photo Object + * + * @category Toolkit + * @package Photos + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version Release: 2.0 + * @link <> + */ +class Toolkit_Photos_Factory +{ + /** + * createPhotoFromValues + * + * Create a Toolkit_Photos_Photo object from given array + * + * @param array $values An array of values used for creating object + * + * @return Toolkit_Photos_Photo $photo Object from given array + */ + static public function createPhotoFromValues($values) + { + $newPhoto = new Toolkit_Photos_Photo(); + $photo = $newPhoto->createByValues($values); + return $photo; + } +} +?> diff --git a/Toolkit/Photos/Gallery.php b/Toolkit/Photos/Gallery.php new file mode 100644 index 0000000..bddd6b1 --- /dev/null +++ b/Toolkit/Photos/Gallery.php @@ -0,0 +1,136 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Gallery.php,v 1.1 2010/06/09 19:52:24 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Fetches photo galleries assigned to pages + * + * @category Toolkit + * @package Photos + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Photos_Gallery +{ + // {{{ properties + + /** + * Database handler + * @var object + * @access private + */ + private $_dbh; + + /** + * Toolkit_Photos_Display object + * @var object + * @access private + */ + private $_photoApp; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $dbh Database handler + * @param Toolkit_Photos_Display $photoApp Photo Gallery Display object + * + * @return void + * @access public + */ + public function __construct(PDO $dbh, Toolkit_Photos_Display $photoApp) + { + $this->_dbh = $dbh; + $this->_photoApp = $photoApp; + } + + // }}} + // {{{ _getGalleriesAssignedToPage() + + /** + * Gets an array of photo galleries assigned to page + * + * If we were on a page that contained multiple galleries + * and we move into a single gallery page - this function + * returns that single gallery, so we can view all its photos + * + * @param integer $pageId Id of page we're on + * + * @return array multi-dimensional array of photo galleries assigned to page + * @access private + * @throws Toolkit_Photos_Exception If can't query for galleries on page + */ + private function _getGalleriesAssignedToPage($pageId) + { + if (isset($_GET['photo_catid']) && ctype_digit($_GET['photo_catid'])) { + return array( + array('photocat_id' => $_GET['photo_catid']) + ); + } + + try { + $sql = " + SELECT photocat_id + FROM photo_category_bus + WHERE buscat_id = :pageId"; + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':pageId', $pageId, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Photos_Exception( + "Unable to check if page has a gallery `$pageId`" + ); + } + } + + // }}} + // {{{ getPageGallery() + + /** + * Gets the page galleries / gallery + * + * @param integer $pageId Id of page we're on + * + * @return string photo gallery output + * @access public + */ + public function getPageGallery($pageId) + { + $galleries = $this->_getGalleriesAssignedToPage($pageId); + + $photoCatIds = array(); + foreach ($galleries as $gallery) { + $photoCatIds[] = $gallery['photocat_id']; + } + + return !empty($photoCatIds) + ? $this->_photoApp->toHTML($photoCatIds) + : ''; + } + + // }}} +} diff --git a/Toolkit/Photos/Photo.php b/Toolkit/Photos/Photo.php new file mode 100644 index 0000000..bed34f9 --- /dev/null +++ b/Toolkit/Photos/Photo.php @@ -0,0 +1,81 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $Id$ + * @link <> + */ + +/** + * Toolkit_Photos_Photo + * + * Photo Data Object Pattern + * + * @category Toolkit + * @package Photos + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version Release: 1.0 + * @link <> + */ +class Toolkit_Photos_Photo + extends Toolkit_Table +{ + /** + * Description of $tableName + * @var string + * @access public + */ + public $tableName = 'photo'; + + /** + * Description of $id + * @var int + * @access protected + */ + protected $id; + + /** + * Description of $title + * @var string + * @access protected + */ + protected $title; + + /** + * Description of $description + * @var string + * @access protected + */ + protected $description; + + /** + * Description of $image + * @var string + * @access protected + */ + protected $image; + + /** + * Description of $catid + * @var int + * @access protected + */ + protected $catid; + + /** + * Description of $pos + * @var int + * @access protected + */ + protected $pos; +} + diff --git a/Toolkit/Photos/assets/.keepme b/Toolkit/Photos/assets/.keepme new file mode 100644 index 0000000..e69de29 diff --git a/Toolkit/Photos/templates/photoCats.html b/Toolkit/Photos/templates/photoCats.html new file mode 100755 index 0000000..e877442 --- /dev/null +++ b/Toolkit/Photos/templates/photoCats.html @@ -0,0 +1,8 @@ + + diff --git a/Toolkit/Photos/templates/photos.html b/Toolkit/Photos/templates/photos.html new file mode 100755 index 0000000..3f5c910 --- /dev/null +++ b/Toolkit/Photos/templates/photos.html @@ -0,0 +1,11 @@ + diff --git a/Toolkit/Registry.php b/Toolkit/Registry.php new file mode 100644 index 0000000..3003cd1 --- /dev/null +++ b/Toolkit/Registry.php @@ -0,0 +1,82 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Registry.php,v 1.2 2010/05/25 14:07:22 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Variable Registry + * + * The registry is an object where site wide variables can be stored + * without the use of globals. By passing the registry object to + * the controllers that need them, we avoid pollution of the global + * namespace and render our variables safe. + * + * @category Toolkit + * @package Registry + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Registry +{ + // {{{ properties + + /** + * variables + * @access private + */ + private $_vars = array(); + + // }}} + + // {{{ __set() + + /** + * Sets undefined variables + * + * @param string $index key index in variables array + * @param mixed $value variable value + * + * @return void + * @access public + */ + public function __set($index, $value) + { + $this->_vars[$index] = $value; + } + + // }}} + // {{{ __get() + + /** + * Gets defined variables + * + * @param mixed $index variable to retrieve + * + * @return mixed + */ + public function __get($index) + { + return $this->_vars[$index]; + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/ActiveImagesDataGrid.php b/Toolkit/RotatingImages/ActiveImagesDataGrid.php new file mode 100644 index 0000000..5527b47 --- /dev/null +++ b/Toolkit/RotatingImages/ActiveImagesDataGrid.php @@ -0,0 +1,67 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_ActiveImagesDataGrid + * + * Description of newPHPClass + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_ActiveImagesDataGrid + extends Toolkit_RotatingImages_ImagesDataGridAbstract + implements Toolkit_RotatingImages_IImagesDataGrid +{ + // {{{ setControlObject() + + /** + * Description of setControlObject + * + * @return void + */ + protected function setControlObject() + { + $this->ctrlObj['tableId'] = 'active'; + $this->ctrlObj['gridName'] = 'Active Images'; + } + + // }}} + // {{{ setQuery() + + /** + * Sets query to all active rotating images + * + * @return void + */ + public function setQuery() + { + $sql = " + SELECT * + FROM rotating_images + WHERE active = true"; + + parent::setQuery($sql); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Database/application.sql b/Toolkit/RotatingImages/Database/application.sql new file mode 100644 index 0000000..eb0b201 --- /dev/null +++ b/Toolkit/RotatingImages/Database/application.sql @@ -0,0 +1,15 @@ +CREATE SCHEMA rotatingImages; +GRANT ALL ON SCHEMA rotatingImages TO nobody; +-- +-- Tables +-- +\i ./tables/rotating_images.sql +\i ./tables/rotating_images_transitions.sql + +-- +-- Procedures +-- + +-- +-- Modules +-- diff --git a/Toolkit/RotatingImages/Database/removeApplication.sql b/Toolkit/RotatingImages/Database/removeApplication.sql new file mode 100644 index 0000000..ed04c5c --- /dev/null +++ b/Toolkit/RotatingImages/Database/removeApplication.sql @@ -0,0 +1,8 @@ +-- +-- This will drop everything in the rotatingImages schema. +-- Nothing better be in here except rotatingImages related objects +-- or it will be dropped +-- +-- the forece is strong w/ this one, use it wisely. +-- +DROP SCHEMA IF EXISTS rotatingImages CASCADE; diff --git a/Toolkit/RotatingImages/Database/tables/rotating_images.sql b/Toolkit/RotatingImages/Database/tables/rotating_images.sql new file mode 100644 index 0000000..9c665b5 --- /dev/null +++ b/Toolkit/RotatingImages/Database/tables/rotating_images.sql @@ -0,0 +1,18 @@ +DROP TABLE IF EXISTS rotatingImages.rotating_images CASCADE; + +CREATE TABLE rotatingImages.rotating_images +(id SERIAL, + image TEXT NOT NULL UNIQUE, + url TEXT, + external BOOLEAN NOT NULL DEFAULT FALSE, + active BOOLEAN NOT NULL DEFAULT FALSE, + pos INTEGER, + thumb_width INTEGER NOT NULL, + thumb_height INTEGER NOT NULL, + width INTEGER NOT NULL, + height INTEGER NOT NULL, + UNIQUE (active, pos), + PRIMARY KEY (id)); + +GRANT ALL ON rotatingImages.rotating_images_id_seq TO nobody; +GRANT ALL ON rotatingImages.rotating_images TO nobody; diff --git a/Toolkit/RotatingImages/Database/tables/rotating_images_transitions.sql b/Toolkit/RotatingImages/Database/tables/rotating_images_transitions.sql new file mode 100644 index 0000000..60b14f3 --- /dev/null +++ b/Toolkit/RotatingImages/Database/tables/rotating_images_transitions.sql @@ -0,0 +1,9 @@ +DROP TABLE IF EXISTS rotatingImages.rotating_images_transitions CASCADE; + +CREATE TABLE rotatingImages.rotating_images_transitions +(timeout INTEGER NOT NULL DEFAULT 10, + transition TEXT NOT NULL DEFAULT 'fade'); + +INSERT INTO rotatingImages.rotating_images_transitions VALUES (10, 'fade'); + +GRANT ALL ON rotatingImages.rotating_images_transitions TO nobody; diff --git a/Toolkit/RotatingImages/Decorator/Admin.php b/Toolkit/RotatingImages/Decorator/Admin.php new file mode 100644 index 0000000..b25c11f --- /dev/null +++ b/Toolkit/RotatingImages/Decorator/Admin.php @@ -0,0 +1,136 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Admin.php,v 1.1 2010/07/25 17:05:58 jamie Exp $ + * @link <> + */ + + +/** + * Collection of banner decorators to rotate + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @link <> + */ +class Toolkit_RotatingImages_Decorator_Admin + implements IteratorAggregate, Toolkit_RotatingImages_Decorator_IDecoratorsIterator +{ + // {{{ properties + + /** + * Banner decorators + * @var array + * @access private + */ + private $_decorators; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * @return void + * @access protected + */ + public function __construct() + { + $this->_decorators = array(); + } + + // }}} + // {{{ getIterator() + + /** + * Set the external iterator + * + * @return object An instance of an object implementing Iterator or Traversable + * @access public + */ + public function getIterator() + { + return new ArrayIterator($this->_decorators); + } + + // }}} + // {{{ getTotal() + + /** + * Gets the total number of decorators we have added + * + * @return array number of decorators in collection + * @access public + */ + public function getTotal() + { + return count($this->_decorators); + } + + // }}} + // {{{ add() + + /** + * Adds a decorator to the collection + * + * @param Toolkit_RotatingImages_Decorator_DecoratorAbstract $d Decorator object + * + * @return void + * @access public + */ + public function add(Toolkit_RotatingImages_Decorator_DecoratorAbstract $d) + { + $this->_decorators[] = $d; + } + + // }}} + // {{{ toHtml() + + /** + * Converts all decorator objects collection into an HTML string + * + * Adds the appropriate scripts to the page so we can use JS to + * rotate through the banners + * + * @return string HTML version of the static banners available + * @access public + */ + public function toHtml() + { + $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/plugins/nivoslider/2.0/'.LIBJS_ENV.'/jquery.nivo.slider.js'; + $GLOBALS['styleSheets'][] = GLM_APP_BASE_URL . 'libjs/plugins/nivoslider/2.0/'.LIBJS_ENV.'/nivo-slider.css'; + $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/RotatingImages/styles.css'; + + foreach ($this->_decorators as $i) { + switch (get_class($i)) { + case 'Toolkit_RotatingImages_Decorator_Thumbnail' : + case 'Toolkit_RotatingImages_Decorator_Image' : + $images .= $i->toHtml(); + break; + + case 'Toolkit_RotatingImages_Decorator_Anchor' : + $images .= $i->toHtml(); + break; + + default : + break; + } + } + + return "
    $images
    "; + } + + // }}} +} diff --git a/Toolkit/RotatingImages/Decorator/Anchor.php b/Toolkit/RotatingImages/Decorator/Anchor.php new file mode 100644 index 0000000..b424787 --- /dev/null +++ b/Toolkit/RotatingImages/Decorator/Anchor.php @@ -0,0 +1,86 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Anchor.php,v 1.3 2010/08/15 16:02:21 jamie Exp $ + * @link <> + */ + + +/** + * Decorator for links + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @link <> + */ +class Toolkit_RotatingImages_Decorator_Anchor + extends Toolkit_RotatingImages_Decorator_DecoratorAbstract +{ + // {{{ properties + + /** + * The image decorator object + * @var Toolkit_RotatingImages_Decorator_Image + * @access private + */ + private $_imageDecorator; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * create a shallow copy of the image passed in so we can manipulate + * it all we want and not worry about affecting the original object + * + * @param Toolkit_RotatingImages_Decorator_Image $imageDecorator Object to decorate image markup + * @param Toolkit_RotatingImages_Image $image Node to be decorated + * + * @return void + * @access protected + */ + public function __construct( + Toolkit_RotatingImages_Decorator_Image $imageDecorator, + Toolkit_RotatingImages_Image $image + ) { + $this->_imageDecorator = $imageDecorator; + // Clone the node object so we keep original properties the same + $this->image = clone $image; + } + + // }}} + // {{{ toHtml() + + /** + * Convert the anchor to a HTML string + * + * @return string HTML output of the anchor + * @access public + */ + public function toHtml() + { + $anchorFormat = '%s'; + return sprintf( + $anchorFormat, + $this->image->getUrl(), + $this->image->getExternal() ? 'class="external"' : '', + $this->_imageDecorator->toHtml() + ); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Decorator/DecoratorAbstract.php b/Toolkit/RotatingImages/Decorator/DecoratorAbstract.php new file mode 100644 index 0000000..12cdd5d --- /dev/null +++ b/Toolkit/RotatingImages/Decorator/DecoratorAbstract.php @@ -0,0 +1,55 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DecoratorAbstract.php,v 1.1 2010/07/25 17:05:58 jamie Exp $ + * @link <> + */ + + +/** + * Base class for decorators + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @link <> + */ +abstract class Toolkit_RotatingImages_Decorator_DecoratorAbstract +{ + // {{{ properties + + /** + * Image object that will be decorated + * @var Toolkit_RotatingImages_Image + * @access protected + */ + protected $image; + + // }}} + // {{{ getImage() + + /** + * Get the image we are decorating + * + * @return Toolkit_RotatingImages_Image object + * @access public + */ + public function getImage() + { + return $this->image; + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Decorator/IDecoratorsIterator.php b/Toolkit/RotatingImages/Decorator/IDecoratorsIterator.php new file mode 100644 index 0000000..55a2137 --- /dev/null +++ b/Toolkit/RotatingImages/Decorator/IDecoratorsIterator.php @@ -0,0 +1,48 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: IDecoratorsIterator.php,v 1.1 2010/07/25 17:05:58 jamie Exp $ + * @link <> + */ + +/** + * Decorators collection + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @link <> + */ +interface Toolkit_RotatingImages_Decorator_IDecoratorsIterator +{ + + /** + * Add a new decorator to the collection + * + * @param Toolkit_RotatingImages_Decorator_DecoratorAbstract $d decorator + * + * @return void + * @access public + */ + public function add(Toolkit_RotatingImages_Decorator_DecoratorAbstract $d); + + /** + * Return an HTML version of the decorator + * + * @return html version of banners + * @access public + */ + public function toHtml(); +} +?> diff --git a/Toolkit/RotatingImages/Decorator/Image.php b/Toolkit/RotatingImages/Decorator/Image.php new file mode 100644 index 0000000..6969a75 --- /dev/null +++ b/Toolkit/RotatingImages/Decorator/Image.php @@ -0,0 +1,72 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Image.php,v 1.2 2010/08/15 15:57:30 jamie Exp $ + * @link <> + */ + + +/** + * Decorator for images + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @link <> + */ +class Toolkit_RotatingImages_Decorator_Image + extends Toolkit_RotatingImages_Decorator_DecoratorAbstract +{ + // {{{ __construct() + + /** + * constructor + * + * create a shallow copy of the node passed in so we can manipulate + * it all we want and not worry about affecting the original object + * + * @param Toolkit_RotatingImages_Image $image node to be decorated + * + * @return void + * @access protected + */ + public function __construct(Toolkit_RotatingImages_Image $image) + { + // Clone the node object so we keep original properties the same + $this->image = clone $image; + } + + // }}} + // {{{ toHtml() + + /** + * Convert the image to a HTML string + * + * @return string HTML output of the image + * @access public + */ + public function toHtml() + { + $format = 'Rotating Image'; + return sprintf( + $format, + $this->image->getWidth(), + $this->image->getHeight(), + ROTATING_IMAGE_RESIZED . $this->image->getImage() + ); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Decorator/Thumbnail.php b/Toolkit/RotatingImages/Decorator/Thumbnail.php new file mode 100644 index 0000000..ba8c157 --- /dev/null +++ b/Toolkit/RotatingImages/Decorator/Thumbnail.php @@ -0,0 +1,72 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Thumbnail.php,v 1.1 2010/07/25 17:05:58 jamie Exp $ + * @link <> + */ + + +/** + * Decorator for thumbnail images + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @link <> + */ +class Toolkit_RotatingImages_Decorator_Thumbnail + extends Toolkit_RotatingImages_Decorator_DecoratorAbstract +{ + // {{{ __construct() + + /** + * constructor + * + * create a shallow copy of the node passed in so we can manipulate + * it all we want and not worry about affecting the original object + * + * @param Toolkit_RotatingImages_Image $image image to be decorated + * + * @return void + * @access protected + */ + public function __construct(Toolkit_RotatingImages_Image $image) + { + // Clone the image object so we keep original properties the same + $this->image = clone $image; + } + + // }}} + // {{{ toHtml() + + /** + * Convert the image to a HTML string + * + * @return string HTML output of the image + * @access public + */ + public function toHtml() + { + $format = ''; + return sprintf( + $format, + $this->image->getThumbWidth(), + $this->image->getThumbHeight(), + ROTATING_IMAGE_THUMB . $this->image->getImage() + ); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Decorator/User.php b/Toolkit/RotatingImages/Decorator/User.php new file mode 100644 index 0000000..5fa7a98 --- /dev/null +++ b/Toolkit/RotatingImages/Decorator/User.php @@ -0,0 +1,139 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: User.php,v 1.2 2010/08/15 15:59:26 jamie Exp $ + * @link <> + */ + + +/** + * Collection of banner decorators to rotate + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @link <> + */ +class Toolkit_RotatingImages_Decorator_User + implements IteratorAggregate, Toolkit_RotatingImages_Decorator_IDecoratorsIterator +{ + // {{{ properties + + /** + * Banner decorators + * @var array + * @access private + */ + private $_decorators; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * @return void + * @access protected + */ + public function __construct() + { + $this->_decorators = array(); + } + + // }}} + // {{{ getIterator() + + /** + * Set the external iterator + * + * @return object An instance of an object implementing Iterator or Traversable + * @access public + */ + public function getIterator() + { + return new ArrayIterator($this->_decorators); + } + + // }}} + // {{{ getTotal() + + /** + * Gets the total number of decorators we have added + * + * @return array number of decorators in collection + * @access public + */ + public function getTotal() + { + return count($this->_decorators); + } + + // }}} + // {{{ add() + + /** + * Adds a decorator to the collection + * + * @param Toolkit_RotatingImages_Decorator_DecoratorAbstract $d Decorator object + * + * @return void + * @access public + */ + public function add(Toolkit_RotatingImages_Decorator_DecoratorAbstract $d) + { + $this->_decorators[] = $d; + } + + // }}} + // {{{ toHtml() + + /** + * Converts all decorator objects collection into an HTML string + * + * Adds the appropriate scripts to the page so we can use JS to + * rotate through the banners + * + * @return string HTML version of the static banners available + * @access public + */ + public function toHtml() + { + $glmAppBaseUrl + = ($_SERVER['HTTPS'] == 'on') + ? GLM_APP_BASE_SECURE_URL + : GLM_APP_BASE_URL; + $baseUrl + = ($_SERVER['HTTPS'] == 'on') + ? BASE_SECURE_URL + : BASE_URL; + + $GLOBALS['styleSheets'][] + = $glmAppBaseUrl . 'libjs/plugins/nivoslider/2.0/prod/nivo-slider.css'; + $GLOBALS['bottomScripts'][] + = $glmAppBaseUrl . 'libjs/plugins/nivoslider/2.0/prod/jquery.nivo.slider.js'; + $GLOBALS['bottomScripts'][] + = $baseUrl . 'Toolkit/RotatingImages/libjs/user.php'; + + $images = ''; + foreach ($this->_decorators as $i) { + $images .= $i->toHtml(); + } + + return !empty($images) + ? "
    $images
    " + : ''; + } + + // }}} +} diff --git a/Toolkit/RotatingImages/EditImageController.php b/Toolkit/RotatingImages/EditImageController.php new file mode 100644 index 0000000..85ec8f0 --- /dev/null +++ b/Toolkit/RotatingImages/EditImageController.php @@ -0,0 +1,94 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_EditImageController + * + * Description of Toolkit_RotatingImages_EditImageController + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_EditImageController + extends Toolkit_BaseControllerAbstract implements Toolkit_IController +{ + // {{{ indexAction() + + /** + * indexAction + * + * @return string + */ + public function indexAction() + { + $imageAdapter = new Toolkit_FileServer_ImageAdapter(); + $form = new Toolkit_RotatingImages_Forms_EditImage( + 'GLM_RotatingImages' + ); + $form->configureForm($this->registry->dbh, $imageAdapter); + $html = $form->toHtml($this->registry->dbh); + + if ($form->isSubmitted() && $form->validate()) { + if ($form->getSubmitValue('delete')) { + $this->deleteAction(); + } + $ia = new Toolkit_FileServer_ImageAdapter(); + $values = $form->getSubmitValues(); + list($values['thumb_width'], $values['thumb_height'], ) + = $ia->getImageSize(ROTATING_IMAGE_THUMB . $values['image']); + list($values['width'], $values['height'], ) + = $ia->getImageSize(ROTATING_IMAGE_RESIZED . $values['image']); + $gateway = new Toolkit_RotatingImages_Gateway($this->registry->dbh); + if ($imageId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $image = new Toolkit_RotatingImages_Image($values, $imageId); + $gateway->update($image); + } else { + $image = new Toolkit_RotatingImages_Image($values); + $gateway->insert($image); + } + header('Location: ' . BASE_URL . 'admin/rotatingImages.php'); + exit(); + } + + return $html; + } + + // }}} + // {{{ deleteAction() + + /** + * deleteAction + * + * @return void + */ + public function deleteAction() + { + if ($imageId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $gateway = new Toolkit_RotatingImages_Gateway($this->registry->dbh); + $image = $gateway->find($imageId); + $gateway->delete($image, new Toolkit_FileServer_ImageAdapter()); + } + header('Location: ' . BASE_URL . 'admin/rotatingImages.php'); + exit(); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Forms/EditImage.php b/Toolkit/RotatingImages/Forms/EditImage.php new file mode 100644 index 0000000..189c3b2 --- /dev/null +++ b/Toolkit/RotatingImages/Forms/EditImage.php @@ -0,0 +1,381 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditImage.php,v 1.2 2010/08/15 18:40:57 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +require_once BASE . 'Toolkit/Forms/Rules/Image.php'; +require_once BASE . 'Toolkit/Forms/Rules/Url.php'; + +/** + * Rotating Images Application + * + * Manages the creation and editing form for manipulating images in the db. + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_RotatingImages_Forms_EditImage extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * What do you want the success msg to be if the form validates successfully + * + * @var string + * @access protected + */ + protected $successMsg + = '
    Image successfully updated.
    '; + + /** + * 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( + array( + 'checkURI', + 'callback', + 'uri', + 'Validate' + ) + ); + + // }}} + + // {{{ configureConstants() + + /** + * Configure form constants + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array(); + + // If we are adding a new banner + if (!filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $c['current_image_thumb'] = 'Image not yet uploaded'; + } + + // If the form has been submitted and a new image was uploaded + $currImg = $this->getSubmitValue('image'); + if ($this->isSubmitted() && !empty($currImg)) { + $img = ''; + $c['current_image_thumb'] = sprintf( + $img, + ROTATING_IMAGE_THUMB, + $currImg + ); + } + + $this->setupConstants($c); + } + + // }}} + // {{{ configureDefaults() + + /** + * Configure the initial default values for the form + * + * @param PDO $dbh Database handler + * + * @return void + * @access public + */ + public function configureDefaults(PDO $dbh) + { + if ($imageId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $gateway = new Toolkit_RotatingImages_Gateway($dbh); + if ($node = $gateway->find($imageId)) { + $img = 'Rotating Image'; + $d = array( + 'active' => (int) $node->getActive(), + 'image'=> $node->getImage(), + 'current_image_thumb' => sprintf( + $img, + ROTATING_IMAGE_THUMB, + $node->getImage(), + $node->getThumbWidth(), + $node->getThumbHeight() + ), + 'external' => (int) $node->getExternal(), + 'url' => $node->getUrl(), + ); + } + } else { + $d = array( + 'external' => false, + ); + } + + $this->setupDefaults($d); + } + + // }}} + // {{{ configureElements() + + /** + * Configure how the form elements should look + * + * @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' => 'advcheckbox', + 'req' => false, + 'name' => 'active', + 'display' => 'Active', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'image' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'url', + 'display' => 'URL', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'external', + 'display' => 'External Link', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'file', + 'display' => 'Image' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'current_image_thumb', + 'display' => 'Current Image' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => 'Submit Image', + ); + if (filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'delete', + 'display' => 'Delete Image', + ); + } + + $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 PDO + * @param Toolkit_FileServer_ImageAdapter $ia File server image adapter + * + * @return void + * @access public + */ + public function configureForm(PDO $dbh, Toolkit_FileServer_ImageAdapter $ia) + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules($ia); + $this->configureDefaults($dbh); + $this->configureConstants(); + } + + // }}} + // {{{ configureRules() + + /** + * Configure how the form elements should act + * + * @param Toolkit_FileServer_ImageAdapter $ia File server image adapter + * + * @return void + * @access public + */ + public function configureRules(Toolkit_FileServer_ImageAdapter $ia) + { + $r = array(); + + $r[] = array( + 'element' => 'url', + 'message' => 'ERROR: Invalid URL', + 'type' => 'Url', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $uploadedImage = $this->getSubmitValue('image'); + if (empty($uploadedImage)) { + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Must upload an image!', + 'type' => 'uploadedfile', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + } + if (is_uploaded_file($_FILES['file']['tmp_name'])) { + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $ia->getAllowedMimeTypes(), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + } + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Error uploading image!', + 'type' => 'Image', + 'format' => array( + 'form' => $this, + 'fieldName' => 'file', + 'imageField' => 'image', + 'is' => $ia, + 'deleteExistingImage' => true, + 'injectImage' => array('tgtElement' => 'current_image_thumb'), + ), + 'validation' => 'server', + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = ' * '; + $error = '
    {error}
    '; + $renderer->setElementTemplate( + ' + '.$required.'{label}'.$error.'{element} + ', + 'submit' + ); + $renderer->setElementTemplate( + ' + '.$required.'{label}'.$error.'{element} + ', + 'delete' + ); + + } + + // }}} + + // {{{ toHtml() + + /** + * Call the rendering function to get the form in a string + * + * @param PDO $dbh Database handler + * + * @return string $output The Form to be rendered or success msg. + * @access protected + */ + public function toHtml(PDO $dbh) + { + $this->setupRenderers(); + if ($this->isSubmitted()) { + if ($this->validate()) { + $output = $this->successMsg; + } else { + $output = $this->errorMsg; + $output .= parent::toHTML(); + } + } else { + $output = parent::toHTML(); + } + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Forms/TransitionSettings.php b/Toolkit/RotatingImages/Forms/TransitionSettings.php new file mode 100644 index 0000000..08853ad --- /dev/null +++ b/Toolkit/RotatingImages/Forms/TransitionSettings.php @@ -0,0 +1,296 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: TransitionSettings.php,v 1.2 2010/08/15 18:41:14 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Rotating Images Application + * + * Manages the creation and editing form for manipulating banners in the db. + * + * @category RotatingImages + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_RotatingImages_Forms_TransitionSettings + extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * What do you want the success msg to be if the form validates successfully + * + * @var string + * @access protected + */ + protected $successMsg + = '
    Settings successfully updated.
    '; + + /** + * 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(); + + // }}} + + // {{{ configureConstants() + + /** + * Configure the constant values for the form + * + * @return void + * @access protected + */ + public function configureConstants() + { + $c = array( + 'ac' => 'preview' + ); + $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) + { + $sql = " + SELECT * + FROM rotating_images_transitions"; + + $d = $dbh->query($sql, PDO::FETCH_ASSOC)->fetch(); + + $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(); + + $rotationTime =& $c->getItem('section', 'rotation time') + ->getItem('directive', 'timeout') + ->getContent(); + $timeout = array_combine( + array_values($rotationTime), + array_values($rotationTime) + ); + $timeout = array_change_key_case($timeout); + + $animationType =& $c->getItem('section', 'animation type') + ->getItem('directive', 'transition') + ->getContent(); + $transition = array_combine( + array_values($animationType), + array_values($animationType) + ); + + // All Grouped Elements are created here. + $submitButtons = array(); + $submitButtons[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'apply', + 'display' => 'Apply Transition', + ); + $submitButtons[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'preview', + 'display' => 'Preview Transition', + ); + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'ac', + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'timeout', + 'display' => 'Seconds between transition', + 'opts' => array('' => '-- Select --') + $timeout, + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'transition', + 'display' => 'Transition effect', + 'opts' => array('' => '-- Select --') + $transition, + 'att' => array('id' => 'transition') + ); + $e[] = array( + 'type' => 'group', + 'group' => $submitButtons, + 'req' => false, + 'name' => 'submitButtons', + 'appendName' => false, + 'seperator' => ' - ' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * Configure a form so we can use it + * + * @param PDO $pdo Database handler + * @param Config_Container $c Application configuration settings + * + * @return void + * @access public + */ + public function configureForm(PDO $pdo, Config_Container $c) + { + $this->configureConstants(); + $this->configureDefaults($pdo); + $this->configureElements($pdo, $c); + } + + // }}} + + // {{{ processData() + + /** + * Update transition values + * + * @param PDO $dbh Database handler + * + * @return boolean Result of update + * @access protected + */ + private function _processData(PDO $dbh) + { + try { + $sql = " + UPDATE rotating_images_transitions + SET timeout = :timeout, + transition = :transition"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam( + ':timeout', + $this->_submitValues['timeout'], + PDO::PARAM_INT + ); + $stmt->bindParam( + ':transition', + $this->_submitValues['transition'], + PDO::PARAM_INT + ); + + return $stmt->execute(); + } 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(); + $renderer->setFormTemplate( + '
    + +
    + {hidden} +
    + {requiredNote} + {content}
    + +
    ' + ); + $renderer->setElementTemplate( + ' + '.$required.'{label}'.$error.'{element} + ', + 'submitButtons' + ); + } + + // @codeCoverageIgnoreEnd + // }}} + + // {{{ toHtml() + + /** + * Call the rendering function to get the form in a string + * + * @param PDO $pdo PDO + * + * @return string $output The Form to be rendered or success msg. + * @access protected + */ + public function toHtml(PDO $pdo) + { + $GLOBALS['styleSheets'][] = BASE_URL . 'css/contactform.css'; + + $this->setupRenderers(); + $output = ''; + if ($this->validate()) { + if ($this->_processData($pdo)) { + $output = $this->successMsg; + } + } + $output .= parent::toHTML(); + + return $output; + } + + // }}} +} diff --git a/Toolkit/RotatingImages/Gateway.php b/Toolkit/RotatingImages/Gateway.php new file mode 100644 index 0000000..1344043 --- /dev/null +++ b/Toolkit/RotatingImages/Gateway.php @@ -0,0 +1,300 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_Gateway + * + * Description of Toolkit_RotatingImages_Gateway + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_Gateway +{ + // {{{ properties + /** + * PDO + * + * @var PDO + * @access protected + */ + protected $dbh; + + // }}} + // {{{ __construct() + /** + * Class construct + * + * @param PDO $dbh PDO + * + * @return void + */ + public function __construct(PDO $dbh) + { + $this->dbh = $dbh; + } + + // }}} + + // {{{ delete() + /** + * Deleting the image + * + * @param Toolkit_RotatingImages_Image $image Image + * @param Toolkit_FileServer_ImageAdapter $ia ImageAdapter + * + * @return \Toolkit_RotatingImages_Image|boolean + * @throws InvalidArgumentException + */ + public function delete( + Toolkit_RotatingImages_Image $image, + Toolkit_FileServer_ImageAdapter $ia + ) { + $id = $image->getId(); + if (!filter_var($id, FILTER_VALIDATE_INT)) { + throw new InvalidArgumentException("Invalid image id `$id`"); + } + + try { + $ia->delete($image->getImage()); + $sql = " + DELETE FROM rotating_images + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + return $image; + } catch (RangeException $e) { + Toolkit_Logger::logException('File Server Error', $e); + } catch (Toolkit_FileServer_Exception $e) { + Toolkit_Logger::logException('File Server Error', $e); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + } + + return false; + } + + // }}} + // {{{ find() + /** + * Finding the image by id + * + * @param int $id Description for id + * + * @return \Toolkit_RotatingImages_Image|boolean + * @throws InvalidArgumentException + */ + public function find($id) + { + if (!filter_var($id, FILTER_VALIDATE_INT)) { + throw new InvalidArgumentException("Invalid image id `$id`"); + } + + $sql = " + SELECT * + FROM rotating_images + WHERE id = :id"; + + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + return new Toolkit_RotatingImages_Image($row, $row['id']); + } else { + return false; + } + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + } + + return false; + } + + // }}} + // {{{ insert() + /** + * Inserting the image + * + * @param Toolkit_RotatingImages_Image $image Description for $image + * + * @return boolean + */ + public function insert(Toolkit_RotatingImages_Image $image) + { + try { + $this->dbh->beginTransaction(); + $maxPosSql = " + SELECT COALESCE(MAX(pos) + 1, 1) AS pos + FROM rotating_images + WHERE active = cast(1 AS BOOLEAN)"; + $row = $this->dbh->query($maxPosSql)->fetch(PDO::FETCH_ASSOC); + + $insertSql = " + INSERT INTO rotating_images(image, active, url, external, pos, thumb_width, thumb_height, width, height) + VALUES (:image, :active, :url, :external, :pos, :thumb_width, :thumb_height, :width, :height)"; + $stmt = $this->dbh->prepare($insertSql); + $stmt->bindParam(':image', $image->getImage(), PDO::PARAM_STR); + $stmt->bindParam(':active', $image->getActive(), PDO::PARAM_BOOL); + $stmt->bindParam(':external', $image->getExternal(), PDO::PARAM_BOOL); + $stmt->bindParam( + ':thumb_width', + $image->getThumbWidth(), + PDO::PARAM_INT + ); + $stmt->bindParam( + ':thumb_height', + $image->getThumbHeight(), + PDO::PARAM_INT + ); + $stmt->bindParam( + ':width', + $image->getWidth(), + PDO::PARAM_INT + ); + $stmt->bindParam( + ':height', + $image->getHeight(), + PDO::PARAM_INT + ); + if ($image->getActive()) { + $stmt->bindParam(':pos', $row['pos'], PDO::PARAM_INT); + } else { + $stmt->bindValue(':pos', null, PDO::PARAM_NULL); + } + if ($image->getUrl()) { + $stmt->bindParam(':url', $image->getUrl(), PDO::PARAM_STR); + } else { + $stmt->bindValue(':url', null, PDO::PARAM_NULL); + } + $stmt->execute(); + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + } + + return false; + } + + // }}} + // {{{ update() + /** + * Updating the image + * + * @param Toolkit_RotatingImages_Image $image Image + * + * @return boolean + * @throws RuntimeException + */ + public function update(Toolkit_RotatingImages_Image $image) + { + if (!filter_var($image->getId(), FILTER_VALIDATE_INT)) { + throw new RuntimeException( + 'Image has not been inserted into the database yet' + ); + } + + try { + $updateSql = " + UPDATE rotating_images + SET image = :image, + active = :active, + external = :external, + thumb_width = :thumb_width, + thumb_height = :thumb_height, + width = :width, + height = :height, + url = :url + WHERE id = :id"; + $stmt = $this->dbh->prepare($updateSql); + $stmt->bindParam(':image', $image->getImage(), PDO::PARAM_STR); + $stmt->bindParam(':active', $image->getActive(), PDO::PARAM_BOOL); + $stmt->bindParam(':external', $image->getExternal(), PDO::PARAM_BOOL); + $stmt->bindParam(':id', $image->getId(), PDO::PARAM_INT); + $stmt->bindParam( + ':thumb_width', + $image->getThumbWidth(), + PDO::PARAM_INT + ); + $stmt->bindParam( + ':thumb_height', + $image->getThumbHeight(), + PDO::PARAM_INT + ); + $stmt->bindParam( + ':width', + $image->getWidth(), + PDO::PARAM_INT + ); + $stmt->bindParam( + ':height', + $image->getHeight(), + PDO::PARAM_INT + ); + + if ($image->getUrl()) { + $stmt->bindParam(':url', $image->getUrl(), PDO::PARAM_STR); + } else { + $stmt->bindValue(':url', null, PDO::PARAM_NULL); + } + + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + } + + return false; + } + + // }}} + // {{{ find() + /** + * Find all images + * + * @return \Toolkit_RotatingImages_Image + */ + public function findAll() + { + $sql = " + SELECT * + FROM rotating_images + ORDER BY active DESC, pos, id"; + + try { + $images = array(); + foreach ($this->dbh->query($sql) as $row) { + $images[] = new Toolkit_RotatingImages_Image($row, $row['id']); + } + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + } + + return $images; + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/IImagesDataGrid.php b/Toolkit/RotatingImages/IImagesDataGrid.php new file mode 100644 index 0000000..a229c7c --- /dev/null +++ b/Toolkit/RotatingImages/IImagesDataGrid.php @@ -0,0 +1,39 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_IImagesDataGrid + * + * Images Datagrid Interface + * + * @category Toolkit + * @package RotatingImages + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +interface Toolkit_RotatingImages_IImagesDataGrid +{ + /** + * Set the query the datagrid will use. + * + * @return string HTML output + * @access public + */ + public function setQuery(); +} +?> diff --git a/Toolkit/RotatingImages/Image.php b/Toolkit/RotatingImages/Image.php new file mode 100644 index 0000000..c3b35af --- /dev/null +++ b/Toolkit/RotatingImages/Image.php @@ -0,0 +1,396 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_Image + * + * Class representation of the image database + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_Image +{ + // {{{ properties + + /** + * Database id of node tuple + * @var integer + * @access protected + */ + protected $id; + + /** + * If the node is active or not + * @var boolean + * @access protected + */ + protected $active; + + /** + * Image + * @var string + * @access protected + */ + protected $image; + + /** + * url + * @var string + * @access protected + */ + protected $url; + + /** + * external + * @var string + * @access protected + */ + protected $external; + + /** + * width of thumbnail + * @var integer + * @access protected + */ + protected $thumbWidth; + + /** + * height of thumb + * @var integer + * @access protected + */ + protected $thumbHeight; + + /** + * width of image + * @var integer + * @access protected + */ + protected $width; + + /** + * height of image + * @var integer + * @access protected + */ + protected $height; + + // }}} + // {{{ __construct() + /** + * Class constructor + * + * @param array $attributes Description of attributes + * @param integer $id Database ID of node tuple + * + * @throws InvalidArgumentException + * @return void + */ + public function __construct(array $attributes, $id = null) + { + if (!array_key_exists('active', $attributes)) { + throw new InvalidArgumentException( + 'Missing `active` key for attributes' + ); + } elseif (!array_key_exists('image', $attributes)) { + throw new InvalidArgumentException( + 'Missing `image` key for attributes' + ); + } + + if (filter_var($attributes['url'], FILTER_VALIDATE_URL)) { + $this->url = $attributes['url']; + } + + $this->active = (bool) $attributes['active']; + $this->external = (bool) $attributes['external']; + $this->image = $attributes['image']; + $this->thumbWidth = $attributes['thumb_width']; + $this->thumbHeight = $attributes['thumb_height']; + $this->width = $attributes['width']; + $this->height = $attributes['height']; + $this->id = $id; + } + + // }}} + + // {{{ getActive() + + /** + * Gets the active flag + * + * @return boolean node active flag + * @access public + */ + public function getActive() + { + return $this->active; + } + + // }}} + // {{{ getExternal() + + /** + * Checks whether it is external url + * + * @return boolean + * @access public + */ + public function getExternal() + { + return $this->external; + } + + // }}} + // {{{ getHeight() + + /** + * Get image height + * + * @return integer image height + * @access public + */ + public function getHeight() + { + return $this->height; + } + + // }}} + // {{{ getId() + + /** + * Gets the node id in the database + * + * @return integer database id + * @access public + */ + public function getId() + { + return $this->id; + } + + // }}} + // {{{ getImage() + + /** + * Get image + * + * @return string image + * @access public + */ + public function getImage() + { + return $this->image; + } + + // }}} + // {{{ getThumbHeight() + + /** + * Get Thumbnail height + * + * @return integer thumbnail height + * @access public + */ + public function getThumbHeight() + { + return $this->thumbHeight; + } + + // }}} + // {{{ getThumbWidth() + + /** + * Get thumbnail width + * + * @return integer thumbnail width + * @access public + */ + public function getThumbWidth() + { + return $this->thumbWidth; + } + + // }}} + // {{{ getWidth() + + /** + * Get image width + * + * @return integer image width + * @access public + */ + public function getWidth() + { + return $this->width; + } + + // }}} + // {{{ getUrl() + + /** + * Get image url + * + * @return string image url + * @access public + */ + public function getUrl() + { + return $this->url; + } + + // }}} + + // {{{ isAnchor() + + /** + * Checks whether the image is an anchor + * + * @return boolean + * @access public + */ + public function isAnchor() + { + return !empty($this->url); + } + + // }}} + + // {{{ setActive() + + /** + * set the active flag to true for the node + * + * @param boolean $active new active flag to set + * + * @return void + * @access public + */ + public function setActive($active) + { + if (!is_bool($active)) { + throw InvalidArgumentException( + '$active must be a boolean.' + ); + } + + $this->active = $active; + } + + // }}} + // {{{ setExternal() + + /** + * Sets external + * + * @param boolean $external External + * + * @return void + * @access public + */ + public function setExternal($external) + { + $this->external = (bool) $external; + } + + // }}} + // {{{ setImage() + /** + * Sets image + * + * @param string $image Image + * + * @return void + * @access public + * + */ + public function setImage($image) + { + $this->image = $image; + } + + // }}} + // {{{ setUrl() + + /** + * Sets url + * + * @param string $url url + * + * @throws InvalidArgumentException + * @return void + * @access public + */ + public function setUrl($url) + { + if (!filter_var($url, FILTER_VALIDATE_URL)) { + throw new InvalidArgumentException( + '$url parameter must be a valid url' + ); + } + $this->url = $url; + } + + // }}} + // {{{ setThumbHeight() + + /** + * Set the thumbnail image height value + * + * @param integer $thumbHeight thumbnail image height + * + * @return void + * @access public + */ + public function setThumbHeight($thumbHeight) + { + if (!filter_var($thumbHeight, FILTER_VALIDATE_INT)) { + throw new InvalidArgumentException( + "`$thumbHeight` is not an integer" + ); + } + $this->thumbHeight = $thumbHeight; + } + + // }}} + // {{{ setThumbWidth() + + /** + * Set the thumbnail image width value + * + * @param integer $thumbWidth thumbnail image width + * + * @return void + * @access public + */ + public function setThumbWidth($thumbWidth) + { + if (!filter_var($thumbWidth, FILTER_VALIDATE_INT)) { + throw new InvalidArgumentException( + "`$thumbWidth` is not an integer" + ); + } + $this->thumbWidth = $thumbWidth; + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/ImagesDataGridAbstract.php b/Toolkit/RotatingImages/ImagesDataGridAbstract.php new file mode 100644 index 0000000..3a0939e --- /dev/null +++ b/Toolkit/RotatingImages/ImagesDataGridAbstract.php @@ -0,0 +1,214 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_ImagesDataGridAbstract + * + * Description of Toolkit_RotatingImages_ImagesDataGridAbstract + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_RotatingImages_ImagesDataGridAbstract + extends Toolkit_FlexyDataGridBuilder +{ + // {{{ properties + + /** + * Description of $noRecMessage + * @var string + * @access protected + */ + protected $noRecMessage = 'No Images'; + + // }}} + // {{{ configureColumns() + + /** + * Description for configureColumns + * + * @return void + */ + protected function configureColumns() + { + $id = new Structures_DataGrid_Column( + 'ID', + 'id', + 'id' + ); + $this->addColumn($id); + + $delete = new Structures_DataGrid_Column( + 'Delete', + null, + null, + array('class' => 'delLink'), + null, + array(&$this, 'renderDeleteLink') + ); + $this->addColumn($delete); + + $edit = new Structures_DataGrid_Column( + 'Edit', + null, + null, + array('class' => 'editLink'), + null, + array(&$this, 'renderEditLink') + ); + $this->addColumn($edit); + + $url = new Structures_DataGrid_Column( + 'URL', + 'url', + 'url' + ); + $this->addColumn($url); + + $image = new Structures_DataGrid_Column( + 'Image', + null, + null, + array('class' => 'image'), + null, + array(&$this, 'renderImage') + ); + $this->addColumn($image); + } + + // }}} + // {{{ renderEditLink() + + /** + * Render the edit link for an image + * + * @param array $data DB record + * + * @return mixed Link to edit a banner + * @access public + */ + public function renderEditLink($data) + { + extract($data['record']); + $imgFormat = 'Edit Image Icon Edit Image'; + $img = sprintf( + $imgFormat, + GLM_APP_BASE_URL . 'assets/icons/image_edit.png' + ); + + $linkFormat = '%s'; + return sprintf( + $linkFormat, + BASE_URL . 'admin/rotatingImages.php', + "rt=EditImage&id=$id", + $img + ); + } + + // }}} + // {{{ renderDeleteLink() + + /** + * Render the delete link for an image + * + * @param array $data DB record + * + * @return mixed Link to edit a banner + * @access public + */ + public function renderDeleteLink($data) + { + extract($data['record']); + $imgFormat = 'Delete Image Icon Delete Image'; + $img = sprintf( + $imgFormat, + GLM_APP_BASE_URL . 'assets/icons/image_delete.png' + ); + + $linkFormat = '%s'; + return sprintf( + $linkFormat, + BASE_URL . 'admin/rotatingImages.php', + "rt=EditImage&ac=delete&id=$id", + $img); + } + + // }}} + // {{{ renderImage() + + /** + * Render the delete link for an image + * + * @param array $data DB record + * + * @return mixed Link to edit a banner + * @access public + */ + public function renderImage($data) + { + extract($data['record']); + $imgFormat = 'Image thumbnail'; + return sprintf( + $imgFormat, + $thumb_width, + $thumb_height, + ROTATING_IMAGE_THUMB . $image + ); + } + + // }}} + + // {{{ toHtml() + + /** + * Returns the DataGrid + * + * @param Structures_DataGrid_Renderer_Flexy $renderer Rendering engine used to render DG + * @param string $template Template to use + * + * @return string html templated datagrid results + * @access public + */ + public function toHtml( + Structures_DataGrid_Renderer_Flexy $renderer, + $template = null + ) { + $GLOBALS['styleSheets'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/themes/smoothness/jquery.ui.core.css'; + $GLOBALS['styleSheets'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/themes/smoothness/jquery.ui.theme.css'; + + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.core.min.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.widget.min.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.mouse.min.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.sortable.min.js'; + $GLOBALS['bottomScripts'][] + = BASE_URL . 'Toolkit/RotatingImages/libjs/sortable.js'; + + return parent::toHtml($renderer, $template); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/InactiveImagesDataGrid.php b/Toolkit/RotatingImages/InactiveImagesDataGrid.php new file mode 100644 index 0000000..d545777 --- /dev/null +++ b/Toolkit/RotatingImages/InactiveImagesDataGrid.php @@ -0,0 +1,67 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_InactiveImagesDataGrid + * + * Description of Toolkit_RotatingImages_InactiveImagesDataGrid + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_InactiveImagesDataGrid + extends Toolkit_RotatingImages_ImagesDataGridAbstract + implements Toolkit_RotatingImages_IImagesDataGrid +{ + // {{{ setControlObject() + + /** + * setControlObject + * + * @return void + */ + protected function setControlObject() + { + $this->ctrlObj['tableId'] = 'disabled'; + //$this->ctrlObj['noRecMessage'] = 'No Disabled Images'; + $this->ctrlObj['gridName'] = 'Disabled Images'; + } + + // }}} + // {{{ setQuery() + + /** + * Sets query to get inactive rotating images + * + * @return void + */ + public function setQuery() + { + $sql = " + SELECT * + FROM rotating_images + WHERE active = false"; + + parent::setQuery($sql); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/IndexController.php b/Toolkit/RotatingImages/IndexController.php new file mode 100644 index 0000000..5c1943a --- /dev/null +++ b/Toolkit/RotatingImages/IndexController.php @@ -0,0 +1,147 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_IndexController + * + * Description of Toolkit_RotatingImages_IndexController + * + * @category Toolkit + * @package RotatingImages + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_IndexController + extends Toolkit_BaseControllerAbstract implements Toolkit_IController +{ + // {{{ indexAction() + + /** + * Description of indexAction() + * + * @return string + */ + public function indexAction() + { + $GLOBALS['styleSheets'][] + = BASE_URL . 'Toolkit/RotatingImages/styles.css'; + + $flexyOptions = $GLOBALS['flexyOptions']; + $flexyOptions['templateDir'] = BASE . 'Toolkit/RotatingImages/templates/'; + $flexyOptions['compileDir'] = $flexyOptions['templateDir'] . 'compiled/'; + $tEngine = new HTML_Template_Flexy($flexyOptions); + + $controllerObject = new stdClass(); + + $controllerObject->width + = $this->registry->config->getItem('section', 'conf') + ->getItem('directive', 'width') + ->getContent(); + $controllerObject->height + = $this->registry->config->getItem('section', 'conf') + ->getItem('directive', 'height') + ->getContent(); + + + $tEngine->compile('instructions.html'); + $ret = $tEngine->bufferedOutputObject($controllerObject); + + // + // Settings Form + // + $settings = new Toolkit_RotatingImages_Forms_TransitionSettings( + 'settings', + 'get', + 'rotatingImages.php?ac=preview', + 'preview' + ); + $settings->configureForm($this->registry->dbh, $this->registry->config); + $ret .= $settings->toHtml($this->registry->dbh); + + $previewIframe = new Toolkit_RotatingImages_PreviewIframe( + 'rotatingImages.php?ac=preview', + 'preview' + ); + $ret .= $previewIframe->toHtml(); + + $activeREngine = new Structures_DataGrid_Renderer_Flexy(); + $activeREngine->setContainer($tEngine); + // + // Active images datagrid + // + $activeDG = new Toolkit_RotatingImages_ActiveImagesDataGrid( + $this->registry->dbh + ); + $activeDG->setQuery(); + $activeDG->setDefaultSort(array('pos' => 'ASC')); + $ret .= $activeDG->toHtml($activeREngine, 'imagesDataGrid.html'); + + $inactiveREngine = new Structures_DataGrid_Renderer_Flexy(); + $inactiveREngine->setContainer($tEngine); + // + // In-active images datagrid + // + $disabledDG = new Toolkit_RotatingImages_InactiveImagesDataGrid( + $this->registry->dbh + ); + $disabledDG->setQuery(); + $disabledDG->setDefaultSort(array('pos' => 'ASC')); + $ret .=$disabledDG->toHtml($inactiveREngine, 'imagesDataGrid.html'); + + return $ret; + } + + // }}} + // {{{ previewAction() + + /** + * Description of previewAction + * + * @return string + */ + public function previewAction() + { + try { + $sql = " + SELECT * + FROM rotating_images + WHERE active = true"; + + $images = $this->registry->dbh->query($sql, PDO::FETCH_ASSOC)->fetchAll(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + + $gateway = new Toolkit_RotatingImages_TransitionGateway($this->registry->dbh); + $previewJavascript = new Toolkit_RotatingImages_PreviewJavascript($gateway); + $javascript = $previewJavascript->toHtml(); + $fadingDecorator = new Toolkit_RotatingImages_Decorator_Admin(); + foreach ($images as $v) { + $image = new Toolkit_RotatingImages_Image($v); + $thumbnailDecorator + = new Toolkit_RotatingImages_Decorator_Thumbnail($image); + + $fadingDecorator->add($thumbnailDecorator); + } + + return $fadingDecorator->toHtml() . $javascript; + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/Navigation.php b/Toolkit/RotatingImages/Navigation.php new file mode 100644 index 0000000..746be36 --- /dev/null +++ b/Toolkit/RotatingImages/Navigation.php @@ -0,0 +1,126 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_Navigation + * + * Sets up navigation bars + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_Navigation extends Toolkit_NavigationAbstract + implements Toolkit_INavigation +{ + // {{{ __construct() + + /** + * Class constructor + * + * @param HTML_Menu $menu + * @param HTML_Menu_Renderer $rEngine + */ + public function __construct( + HTML_Menu $menu, + HTML_Menu_Renderer $rEngine + ) { + $this->menu = $menu; + $this->rEngine = $rEngine; + $this->currIndex = 'listToolbox'; + } + + // }}} + // {{{ setNavTemplates() + + /** + * Set navigation templates + * + * @return void + */ + protected function setNavTemplates() + { + $tpl = '
  • {Title}
  • '; + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_INACTIVE, + sprintf($tpl, '{url}', '{desc}', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVE, + sprintf($tpl, '{url}', '{desc}', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVEPATH, + sprintf($tpl, '{url}', '{desc}', '{Title}') + ); + $this->rEngine->setMenuTemplate('', ''); + $this->rEngine->setRowTemplate('
      ', '
    '); + } + + // }}} + // {{{ setCurrentIndex() + + /** + * Sets current menu index + * + * @return void + */ + protected function setCurrentIndex() + { + $this->menu->forceCurrentIndex($_GET['rt']); + } + + // }}} + // {{{ getNavSructure() + + /** + * Sets up a multi dimensional array used for the nav structure + * + * @param Config_Container $c Application configuration + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure(Config_Container $c) + { + // get reference to [listing type] section of config file + $appName = $c->getItem('section', 'conf') + ->getItem('directive', 'applicationName') + ->getContent(); + + $nav = array( + 'listImages' => array( + 'Title' => "List Images", + 'url' => BASE_URL . 'admin/rotatingImages.php', + 'desc' => "Display all the Images", + ), + 'addImage' => array( + 'Title' => 'Add Image', + 'url' => BASE_URL . 'admin/rotatingImages.php?rt=EditImage', + 'desc' => 'Display all the page drafts' + + ), + ); + + return $nav; + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/NodesIterator.php b/Toolkit/RotatingImages/NodesIterator.php new file mode 100644 index 0000000..d2b98c9 --- /dev/null +++ b/Toolkit/RotatingImages/NodesIterator.php @@ -0,0 +1,131 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: NodesIterator.php,v 1.2 2010/07/25 17:07:24 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * class to iterator over available rotating image nodes + * + * @category Toolkit + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_RotatingImages_NodesIterator implements IteratorAggregate +{ + // {{{ properties + + /** + * Node objects to iterator over + * @var array + * @access private + */ + private $_nodes; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @return void + * @access public + */ + public function __construct() + { + $this->_nodes = array(); + } + + // }}} + // {{{ getIterator() + + /** + * Get the iterator + * + * @return ArrayIterator iterator for arrays + * @access public + */ + public function getIterator() + { + return new ArrayIterator($this->_nodes); + } + + // }}} + // {{{ addImage() + + /** + * Add image node object to iterator + * + * @param Toolkit_RotatingImages_Image $node node object to add to iterator + * + * @return void + * @access public + */ + public function addImage(Toolkit_RotatingImages_Image $node) + { + $this->_nodes[] = $node; + } + + // }}} + // {{{ getNode() + + /** + * Get a node from the iterator + * + * @param integer $key offset to get node at + * + * @return mixed false if no nodes available, else Toolkit_RotatingImages_Image object + * @access public + * @throws InvalidArgumentException if $key is not an integer + */ + public function getNode($key) + { + if (!count($this->_nodes)) { + return false; + } + + if (!filter_var($key, FILTER_VALIDATE_INT)) { + throw new InvalidArgumentException( + "\$key must be an integer, `$key` given" + ); + } + + return $this->_nodes[$key]; + } + + // }}} + // {{{ getTotal() + + /** + * Gets the total number of nodes in the iterator + * + * @return integer number of nodes in interator + * + * @access public + */ + public function getTotal() + { + return count($this->_nodes); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/PreviewIframe.php b/Toolkit/RotatingImages/PreviewIframe.php new file mode 100644 index 0000000..e415d39 --- /dev/null +++ b/Toolkit/RotatingImages/PreviewIframe.php @@ -0,0 +1,90 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: PreviewIframe.php,v 1.1 2010/07/25 17:07:24 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Short description for class + * + * Long description (if any) ... + * + * @category Toolkit + * @package Toolkit_RotatingImages + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_RotatingImages_PreviewIframe +{ + // {{{ properties + + /** + * url of the document to show in iframe + * @var string + * @access private + */ + private $_src; + + /** + * name of the iframe + * @var string + * @access private + */ + private $_name; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param string $src URL of the document to show in ifram + * @param string $name name of the iframe + * + * @return void + * @access public + */ + public function __construct($src, $name) + { + $this->_src = $src; + $this->_name = $name; + } + + // }}} + // {{{ toHtml() + + /** + * Creates an iframe + * + * @return string html iframe tag + * @access public + */ + public function toHtml() + { + $nonSupport = 'Your browser does not support iframes.'; + $format = ''; + return sprintf($format, $this->_src, $this->_name, $nonSupport); + } + + // }}} +} +?> diff --git a/Toolkit/RotatingImages/PreviewJavascript.php b/Toolkit/RotatingImages/PreviewJavascript.php new file mode 100644 index 0000000..b7329f2 --- /dev/null +++ b/Toolkit/RotatingImages/PreviewJavascript.php @@ -0,0 +1,81 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_PreviewJavascript + * + * Description of Toolkit_RotatingImages_PreviewJavascript + * + * @category Toolkit + * @package RotatingImages + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_PreviewJavascript +{ + /** + * Transition gateway + * + * @var Toolkit_RotatingImages_TransitionGateway + * @access private + */ + private $_gateway; + + /** + * Class construct + * + * @param Toolkit_RotatingImages_TransitionGateway $gateway Construct gateway + */ + public function __construct( + Toolkit_RotatingImages_TransitionGateway $gateway + ) { + $this->_gateway = $gateway; + } + + /** + * Description for toHtml + * + * @return string + */ + public function toHtml() + { + if (filter_input(INPUT_GET, 'preview')) { + $transitionEffect = filter_input(INPUT_GET, 'transition', FILTER_SANITIZE_STRING); + $pauseTime = filter_input(INPUT_GET, 'timeout', FILTER_SANITIZE_NUMBER_INT); + } elseif (filter_input(INPUT_GET, 'apply')) { + $transitionEffect = filter_input(INPUT_GET, 'transition', FILTER_SANITIZE_STRING); + $pauseTime = filter_input(INPUT_GET, 'timeout', FILTER_SANITIZE_NUMBER_INT); + $this->_gateway->set($transitionEffect, $pauseTime); + } else { + $effect = $this->_gateway->get(); + $transitionEffect = $effect['transition']; + $pauseTime = $effect['timeout']; + } + $js = "$(window).load(function() {\n"; + $js .= " $('#rotatingImagesPreview').nivoSlider({\n"; + $js .= " effect: '$transitionEffect',\n"; + $js .= " pauseTime: $pauseTime * 1000,\n"; + $js .= " directionNav: false,\n"; + $js .= " controlNav: false\n"; + $js .= " });\n"; + $js .= "});\n"; + + return ""; + } +} +?> diff --git a/Toolkit/RotatingImages/TransitionGateway.php b/Toolkit/RotatingImages/TransitionGateway.php new file mode 100644 index 0000000..69d7ab9 --- /dev/null +++ b/Toolkit/RotatingImages/TransitionGateway.php @@ -0,0 +1,100 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_RotatingImages_TransitionGateway + * + * Gateway for transition of rotating images + * + * @category Toolkit + * @package RotatingImages + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_RotatingImages_TransitionGateway +{ + + /** + * PDO + * + * @var PDO + * @access private + */ + private $_dbh; + + /** + * Class construct + * + * @param PDO $dbh PDO + */ + public function __construcT(PDO $dbh) + { + $this->_dbh = $dbh; + } + + /** + * Getting the transitions for the slideshow + * + * @return array|null + */ + public function get() + { + try { + $sql = " + SELECT * + FROM rotating_images_transitions"; + + return $this->_dbh->query($sql)->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + } + } + + /** + * Set transition type and time + * + * @param string $transition Description for transition + * @param int $timeout Description for timeout + * + * @throws RuntimeException + * @return void + */ + public function set($transition, $timeout) + { + if (!filter_var($transition)) { + throw new RuntimeException("Invalid transition type `$transition`"); + } elseif (!filter_var($timeout, FILTER_VALIDATE_INT)) { + throw new RuntimeException("Invalid transition timeout `$transition`"); + } + + try { + $sql = " + UPDATE rotating_images_transitions + SET timeout = :timeout, transition = :transition"; + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':transition', $transition, PDO::PARAM_STR); + $stmt->bindParam(':timeout', $timeout, PDO::PARAM_INT); + + $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + } + } +} +?> diff --git a/Toolkit/RotatingImages/ajax.php b/Toolkit/RotatingImages/ajax.php new file mode 100644 index 0000000..d51cc8d --- /dev/null +++ b/Toolkit/RotatingImages/ajax.php @@ -0,0 +1,52 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + + +if ( !isset($_POST['action']) + || $_POST['action'] != 'updateOrder' +) { + return false; +} + +require_once '../../setup.phtml'; + +$dbh = Toolkit_Database::getInstance(); + +try { + $dbh->beginTransaction(); + $sql = " + UPDATE rotating_images + SET active = false, pos = null"; + + $dbh->query($sql); + + $sql = " + UPDATE rotating_images + SET active = true, pos = :pos + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $i = 1; + foreach ($_POST['image'] as $v) { + $stmt->bindParam(':pos', $i, PDO::PARAM_INT); + $stmt->bindParam(':id', $v, PDO::PARAM_INT); + $stmt->execute(); + ++$i; + } + return $dbh->commit(); +} catch (PDOException $e) { + $dbh->rollback(); + return Toolkit_Common::handleError($e); +} +?> diff --git a/Toolkit/RotatingImages/assets/.keepme b/Toolkit/RotatingImages/assets/.keepme new file mode 100644 index 0000000..e69de29 diff --git a/Toolkit/RotatingImages/config.ini b/Toolkit/RotatingImages/config.ini new file mode 100644 index 0000000..4fb20a8 --- /dev/null +++ b/Toolkit/RotatingImages/config.ini @@ -0,0 +1,27 @@ +[conf] +; Application Name +applicationName = "Homepage Slideshow" +hasPrevNextLinks = Off +width = 739 +height = 307 + +; time between the fades in milliseconds +[rotation time] +timeout[] = 5 +timeout[] = 10 +timeout[] = 15 +timeout[] = 20 +timeout[] = 25 +timeout[] = 30 + +; type of animation 'fade' or 'slide' +[animation type] +transition[] = "sliceDown" +transition[] = "sliceDownLeft" +transition[] = "sliceUp" +transition[] = "sliceUpLeft" +transition[] = "sliceUpDown" +transition[] = "sliceUpDownLeft" +transition[] = "fold" +transition[] = "fade" +transition[] = "random" diff --git a/Toolkit/RotatingImages/libjs/sortable.js b/Toolkit/RotatingImages/libjs/sortable.js new file mode 100644 index 0000000..21d1788 --- /dev/null +++ b/Toolkit/RotatingImages/libjs/sortable.js @@ -0,0 +1,56 @@ +var RISortable = +{ + init: function() + { + $('#active, #disabled').sortable({ + connectWith: 'ul', + revert: true, + cancel: '.ui-state-disabled', + distance: 15, + forcePlaceholderSize: true, + placeholder: 'ui-state-highlight', + cursor: 'move', + receive: RISortable.receive, + remove: RISortable.remove, + stop: RISortable.stop, + opacity: 0.6 + }); + $('.dataGrid').disableSelection(); + }, + + receive: function(event, ui) + { + var $disabled = $(this).children('.ui-state-disabled'); + if ($disabled.is('li')) { + $disabled.remove(); + } + }, + + remove: function(event, ui) + { + var $myself = $(this); + if ($myself.children().length == 0) { + $myself.html('
  • Drag image here to add
  • '); + } + }, + + stop: function(event, ui) + { + var order = $('#active').sortable('serialize'); + + $.post('../Toolkit/RotatingImages/ajax.php', order+'&action=updateOrder'); + +/* + $(fade.container).empty(); + $('#active img.thumbnail').each(function() { + var copy = $(this).clone(); + copy.removeAttr('class') + .removeAttr('alt'); + copy.appendTo(fade.container); + }); + fade.update(); +*/ + } +}; + +$(document).ready(RISortable.init); diff --git a/Toolkit/RotatingImages/libjs/user.php b/Toolkit/RotatingImages/libjs/user.php new file mode 100644 index 0000000..4c213d7 --- /dev/null +++ b/Toolkit/RotatingImages/libjs/user.php @@ -0,0 +1,36 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +require_once '../../../setup.phtml'; +$dbh = Toolkit_Database::getInstance(); +$sql = "select * from rotating_images_transitions"; +$row = $dbh->query($sql)->fetch(PDO::FETCH_ASSOC); +?> +$(window).load(function() { + $('#slideshow').nivoSlider({ + effect: '', + pauseTime: , + directionNav: false, + controlNav: false + }); + + $('#slideshow a.external').each(function() { + $(this).click(function() { + var $newWindow = window.open($(this).attr('href')); + $newWindow.focus(); + return false; + }); + }); +}); diff --git a/Toolkit/RotatingImages/styles.css b/Toolkit/RotatingImages/styles.css new file mode 100644 index 0000000..14abe30 --- /dev/null +++ b/Toolkit/RotatingImages/styles.css @@ -0,0 +1,119 @@ +ul.dataGrid { + list-style-type: none; + margin: 0; + padding: 0; +} +ul.dataGrid li { + margin: 0 5px 5px 5px; + padding: 5px; +} +.ui-state-default { + width: 500px; + height: 120px; + clear: left; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + border-radius: 10px; + padding: 10px !important; + border: 1px solid #999 !important } +h2 { + clear: left; +} +.thumbnail { + float: left; + -webkit-box-shadow: 2px 2px 5px #ccc; + -moz-box-shadow: 2px 2px 5px #ccc; +} +.ui-state-default { } +.info { + border: 1px solid #ccc; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + border-radius: 10px; + -moz-box-shadow: 2px 2px 5px #ccc; + -webkit-box-shadow: 2px 2px 5px #ccc; + background: #eee; + margin: 0 10px; + float: right; + width: 250px; + padding: 10px; + height: 80px; +} +.info img { + border: 0; +} +.info a { + text-decoration: underline !important; +} +.info a:hover { + color: black; + font-weight: bold; + text-decoration: none !important; +} +.dataGrid .delete { + line-height: 16px; + vertical-align: center; + float: right; + margin-top: 10px; +} +.dataGrid .edit { + line-height: 16px; + vertical-align: center; + clear: left; + margin-top: 10px; +} +.webform { + width: 250px; +} +h2 { + margin-top: 0; + padding-top: 1em; +} +#instructions { + width: 500px; + clear: left; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + border-radius: 10px; + padding: 10px !important; + border: 1px solid #D5DFC3; + background: #F3FFDF; + margin-top: 6px; +} + +/* Slideshow */ +#transition-settings { + float: left; + margin: 0 10px 0 0; + display: block; + width: 300px; +} +#rotatingImagesPreview { + height: 100px; + width: 200px; + float: left; + overflow: hidden; +} +#rotatingImagesLive { + color: orange; + font-weight: bold; + height: 1%; + overflow: hidden; +} +#rotatingImagesLive #images { + overflow: hidden; +} +#rotatingImagesLive #images img { + border-bottom: 5px solid #f7941d; +} +#if-prev, +#if-next { + text-decoration: underline; + cursor: hand; + cursor: pointer; + color: orange; +} +#if-prev:hover, +#if-next:hover { + color: black; +} diff --git a/Toolkit/RotatingImages/templates/currentTables/Element.tpl b/Toolkit/RotatingImages/templates/currentTables/Element.tpl new file mode 100755 index 0000000..595457b --- /dev/null +++ b/Toolkit/RotatingImages/templates/currentTables/Element.tpl @@ -0,0 +1,14 @@ + + + + * + + + + + +
    {error}
    + + {element} + + diff --git a/Toolkit/RotatingImages/templates/currentTables/Form.tpl b/Toolkit/RotatingImages/templates/currentTables/Form.tpl new file mode 100755 index 0000000..f59286a --- /dev/null +++ b/Toolkit/RotatingImages/templates/currentTables/Form.tpl @@ -0,0 +1,7 @@ +
    + + + {content} +
    + +
    diff --git a/Toolkit/RotatingImages/templates/currentTables/Group.tpl b/Toolkit/RotatingImages/templates/currentTables/Group.tpl new file mode 100755 index 0000000..cdd24cf --- /dev/null +++ b/Toolkit/RotatingImages/templates/currentTables/Group.tpl @@ -0,0 +1,5 @@ + + + {content} + +
    diff --git a/Toolkit/RotatingImages/templates/currentTables/GroupElement.tpl b/Toolkit/RotatingImages/templates/currentTables/GroupElement.tpl new file mode 100755 index 0000000..1a4ba27 --- /dev/null +++ b/Toolkit/RotatingImages/templates/currentTables/GroupElement.tpl @@ -0,0 +1,9 @@ + + + {element} + + * + + {label} + + diff --git a/Toolkit/RotatingImages/templates/currentTables/Header.tpl b/Toolkit/RotatingImages/templates/currentTables/Header.tpl new file mode 100755 index 0000000..64ac244 --- /dev/null +++ b/Toolkit/RotatingImages/templates/currentTables/Header.tpl @@ -0,0 +1,5 @@ + + + {header} + + diff --git a/Toolkit/RotatingImages/templates/currentTables/RequiredNote.tpl b/Toolkit/RotatingImages/templates/currentTables/RequiredNote.tpl new file mode 100755 index 0000000..dad5d0b --- /dev/null +++ b/Toolkit/RotatingImages/templates/currentTables/RequiredNote.tpl @@ -0,0 +1 @@ +* = Required Fields diff --git a/Toolkit/RotatingImages/templates/imagesDataGrid.html b/Toolkit/RotatingImages/templates/imagesDataGrid.html new file mode 100644 index 0000000..6f91d70 --- /dev/null +++ b/Toolkit/RotatingImages/templates/imagesDataGrid.html @@ -0,0 +1,22 @@ +

    {gridName:h}

    +
      + {if:numberedSet} + {foreach:recordSet,row} +
    • + + {row[Image]:h} +
      +
      {row[Delete]:h}
      +
      {row[Edit]:h}
      + {if:row[url]} +
      Link: {row[url]:h} + {end:} +
      +
    • + {end:} + {else:} +
    • + Drag image here to add +
    • + {end:} +
    diff --git a/Toolkit/RotatingImages/templates/instructions.html b/Toolkit/RotatingImages/templates/instructions.html new file mode 100644 index 0000000..8822e86 --- /dev/null +++ b/Toolkit/RotatingImages/templates/instructions.html @@ -0,0 +1,10 @@ +
    +Instructions +

    All images will be resized to correct size.

    +

    If you want to resize the images yourself before uploading, use these dimensions:

    +
      +
    • Width: {width} pixels
    • +
    • Height: {height} pixels
    • +
    +
    +

    Slideshow Settings

    diff --git a/Toolkit/Router.php b/Toolkit/Router.php new file mode 100644 index 0000000..7d709bf --- /dev/null +++ b/Toolkit/Router.php @@ -0,0 +1,195 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Registry.php,v 1.2 2010/05/25 14:07:22 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Toolkit_Router + * + * The registry is an object where site wide variables can be stored + * without the use of globals. By passing the registry object to + * the controllers that need them, we avoid pollution of the global + * namespace and render our variables safe. + * + * @category Toolkit + * @package Router + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Router +{ + // {{{ properties + + + /** + * Description for $_registry + * @var string + * @access protected + */ + private $_registry; + + /** + * Description for $_path + * @var string + * @access protected + */ + private $_path; + + /** + * Description for $_application + * @var string + * @access protected + */ + private $_application; + + /** + * Will hold location of controller + * @var string + * @access protected + */ + public $file; + + /** + * Holds intended controller + * @var string + * @access protected + */ + public $controller; + + /** + * Holds intended action + * @var string + * @access protected + */ + public $action; + + // }}} + // {{{ __construct() + + /** + * class constructor + * + * @param Toolkit_Registry $registry Registry + * + * @access public + */ + public function __construct(Toolkit_Registry $registry) + { + $this->_registry = $registry; + } + + // }}} + + // {{{ _getController() + + /** + * Gets controller and action. + * + * @access private + * @return void + */ + private function _getController() + { + $this->controller = empty($_GET['rt']) ? 'Index' : $_GET['rt']; + $this->action = empty($_GET['ac']) ? 'index' : $_GET['ac']; + + // all action methods must end in the word [Action] so we + // can easily spot them. + $this->action .= 'Action'; + + $this->file = $this->_path . '/' . $this->controller . 'Controller.php'; + } + + // }}} + + // {{{ loader() + + /** + * Loads toolkit application + * + * @return string + */ + public function loader() + { + // Check the route + $this->_getController(); + + // If the file is not there, log error + if (is_readable($this->file) == false) { + $this->_registry + ->logger + ->emerg("File is not readable: `{$this->file}`"); + } + + $class = "Toolkit_{$this->_application}_{$this->controller}Controller"; + $controller = new $class($this->_registry); + + if (is_callable(array($controller, $this->action)) == false) { + $action = 'indexAction'; + } else { + $action = $this->action; + } + + return $controller->$action(); + } + + // }}} + + // {{{ setApplication() + + /** + * Set application + * + * @param string $application Application + * + * @return void + */ + public function setApplication($application) + { + $this->_application = str_replace('/', '_', $application); + } + + // }}} + // {{{ setPath() + + /** + * Sets path + * + * @param string $path Path + * + * @throws RuntimeException + * + * @return void + */ + public function setPath($path) + { + if (is_dir($path) == false) { + throw new RuntimeException( + "Invalid controller path: `$path`" + ); + } + + $this->_path = $path; + } + + // }}} +} +?> diff --git a/Toolkit/ShortURL.php b/Toolkit/ShortURL.php new file mode 100755 index 0000000..b52a005 --- /dev/null +++ b/Toolkit/ShortURL.php @@ -0,0 +1,163 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_ShortURL + * + * Integration of Toolbox with creation of ShortURL + * the url rewrite happens with one line of code in .htaccess + * RewriteRule ^([A-Za-z0-9_-]*)$ index.php?page=$1 [L] + * index page checks for $_GET['page'] and then calls + * getShortUrlId to get the page's catid. If not found it + * defaults to HOME_ID + * + * @category Toolkit + * @package Toolkit_ShortURL + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version Release: @package_version@ + * @link <> + */ +class Toolkit_ShortURL +{ + // {{{ Class Properties + + /** + * Database handler + * @var PDO + * @access private + */ + private $_dbh; + + // }}} + + // {{{ __construct() + + /** + * __construct() + * + * @param PDO $dbh Database handler + * + * @return void + * @access public + */ + function __construct(PDO $dbh) + { + $this->_dbh = $dbh; + } + + // }}} + // {{{ getShortUrl() + + /** + * getShortUrl() + * + * grab the shorturl from bus_category table + * else return false + * + * @param string $id bus_category id + * + * @return mixed ShortURL from bus_category + * @access public + */ + function getShortUrl($id) + { + $sql = " + SELECT short_url + FROM pages + WHERE id = :id"; + try { + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(":id", $id, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getShortUrlId() + + /** + * getShortUrlId() + * + * grab the id from bus_category table + * else return false + * + * @param string $short_url bus_category short_url + * + * @return mixed catid for page or HOME_ID if not found + * @access public + */ + function getShortUrlId($short_url) + { + $sql = " + SELECT id + FROM pages + WHERE short_url = :short_url"; + try { + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(":short_url", $short_url, PDO::PARAM_STR); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + return HOME_ID; + } + + // }}} + // {{{ isValidUrlName() + + /** + * check the short url nam eto make sure it doesn't match any file names in the root + * + * @param mixed $url requested short url name + * + * @access public + * @return string + */ + public function isValidUrlName($url) + { + if (is_dir(BASE)) { + if (file_exists(BASE . $url)) { + return false; + } + if (file_exists(BASE . $url.'.php')) { + return false; + } + if (file_exists(BASE . $url.'.css')) { + return false; + } + if (file_exists(BASE . $url.'.html')) { + return false; + } + if (file_exists(BASE . $url.'.js')) { + return false; + } + return true; + } else { + throw new Exception('Main Web root dir define BASE not set'); + } + } + + // }}} +} +?> diff --git a/Toolkit/SiteMap.php b/Toolkit/SiteMap.php new file mode 100755 index 0000000..c527645 --- /dev/null +++ b/Toolkit/SiteMap.php @@ -0,0 +1,158 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: SiteMap.php,v 1.10 2010/06/08 20:39:20 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_SiteMap + * + * Generate a sitemap for the site + * need to remove members only pages and other pages you + * don't want viewed by public + * + * @category Toolkit + * @package Toolkit_SiteMap + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_SiteMap +{ + // {{{ Properties + /** + * Description of $beginLevel + * @var string + * @access public + */ + var $beginLevel = "
      "; + + /** + * Description of $endLevel + * @var string + * @access public + */ + var $endLevel = "
    "; + + /** + * Description of $beginItem + * @var string + * @access public + */ + var $beginItem = "
  • "; + + /** + * Description of $endItem + * @var string + * @access public + */ + var $endItem = "
  • "; + + /** + * Description of $wholeThread + * @var string + * @access public + */ + var $wholeThread; + + /** + * Description of $search + * @var string + * @access public + */ + var $search = ""; + + /** + * Description of $pageGateway + * @var string + * @access public + */ + var $pageGateway; + + // }}} + + /** + * Class constructor + * + * Creates object of siteMap + * + * @param string $pageGateway page gateway + */ + public function __construct($pageGateway) + { + $this->pageGateway = $pageGateway; + } + // {{{ sortChilds() + + /** + * sortChilds + * + * Sort by Parent + * + * @param array $threads Array + * + * @return array Return array + * @access public + */ + function sortChilds($threads) + { + $childs = array(); + while (list($var, $value) = each($threads)) { + $childs[$value['parent']][$value['id']] = $value; + } + return $childs; + } + + // }}} + + // {{{ convertToThread() + + /** + * convertToThread + * + * outputs the array with the correct styles and code applied + * + * @param array $threads Thread array + * @param array $thread Start with thread[0] will work it way down + * + * @return wholeThread + * @access public + */ + function convertToThread($threads, $thread) + { + static $level_counter = 1; + + $this->wholeThread .= $this->beginLevel; + while (list($parent, $value) = each($thread)) { + $this->wholeThread .= $this->beginItem; + $page = Toolkit_Template_Page::getSeoUrl( + $this->pageGateway, + $value['id'] + ); + $this->wholeThread .= ''; + $this->wholeThread .= $value["category"] + . ""; + if ($threads[$parent]) { + ++$level_counter; + $this->convertToThread($threads, $threads[$parent]); + --$level_counter; + } + $this->wholeThread .= $this->endItem ."\n"; + } + $this->wholeThread .= $this->endLevel; + return $this->wholeThread; + } + // }}} +} +?> diff --git a/Toolkit/SiteMapXml.php b/Toolkit/SiteMapXml.php new file mode 100644 index 0000000..eb7e40a --- /dev/null +++ b/Toolkit/SiteMapXml.php @@ -0,0 +1,183 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_SiteMapXml + * + * Description of Toolkit_SiteMapXml + * + * @category Toolkit + * @package Toolkit + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +class Toolkit_SiteMapXml +{ + /** + * Database Connection + * + * @var PDO + * @access private + */ + private $_dbh; + + /** + * Class Constructor + * + * @param PDO $pdo Database Connection + * + * @return void + * @access public + */ + public function __construct(PDO $pdo) + { + $this->_dbh = $pdo; + } + + /** + * getMobileSitemap + * + * Call this function with no $sid. + * + * This function will recurse down the menu structure and + * return a full list of all menu data at all levels + * + * This is helpful for generating a sitemap or index + * + * @static var array $mids Member array + * @static var string $xml XML string + * + * @param int $sid Catid of the page + * + * @return string xml + * @access public + */ + public function getXmlSitemap($sid = 0) + { + + // Characters to be replaced in link text + $transdata = array('/' => '', ' ' => '-', '&' => ''); + + // Array to keep track of member's for whom we produced links + // This is used to prevent duplicate links to the same member + // records from different catids. It's static so that it is + // common to all instances of recursion. + static $mids = array(); + + // This is where the XML site map goes. It's also static so + // we don't have to pass map segments back from recursive calls. + static $xml = ''; + + // If this is the top level, add the beginning of the xml file + if ($sid == 0) { + $xml = '' . "\r\n" + . '' . "\r\n"; + } + + $qs = " + SELECT id, navigation_name as category, include_members + FROM pages + WHERE parent = :id"; + if (defined('MEMBERS_CATEGORY') && MEMBERS_CATEGORY) { + $qs .= " AND parent != ".MEMBERS_CATEGORY." + AND id != ".MEMBERS_CATEGORY; + } + $qs .= " AND active = 't' + ORDER BY pos"; + $stmt = $this->_dbh->prepare($qs); + $stmt->bindParam( + ':id', + $sid, + PDO::PARAM_INT + ); + $stmt->execute(); + + while ($v = $stmt->fetch(PDO::FETCH_ASSOC)) { + $catid = $v['id']; + if ($catid > 0) { + // Add this menu item to the site map + $url = BASE_URL . strtr($v['category'], $transdata) . '-' + . $catid . '/'; + $xml .= '' . $url . "\r\n"; + // Get members for this catid + if (MEMBERS_DB == 1 && $v['include_members']) { + // now check to see if the page has member + // categories assigned to it + $qs = " + SELECT * + FROM member_categories2toolbox_pages + WHERE page = {$catid}"; + $mc2tpData + = $this->_dbh->query($qs) + ->fetchAll(PDO::FETCH_ASSOC); + if ($mc2tpData) { + foreach ($mc2tpData as $mc2tp) { + $mc2tpCat[] = $mc2tp['category']; + } + if (is_array($mc2tpCat) && !empty($mc2tpCat)) { + $where = " WHERE member_id IN ( + SELECT member_id + FROM member_category + WHERE category_id IN (" + . implode(",", $mc2tpCat) . ")) "; + } + } + $qs = " + SELECT member_id,member_name + FROM member + $where"; + $members = $this->_dbh + ->query($qs) + ->fetchAll(PDO::FETCH_ASSOC); + } //IF MEMBERS_DB + // If there are any + if ($members && count($members) > 0) { + // Include an entry for each member on this page + foreach ($members as $memb) { + + // Check to make sure we have a member # and + // that we haven't already provided some + // link to this member + $member = ($memb['member_id'] - 0); + if ($member > 0 && !isset($mids[$member])) { + + // Add this member to the site map + $murl = BASE_URL . 'member-profile/'.$catid + . '/' . $member . '/'; + $xml .= '' . $murl + . "\r\n"; + // Add this member to the member id array so we + // don't display them again. + $mids[$member] = true; + } + } + } // if members + $this->getXmlSitemap($catid); + } // if catid + } // if menu results + // If this is the top level, add the end of the XML file and be done + if ($sid == 0) { + $xml .= "\r\n"; + return $xml; + } + } + +} \ No newline at end of file diff --git a/Toolkit/Table.php b/Toolkit/Table.php new file mode 100644 index 0000000..7c6eb42 --- /dev/null +++ b/Toolkit/Table.php @@ -0,0 +1,300 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Abstract class for aiding creation of class objects which relate to + * Database tables + * + * @category Toolkit + * @package Table + * @author Steve Sutton + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +abstract class Toolkit_Table + implements Toolkit_ITable, Toolkit_IMapper +{ + /** + * Description for $tableName + * @var string + * @access protected + */ + protected $tableName; + + /** + * 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 = trim($args[0]); + return $this; + } + } else { + throw new Exception( + 'Call to undefined method '. get_class($this).'::' . $name + ); + } + } + + /** + * Create a class object that has the given values from an array + * + * @param Array $values Array of values to set the class properties to + * + * @return Object + * @access public + */ + public function createByValues($values) + { + $classVars = get_object_vars($this); + unset($classVars['tableName']); + foreach ($classVars as $fieldName => $var) { + if ($fieldName == 'id' && $values[$fieldName] == '') { + continue; + } + $setter = 'set' . ucfirst($fieldName); + $this->$setter($values[$fieldName]); + } + return $this; + } + + /** + * Removes a object from the database by the id + * if id is not set then it throws an error + * + * @param PDO $dbh Database Connection + * + * @return void + * @throws Exception + * @access public + */ + public function delete(PDO $dbh) + { + if (!$this->id) { + throw new Exception('id is not set'); + } + try { + $sql = " + DELETE + FROM {$this->tableName} + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $this->getId(), PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * fetch from $this->tableName by id + * + * @param PDO $dbh Database Connection + * @param integer $id id to fetch with + * + * @return null|object + * @access public + */ + public function fetchById(PDO $dbh, $id) + { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $values = $stmt->fetch(PDO::FETCH_ASSOC); + if ($values) { + return $this->createByValues($values); + } else { + return null; + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Return the object as an array + * + * @return Array + * @access public + */ + public function getPropertiesAsArray() + { + $classVars = get_object_vars($this); + unset($classVars['tableName']); + return $classVars; + } + + /** + * Return the table metadata + * + * @param PDO $dbh Database Connection + * @param string $tableName Table name + * + * @return array + * @access public + */ + public function getTableMetaData(PDO $dbh, $tableName = null) + { + try { + $sql = " + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = :tname"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':tname', $tableName, PDO::PARAM_STR); + $stmt->execute(); + + $metaData = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $metaData[$row['column_name']] = $row['data_type']; + } + + return $metaData; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + /** + * 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']); + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + $sql .= ' RETURNING id'; + $stmt = Toolkit_Common::prepareQuery( + $dbh, + $this->tableName, + $sql, + $values + ); + $stmt->execute(); + $this->setId($stmt->fetchColumn()); + return $this; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Checks the id of the object if it is set then calls update othervise + * calls insert function + * + * @param PDO $dbh Database connection + * + * @return void + * @access public + */ + public function save(PDO $dbh) + { + if ($this->id) { + $this->update($dbh); + } else { + $this->insert($dbh); + } + } + + /** + * sets the id of object + * + * @param Int $id set the id of object if not numeric throw Exception + * + * @return Toolkit_Table + * @access public + */ + public function setId($id) + { + if (!is_numeric($id)) { + throw new Exception('id must be an integer'); + } + if (!$this->id) { + $this->id = $id; + } + 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); + unset($values['tableName']); + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('id = :id') + ); + $stmt = Toolkit_Common::prepareQuery( + $dbh, + $this->tableName, + $sql, + $values + ); + $stmt->execute(); + return $this; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Validates the property + * + * @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/Template/BreadCrumbs.php b/Toolkit/Template/BreadCrumbs.php new file mode 100644 index 0000000..4d46e21 --- /dev/null +++ b/Toolkit/Template/BreadCrumbs.php @@ -0,0 +1,144 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_BreadCrumbs + * + * Description of Toolkit_Template_BreadCrumbs + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_BreadCrumbs +{ + // {{{ properties + + /** + * Description for $pageGateway + * @var Toolkit_Toolbox_PageGatewayAbstract $gateway + * @access protected + */ + protected $pageGateway; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * @access public + */ + public function __construct(Toolkit_Toolbox_PageGatewayAbstract $gateway) + { + $this->pageGateway = $gateway; + } + + // }}} + // {{{ getBreadCrumbsArray() + + /** + * Gets bread crumbs array + * + * @param int $id ID + * + * @return array + * @throws RuntimeException + * @access protected + */ + protected function getBreadCrumbsArray($id) + { + $stack = array(); + + $hasPhotoGalleriesOnThisPage + = ( defined('PHOTO_GALLERY') + && PHOTO_GALLERY + && filter_var($_GET['photo_catid'], FILTER_VALIDATE_INT) + ); + + if ($hasPhotoGalleriesOnThisPage) { + if (!$catid = filter_var($_GET['catid'], FILTER_VALIDATE_INT)) { + throw new RuntimeException('Invalid catid'); + } + if (!$photoCatid = filter_var($_GET['photo_catid'], FILTER_VALIDATE_INT)) { + throw new RuntimeException('Invalid photo_catid'); + } + $page = $this->pageGateway->findNavItem($catid); + array_unshift($stack, $page['photo_galleries'][$_GET['photo_catid']]); + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->pageGateway, + $_GET['catid'] + ); + $anchor = ''.$page['navigation_name'].''; + array_unshift($stack, $anchor); + } + + + if ($id != HOME_ID) { + $page = $this->pageGateway->findNavItem($id); + if ($hasPhotoGalleriesOnThisPage) { + // Do Nothing + } else { + array_unshift($stack, $page['navigation_name']); + } + $parent = $page['parent']; + while ($parent != 0) { + $page = $this->pageGateway->findNavItem($parent); + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->pageGateway, + $parent + ); + $anchor = ''.$page['navigation_name'].''; + array_unshift($stack, $anchor); + $parent = $page['parent']; + } + + $anchor = 'Home'; + array_unshift($stack, $anchor); + } + + return $stack; + } + + // }}} + // {{{ toHtml() + + /** + * to html + * + * @param int $id ID + * + * @return string + * @access public + */ + public function toHtml($id) + { + $breadCrumbsArray = $this->getBreadCrumbsArray($id); + $breadCrumbs = implode(' > ', $breadCrumbsArray); + + return !empty($breadCrumbsArray) + ? '' + : ''; + } + + // }}} +} +?> diff --git a/Toolkit/Template/DraftBreadCrumbs.php b/Toolkit/Template/DraftBreadCrumbs.php new file mode 100644 index 0000000..1cff6d5 --- /dev/null +++ b/Toolkit/Template/DraftBreadCrumbs.php @@ -0,0 +1,110 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_DraftBreadCrumbs + * + * Description of Toolkit_Template_DraftBreadCrumbs + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_DraftBreadCrumbs + extends Toolkit_Template_BreadCrumbs +{ + // {{{ properties + + /** + * Description for $pageGatewayPublish + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access protected + */ + protected $pageGatewayPublish; + + /** + * Description for $pageGatewayDraft + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access protected + */ + protected $pageGatewayDraft; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $publishGateway + * @param Toolkit_Toolbox_PageGatewayAbstract $draftGateway + * + * @access public + */ + public function __construct( + Toolkit_Toolbox_PageGatewayAbstract $publishGateway, + Toolkit_Toolbox_PageGatewayAbstract $draftGateway + ) { + $this->pageGatewayPublish = $publishGateway; + $this->pageGatewayDraft = $draftGateway; + } + + // }}} + // {{{ getBreadCrumbsArray() + + /** + * Gets BreadCrumbs Array + * + * @param int $id + * + * @return array + * @access protected + */ + protected function getBreadCrumbsArray($id) + { + if ($id == HOME_ID) { + return array(); + } + + $stack = array(); + $draftPage = $this->pageGatewayDraft->find($id); + array_unshift($stack, $draftPage['navigation_name']); + + $publishPage = $this->pageGatewayPublish->find($draftPage['published_page']); + $parent = $publishPage['parent']; + while ($parent != 0) { + $page = $this->pageGatewayPublish->find($parent); + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->pageGatewayPublish, + $parent + ); + $anchor = ''.$page['navigation_name'].''; + array_unshift($stack, $anchor); + $parent = $page['parent']; + } + + $anchor = 'Home'; + array_unshift($stack, $anchor); + + return $stack; + } + + // }}} +} +?> diff --git a/Toolkit/Template/DraftController.php b/Toolkit/Template/DraftController.php new file mode 100644 index 0000000..8d79bab --- /dev/null +++ b/Toolkit/Template/DraftController.php @@ -0,0 +1,82 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_DraftController + * + * Description of Toolkit_Template_DraftController + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_DraftController + extends Toolkit_Template_PageControllerAbstract +{ + /** + * Description of $_pageGatewayFactory + * + * @var Toolkit_Toolbox_PageGatewayDraftFactory + * @access private + */ + private $_pageGatewayFactory; + + /** + * Description of $_paragraphGatewayFactory + * + * @var Toolkit_Toolbox_ParagraphGatewayDraftFactory + * @access private + */ + private $_paragraphGatewayFactory; + + /** + * Description of getPageGatewayFactory + * + * @return Toolkit_Toolbox_PageGatewayDraftFactory + * @access protected + */ + protected function getPageGatewayFactory() + { + if (!($this->_pageGatewayFactory instanceof Toolkit_Toolbox_PageGatewayDraftFactory)) { + $this->_pageGatewayFactory = new Toolkit_Toolbox_PageGatewayDraftFactory( + $this->registry->dbh + ); + } + + return $this->_pageGatewayFactory; + } + + /** + * Description of getParagraphGatewayFactory + * + * @return Toolkit_Toolbox_ParagraphGatewayDraftFactory + * @access protected + */ + protected function getParagraphGatewayFactory() + { + if (!($this->_paragraphGatewayFactory instanceof Toolkit_Toolbox_ParagraphGatewayDraftFactory)) { + $this->_paragraphGatewayFactory = new Toolkit_Toolbox_ParagraphGatewayDraftFactory( + $this->registry->dbh + ); + } + + return $this->_paragraphGatewayFactory; + } +} +?> diff --git a/Toolkit/Template/Exception.php b/Toolkit/Template/Exception.php new file mode 100644 index 0000000..d623f22 --- /dev/null +++ b/Toolkit/Template/Exception.php @@ -0,0 +1,31 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_Exception + * + * Description of Toolkit_Template_Exception + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Exception extends Exception {} +?> diff --git a/Toolkit/Template/Image/Factory.php b/Toolkit/Template/Image/Factory.php new file mode 100644 index 0000000..13614db --- /dev/null +++ b/Toolkit/Template/Image/Factory.php @@ -0,0 +1,91 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Image_Factory + * + * Description of Toolkit_Template_Image_Factory + * + * @category Toolkit + * @package Template/Image + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Image_Factory +{ + // {{{ properties + + /** + * Description of $_imageServerAdapter + * + * @var string + * @access private + */ + private $_imageServerAdapter; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_FileServer_ImageAdapter $adapter Adapter + * + * @access public + */ + public function __construct(Toolkit_FileServer_ImageAdapter $adapter) + { + $this->_imageServerAdapter = $adapter; + } + + // }}} + // {{{ getImageBuilder() + + /** + * Get image builder + * + * @param array $data data + * @param string $side Side image is on + * + * @access public + * @return \Toolkit_Template_Image_Left|\Toolkit_Template_Image_Right|\Toolkit_Template_Image_Null + */ + public function getImageBuilder(array $data, $side) + { + if (isset($data['image']) && !empty($data['image'])) { + if ($side == 'left') { + return new Toolkit_Template_Image_Left( + $this->_imageServerAdapter, + $data['image'], + $data['caption'] + ); + } else { + return new Toolkit_Template_Image_Right( + $this->_imageServerAdapter, + $data['image'], + $data['caption'] + ); + } + } else { + return new Toolkit_Template_Image_Null(); + } + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/ImageAbstract.php b/Toolkit/Template/Image/ImageAbstract.php new file mode 100644 index 0000000..bb212ca --- /dev/null +++ b/Toolkit/Template/Image/ImageAbstract.php @@ -0,0 +1,114 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: ImageAbstract.php,v 1.1 2010/07/22 19:59:01 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Page Image Element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +abstract class Toolkit_Template_Image_ImageAbstract +{ + // {{{ properties + + /** + * Description for $_adapter + * + * @var string + * @access protected + */ + protected $_adapter; + + /** + * Description for $_caption + * + * @var string + * @access protected + */ + protected $_caption; + + /** + * Description for $_src + * + * @var string + * @access protected + */ + protected $_src; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * Sets elements attributes + * + * @param Toolkit_FileServer_ImageAdapter $adapter File server adapter + * @param string $src src attribute value + * @param string $caption caption + * + * @return void + * @access public + */ + public function __construct( + Toolkit_FileServer_ImageAdapter $adapter, + $src, + $caption + ) { + if (empty($src)) { + throw new InvalidArgumentException('$src cannot be empty'); + } + + $this->_adapter = $adapter; + $this->_caption = $caption; + $this->_src = $src; + } + + // }}} + + // {{{ getImage() + + /** + * Get image + * + * @param int $size Size + * + * @return string + * @access public + */ + public function getImage($size) + { + $format = '%s'; + $img = sprintf( + $format, + $size . $this->_src, + $this->_caption, + $this->_src + ); + + return $img; + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/Left.php b/Toolkit/Template/Image/Left.php new file mode 100644 index 0000000..6fb37f1 --- /dev/null +++ b/Toolkit/Template/Image/Left.php @@ -0,0 +1,62 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Left.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Page Image + * + * Returns a left side image + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Image_Left extends Toolkit_Template_Image_ImageAbstract +{ + // {{{ getImage() + + /** + * Gets the image markup + * + * @param string $size constant path to image size + * + * @return string Html image element + * @access public + */ + public function getImage($size) + { + $imageData = $this->_adapter->getImageSize($size . $this->_src); + + $html = '
    '; + $html .= parent::getImage($size); + if (!empty($this->_caption)) { + $html .= '
    '; + $html .= $this->_caption; + $html .= '
    '; + } + $html .= '
    '; + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/Null.php b/Toolkit/Template/Image/Null.php new file mode 100644 index 0000000..fe291cb --- /dev/null +++ b/Toolkit/Template/Image/Null.php @@ -0,0 +1,56 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Null.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Coupon Image Element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Image_Null +{ + /** + * Class construct + */ + public function __construct() + { + + } + + // {{{ getImage() + + /** + * Get nothing for the image + * + * @param int $size Size of image + * + * @return string empty html string; + * @access public + */ + public function getImage($size) + { + return; + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/Right.php b/Toolkit/Template/Image/Right.php new file mode 100644 index 0000000..f1ef03b --- /dev/null +++ b/Toolkit/Template/Image/Right.php @@ -0,0 +1,62 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Right.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Page Image + * + * Returns a right side image + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Image_Right extends Toolkit_Template_Image_ImageAbstract +{ + // {{{ getImage() + + /** + * Gets the image markup + * + * @param string $size constant path to image size + * + * @return string Html image element + * @access public + */ + public function getImage($size) + { + $imageData = $this->_adapter->getImageSize($size . $this->_src); + + $html = '
    '; + $html .= parent::getImage($size); + if (!empty($this->_caption)) { + $html .= '
    '; + $html .= $this->_caption; + $html .= '
    '; + } + $html .= '
    '; + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Template/IndexController.php b/Toolkit/Template/IndexController.php new file mode 100644 index 0000000..442ebfb --- /dev/null +++ b/Toolkit/Template/IndexController.php @@ -0,0 +1,82 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_IndexController + * + * Description of Toolkit_Template_IndexController + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_IndexController + extends Toolkit_Template_PageControllerAbstract +{ + /** + * Description for $_pageGatewayFactory + * + * @var Toolkit_Toolbox_PageGatewayPublishFactory + * @access private + */ + private $_pageGatewayFactory; + + /** + * Description for $_paragraphGatewayFactory + * + * @var Toolkit_Toolbox_PageGatewayPublishFactory + * @access private + */ + private $_paragraphGatewayFactory; + + /** + * description of paragraphGatewayFactory + * + * @return Toolkit_Toolbox_ParagraphGatewayPublishFactory + * @access protected + */ + protected function getPageGatewayFactory() + { + if (!($this->_pageGatewayFactory instanceof Toolkit_Toolbox_PageGatewayPublishFactory)) { + $this->_pageGatewayFactory = new Toolkit_Toolbox_PageGatewayPublishFactory( + $this->registry->dbh + ); + } + + return $this->_pageGatewayFactory; + } + + /** + * description of getParagraphGatewayFactory + * + * @return Toolkit_Toolbox_ParagraphGatewayPublishFactory + * @access protected + */ + protected function getParagraphGatewayFactory() + { + if (!($this->_paragraphGatewayFactory instanceof Toolkit_Toolbox_ParagraphGatewayPublishFactory)) { + $this->_paragraphGatewayFactory = new Toolkit_Toolbox_ParagraphGatewayPublishFactory( + $this->registry->dbh + ); + } + + return $this->_paragraphGatewayFactory; + } +} +?> diff --git a/Toolkit/Template/KeywordReplacement.php b/Toolkit/Template/KeywordReplacement.php new file mode 100644 index 0000000..c3c2230 --- /dev/null +++ b/Toolkit/Template/KeywordReplacement.php @@ -0,0 +1,86 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_KeywordReplacement + * + * Description of Toolkit_Template_KeywordReplacement + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_KeywordReplacement +{ + /** + * Description for $_pageGateway + * @var Toolkit_Toolbox_GatewayAbstract + * @access private + */ + private $_pageGateway; + + /** + * Class constructor + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Gateway + * + * @access public + */ + public function __construct(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $this->_pageGateway = $gateway; + } + + /** + * Description for findAndReplace() + * + * @param string $haystack Haystack + * + * @return string + * @access public + */ + public function findAndReplace($haystack) + { + if (strstr($haystack, '{') !== false) { + $pattern = '/\{([A-Z0-9\&\-\,\'\" ]*)\}/i'; + if (preg_match($pattern, $haystack, $needle) != 0) { + $page = $this->_pageGateway->findByKeyword($needle[1]); + if ($page == false) { + return $haystack; + } else { + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->_pageGateway, + $page['id'] + ); + $anchor = ''.$page['navigation_name'].''; + $haystack = str_replace($needle[0], $anchor, $haystack); + } + } else { + return $haystack; + } + + if (strstr($haystack, '{') !== false) { + return $this->findAndReplace($haystack); + } + } + + return $haystack; + } +} +?> diff --git a/Toolkit/Template/Navigation/Factory.php b/Toolkit/Template/Navigation/Factory.php new file mode 100644 index 0000000..95e62b7 --- /dev/null +++ b/Toolkit/Template/Navigation/Factory.php @@ -0,0 +1,116 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_Factory + * + * Description of Toolkit_Template_Navigation_Factory + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_Factory + extends Toolkit_NavigationFactoryAbstract +{ + /** + * Description for $_gateway + * + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access private + */ + private $_gateway; + + /** + * Sets gateway + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * + * @access public + * @return void + */ + public function setGateway(Toolkit_Toolbox_PageGatewayAbstract $gateway) + { + $this->_gateway = $gateway; + } + + /** + * NOTE: You have different renderers that you can choose for the main + * navigation. + * Toolkit/Template/Navigation/SideNavigation.php + * + * Renderers: all renderers use HTML_Menu which renders ul li + * DirectTreeLastLi = with id in the last li element + * DirectTreeUlId = with id in the main ul element + * DirectTreeLiId = with id on the current li element + * DirectTreeSideNavTitle = adds the page title above sidenav + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * + * @access public + * @return Toolkit_Template_Navigation_SideNavigation + */ + public function createSideNav( + Toolkit_Toolbox_PageGatewayAbstract $gateway = null + ) { + return new Toolkit_Template_Navigation_SideNavigation( + new HTML_Menu(), + new Toolkit_Template_Navigation_Renderer_DirectTreeSideNavTitle($this->_gateway) + ); + } + + /** + * New main nav added can use + * Toolkit_Template_Navigation_MainNavigationAllInOne + * Which will create a side nav that includes all main level pages + * + * NOTE: You have different renderers that you can choose for the main + * navigation. And you can choose from a static or dynamic setup. + * 1) for Dynamic setup use + * Toolkit_Template_Navigation_MainNavigationDynamic + * 2) to edit the static one edit the file + * Toolkit/Template/Navigation/MainNavigationStatic.php + * 3) with either of these navigation objects you can use a different + * renderer. + * + * Renderers: all renderers use HTML_Menu which renders ul li + * DirectTreeLastLi = with id in the last li element + * DirectTreeUlId = with id in the main ul element + * DirectTreeLiId = with id on the current li element + * + * @access public + * @return Toolkit_Template_Navigation_MainNavigationStatic + */ + public function createMainNav() + { + return new Toolkit_Template_Navigation_MainNavigationStatic( + new HTML_Menu(), + /** + * new Toolkit_Template_Navigation_Renderer_DirectTreeLiId( + * $this->_gateway, + * 'current' + * ) + */ + new Toolkit_Template_Navigation_Renderer_DirectTreeLastLi( + 'lastli' + ) + ); + } +} +?> diff --git a/Toolkit/Template/Navigation/MainNavigationAbstract.php b/Toolkit/Template/Navigation/MainNavigationAbstract.php new file mode 100644 index 0000000..69accb3 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationAbstract.php @@ -0,0 +1,103 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_MainNavigationAbstract + * + * Description of Toolkit_Template_Navigation_MainNavigationAbstract + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_Template_Navigation_MainNavigationAbstract + extends Toolkit_NavigationAbstract implements Toolkit_INavigation +{ + // {{{ __construct() + + /** + * Class constructor + * + * @param HTML_Menu $menu + * @param HTML_Menu_Renderer $rEngine + * + * @access public + */ + public function __construct( + HTML_Menu $menu, + HTML_Menu_Renderer $rEngine + ) { + $this->menu = $menu; + $this->rEngine = $rEngine; + } + + // }}} + // {{{ setNavTemplates() + + /** + * Set nav templates + * + * @return void + * @access protected + */ + protected function setNavTemplates() + { + $tpl = '{Title}'; + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_INACTIVE, + sprintf($tpl, '{url}', '', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVE, + sprintf($tpl, '{url}', 'id="current"', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVEPATH, + sprintf($tpl, '{url}', '', '{Title}') + ); + } + + // }}} + // {{{ setCurrentIndex() + + /** + * Set current index + * + * @access protected + * @return void + */ + protected function setCurrentIndex() + { + $this->menu->forceCurrentIndex($_GET['catid']); + } + + // }}} + // {{{ getNavSructure() + + /** + * Create a static array of nav items to use + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure() {} + + // }}} +} +?> diff --git a/Toolkit/Template/Navigation/MainNavigationAllInOne.php b/Toolkit/Template/Navigation/MainNavigationAllInOne.php new file mode 100644 index 0000000..36e45d9 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationAllInOne.php @@ -0,0 +1,123 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_MainNavigationAllInOne + * + * Description of Toolkit_Template_Navigation_MainNavigationDynamic + * + * @category Toolkit + * @package Template/Navigation + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_MainNavigationAllInOne + extends Toolkit_Template_Navigation_MainNavigationAbstract +{ + + /** + * Recursive function to create a multi dimensional array for sub nav + * + * create tree (A) at the starting page level, pass the tree up to + * parent page, where tree (B) is created for that level. append + * tree A to tree B as a sub under the correct parent + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway + * @param integer $id id to get subtree for + * @param array $tree subtree created to be + * passed up to the parent + * level + * @param integer $appendTo pageId to append the + * passed up subtree to + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id + ) { + static $currentPage; + if (!$currentPage) { + $currentPage = $gateway->findNavItem($id); + $this->_currentPage = $currentPage['navigation_name']; + $subPages = $gateway->findAllByParent(0); + } else { + $subPages = $gateway->findAllByParent($id); + } + $nav = array(); + foreach ($subPages as $subPage) { + // no home page in sub nav + if (defined('MEMBERS_CATEGORY') && MEMBERS_CATEGORY) { + if ( ($subPage['parent'] != MEMBERS_CATEGORY) + && $subPage['active'] + ) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } else { + if ($subPage['active']) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } + $isSubPage = $this->isSubOfPage($currentPage['id'], $subPage['id']); + if ($isSubPage) { + $nav[$subPage['id']]['sub'] + = $this->getNavStructure($gateway, $subPage['id']); + } + } + return $nav; + } + + /** + * Checks to see if the given $id is a sub page of the $parent + * + * @param type $id id of page to check + * @param type $parent Parent id to check + * + * @return boolean + */ + private function isSubOfPage($id, $parent) + { + if ($id == $parent) { + return true; + } + if ($id == 0 || $parent == 0) { + return false; + } + try { + $dbh = Toolkit_Database::getInstance(); + $sql = " + SELECT parent + FROM pages + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $id = $stmt->fetchColumn(); + return $this->isSubOfPage($id, $parent); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } +} diff --git a/Toolkit/Template/Navigation/MainNavigationDynamic.php b/Toolkit/Template/Navigation/MainNavigationDynamic.php new file mode 100644 index 0000000..8e3c079 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationDynamic.php @@ -0,0 +1,104 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_MainNavigationDynamic + * + * Description of Toolkit_Template_Navigation_MainNavigationDynamic + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_MainNavigationDynamic + extends Toolkit_Template_Navigation_MainNavigationAbstract +{ + // {{{ getNavSructure() + + /** + * Recursive function to create a multi dimensional array for sub nav + * + * create tree (A) at the starting page level, pass the tree up to + * parent page, where tree (B) is created for that level. append + * tree A to tree B as a sub under the correct parent + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway + * @param integer $id id to get subtree for + * @param array $tree subtree created to be + * passed up to the parent + * level + * @param integer $appendTo pageId to append the + * passed up subtree to + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id, + array $tree = null, + $appendTo = null + ) { + $id = 0; + $currentPage = $gateway->findNavItem($id); + $this->_currentPage = $currentPage['navigation_name']; + + $subPages = $gateway->findAllByParent($id); + + $nav = array(); + foreach ($subPages as $subPage) { + // no home page in sub nav + if (defined('MEMBERS_CATEGORY') && MEMBERS_CATEGORY) { + if ( ($subPage['parent'] != MEMBERS_CATEGORY) + && $subPage['active'] + ) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } else { + if ($subPage['active']) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } + } + + if (is_array($tree) && array_key_exists($appendTo, $nav)) { + $nav[$appendTo]['sub'] = $tree; + } + + if ($currentPage['parent'] != 0) { + return $this->getNavStructure( + $gateway, + $currentPage['parent'], + $nav, + $id + ); + } else { + return $nav; + } + } + + // }}} +} +?> diff --git a/Toolkit/Template/Navigation/MainNavigationStatic.php b/Toolkit/Template/Navigation/MainNavigationStatic.php new file mode 100644 index 0000000..9efce29 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationStatic.php @@ -0,0 +1,71 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_Navigation_MainNavigationStatic + * + * Description of Toolkit_Template_Navigation_MainNavigationStatic + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_MainNavigationStatic + extends Toolkit_Template_Navigation_MainNavigationAbstract +{ + // {{{ getNavSructure() + + /** + * Create a static array of nav items to use + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway + * @param integer $id Not used for static nav + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id = null + ) { + $staticPages = array( + HOME_ID, // Home Page + 2, // The GLM Associate + 10, // Contact Gaslight Media + 81, // Services Offered + 86, // About Gaslight Media + ); + + $nav = array(); + + foreach ($staticPages as $pageId) { + // Home Page + $page = $gateway->findNavItem($pageId); + $nav[$pageId] = array( + 'Title' => htmlspecialchars($page['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $pageId) + ); + } + + return $nav; + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/Renderer/DirectTreeLastLi.php b/Toolkit/Template/Navigation/Renderer/DirectTreeLastLi.php new file mode 100644 index 0000000..28f43db --- /dev/null +++ b/Toolkit/Template/Navigation/Renderer/DirectTreeLastLi.php @@ -0,0 +1,97 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DirectTreeRendererLastLi.php,v 1.2 2010/07/27 19:14:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Renderer to create a LI list that has an id on the last element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Navigation_Renderer_DirectTreeLastLi + extends HTML_Menu_DirectTreeRenderer +{ + // {{{ properties + + /** + * Id to be assigned to last LI + * @var string + * @access private + */ + private $_id = null; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * @param string $id id to be assigned to last li + * + * @return void + * @access public + */ + public function __construct($id = null) + { + if (!is_null($id)) { + $this->_id = $id; + } + } + + // }}} + // {{{ finishMenu() + + /** + * Rendering before finishing + * + * if an id must be assigned to the last li element, then extract that + * element from the string and adjust the opening template + * + * @param integer $level Parameter description (if any) ... + * + * @return void + * @access public + */ + function finishMenu($level) + { + parent::finishMenu($level); + if (!is_null($this->_id)) { + $dom = new DOMDocument(); + $htmlUTF8 = mb_convert_encoding($this->_html, 'HTML-ENTITIES', 'UTF-8'); + @$dom->loadHTML($htmlUTF8); + + $uls = $dom->getElementsByTagName('ul'); + $ul = $uls->item(0); + $ul->lastChild->setAttribute('id', $this->_id); + + // Prevent auto tags and doctype from being added to the HTML + $this->_html = substr( + $dom->saveXML($dom->getElementsByTagName('ul')->item(0)), + 0 + ); + } + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/Renderer/DirectTreeLiId.php b/Toolkit/Template/Navigation/Renderer/DirectTreeLiId.php new file mode 100644 index 0000000..1b81bc8 --- /dev/null +++ b/Toolkit/Template/Navigation/Renderer/DirectTreeLiId.php @@ -0,0 +1,121 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DirectTreeRendererLastLi.php,v 1.2 2010/07/27 19:14:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Renderer to create a LI list that has an id on the last element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Navigation_Renderer_DirectTreeLiId + extends HTML_Menu_DirectTreeRenderer +{ + // {{{ properties + + /** + * Id to be assigned to last LI + * @var string + * @access private + */ + private $_id = null; + + /** + * Database gateway for toolbox + * @var string + * @access private + */ + private $_gateway; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * @param string $id id to be assigned to last li + * + * @return void + * @access public + */ + public function __construct( + Toolkit_Toolbox_PageGatewayAbstract $gateway, + $id = null + ) { + $this->_gateway = $gateway; + + if (!is_null($id)) { + $this->_id = $id; + } + } + + // }}} + // {{{ finishMenu() + + /** + * Rendering before finishing + * + * if an id must be assigned to the last li element, then extract that + * element from the string and adjust the opening template + * + * @param integer $level Parameter description (if any) ... + * + * @return void + * @access public + */ + function finishMenu($level) + { + parent::finishMenu($level); + if (!is_null($this->_id)) { + $dom = new DOMDocument(); + $htmlUTF8 = mb_convert_encoding($this->_html, 'HTML-ENTITIES', 'UTF-8'); + @$dom->loadHTML($htmlUTF8); + + $xpath = new DOMXPath($dom); + $element = $xpath->query("//*[@id='{$this->_id}']")->item(0); + + if ($pageId = filter_input(INPUT_GET, 'catid', FILTER_VALIDATE_INT)) { + $topParent = $this->_gateway->findTopParent($pageId); + $page = $this->_gateway->find($topParent); + $nodes = $dom->getElementsByTagName('a'); + foreach ($nodes as $node) { + if ($node->nodeValue == $page['navigation_name']) { + // uncomment to put id on parent node + // $node = $node->parentNode; + $node->setAttribute('id', $this->_id); + } + } + } + + // Prevent auto tags and doctype from being added to the HTML + $this->_html = substr( + $dom->saveXML($dom->getElementsByTagName('ul')->item(0)), + 0 + ); + } + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php b/Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php new file mode 100644 index 0000000..3d27b6c --- /dev/null +++ b/Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php @@ -0,0 +1,84 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DirectTreeRendererSideNavTitle.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Render the side nav w/ the top parent as a header above the nav + * + * @category Toolkit + * @package Toolkit_Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Navigation_Renderer_DirectTreeSideNavTitle + extends HTML_Menu_DirectTreeRenderer +{ + // {{{ properties + + /** + * Page gateway to use + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access private + */ + private $_gateway; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Page gateway to use + * + * @return void + * @access public + */ + public function __construct(Toolkit_Toolbox_PageGatewayAbstract $gateway) + { + $this->_gateway = $gateway; + } + + // }}} + + // {{{ finishMenu() + + /** + * Render nav with header before it + * + * Render the entire nav, then prepend the top level parent pages + * navigation name as a head above the nav + * + * @param integer $level Parameter description (if any) ... + * + * @return void + * @access public + */ + public function finishMenu($level) + { + parent::finishMenu($level); + $topParentId = $this->_gateway->findTopParent($_GET['catid']); + $page = $this->_gateway->find($topParentId); + $this->_html = "

    {$page['navigation_name']}

    " . $this->_html; + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/Renderer/DirectTreeUlId.php b/Toolkit/Template/Navigation/Renderer/DirectTreeUlId.php new file mode 100644 index 0000000..0e6a9aa --- /dev/null +++ b/Toolkit/Template/Navigation/Renderer/DirectTreeUlId.php @@ -0,0 +1,125 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DirectTreeRendererLastLi.php,v 1.2 2010/07/27 19:14:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Renderer to create a LI list that has an id on the last element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Navigation_Renderer_DirectTreeUlId + extends HTML_Menu_DirectTreeRenderer +{ + // {{{ properties + + /** + * Id to be assigned to first ul as id + * @var string + * @access private + */ + private $_id = null; + /** + * Id to be assigned to first ul as class + * @var string + * @access private + */ + private $_class = null; + + /** + * Database gateway for toolbox + * @var string + * @access private + */ + private $_gateway; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway database gateway + * @param string $id id to be assigned to last li + * @param string $class id to be assigned to first ul as class + * + * @return void + * @access public + */ + public function __construct( + Toolkit_Toolbox_PageGatewayAbstract $gateway, + $id = null, + $class = null + ) { + $this->_gateway = $gateway; + + if (!is_null($id)) { + $this->_id = $id; + } + if (!is_null($class)) { + $this->_class = $class; + } + } + + // }}} + // {{{ finishMenu() + + /** + * Rendering before finishing + * + * if an id must be assigned to the last li element, then extract that + * element from the string and adjust the opening template + * + * @param integer $level Parameter description (if any) ... + * + * @return void + * @access public + */ + function finishMenu($level) + { + parent::finishMenu($level); + if (!is_null($this->_id)) { + $dom = new DOMDocument(); + $htmlUTF8 = mb_convert_encoding($this->_html, 'HTML-ENTITIES', 'UTF-8'); + @$dom->loadHTML($htmlUTF8); + + $xpath = new DOMXPath($dom); + $element = $xpath->query("//*[@id='{$this->_id}']")->item(0); + + $node = $dom->getElementsByTagName('ul')->item(0); + $node->setAttribute('id', $this->_id); + if (!is_null($this->_class)) { + $node->setAttribute('class', $this->_class); + } + + // Prevent auto tags and doctype from being added to the HTML + $this->_html = substr( + $dom->saveXML($dom->getElementsByTagName('ul')->item(0)), + 0 + ); + } + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/SideNavigation.php b/Toolkit/Template/Navigation/SideNavigation.php new file mode 100644 index 0000000..16611f1 --- /dev/null +++ b/Toolkit/Template/Navigation/SideNavigation.php @@ -0,0 +1,156 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_Navigation_SideNavigation + * + * Description of Toolkit_Template_Navigation_SideNavigation + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_SideNavigation + extends Toolkit_NavigationAbstract implements Toolkit_INavigation +{ + // {{{ __construct() + + /** + * Class constructor + * + * @param HTML_Menu $menu + * @param HTML_Menu_Renderer $rEngine + * + * @access public + */ + public function __construct( + HTML_Menu $menu, + HTML_Menu_Renderer $rEngine + ) { + $this->menu = $menu; + $this->rEngine = $rEngine; + } + + // }}} + // {{{ setNavTemplates() + + /** + * Set nav templates + * + * @access protected + * @return void + */ + protected function setNavTemplates() + { + $tpl = '{Title}'; + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_INACTIVE, + sprintf($tpl, '{url}', '', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVE, + sprintf($tpl, '{url}', 'id="current"', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVEPATH, + sprintf($tpl, '{url}', '', '{Title}') + ); + } + + // }}} + // {{{ setCurrentIndex() + + /** + * Set current index + * + * @access protected + * @return void + */ + protected function setCurrentIndex() + { + $this->menu->forceCurrentIndex(filter_var($_GET['catid'], FILTER_SANITIZE_NUMBER_INT)); + } + + // }}} + // {{{ getNavSructure() + + /** + * Recursive function to create a multi dimensional array for sub nav + * + * create tree (A) at the starting page level, pass the tree up to + * parent page, where tree (B) is created for that level. append + * tree A to tree B as a sub under the correct parent + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway + * @param integer $id id to get subtree for + * @param array $tree subtree created to be + * passed up to the parent + * level + * @param integer $appendTo pageId to append the + * passed up subtree to + * @return array navigational array hash + * @access public + */ + public function getNavStructure( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id, + array $tree = null, + $appendTo = null + ) { + $currentPage = $gateway->findNavItem($id); + $this->_currentPage = $currentPage['navigation_name']; + + $subPages = $gateway->findAllByParent($id); + + $nav = array(); + foreach ($subPages as $subPage) { + // no home page in sub nav + if ( ($subPage['id'] != HOME_ID) + && ($subPage['parent'] != MEMBERS_CATEGORY) + && $subPage['active'] + ) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } + + if ( is_array($tree) + && !empty($tree) + && array_key_exists($appendTo, $nav) + ) { + $nav[$appendTo]['sub'] = $tree; + } + + if ($currentPage['parent'] != 0) { + return $this->getNavStructure( + $gateway, + $currentPage['parent'], + $nav, + $id + ); + } else { + return $nav; + } + } + + // }}} +} diff --git a/Toolkit/Template/Page.php b/Toolkit/Template/Page.php new file mode 100644 index 0000000..ac6ff3f --- /dev/null +++ b/Toolkit/Template/Page.php @@ -0,0 +1,138 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page + * + * Description of Toolkit_Template_Page + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page +{ + // {{{ __construct() + + /** + * Class constructor + * + * @access public + */ + public function __construct() + { + + } + + // }}} + + // {{{ getSeoUrl() + + /** + * Description for getSeoUrl + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Gateway + * @param string $id ID + * + * @return boolean|string + * @access public + */ + public static function getSeoUrl( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id + ) { + if (!ctype_digit((string)$id)) { + return false; + } + + if ($id == HOME_ID) { + return ($_ENV['GLM_HOST_ID'] != 'PRODUCTION') + ? BASE_URL . 'index.php' + : BASE_URL; + } + + $page = $gateway->findNavItem($id); + $shortUrlsOn + = (SHORT_URLS) + ? true + : false; + + if (empty($page['short_url']) || !$shortUrlsOn) { + $name = str_replace(' ', '-', $page['navigation_name']); + $pattern = '/[\/#&?\'"]|amp;/'; + $name = preg_replace( + $pattern, + '', + strip_tags(strtolower(trim($name))) + ); + $baseUrl + = in_array($id, unserialize(SECURE_PAGES)) + ? BASE_SECURE_URL + : BASE_URL; + return $baseUrl . htmlspecialchars($name) . "-$id/"; + } else { + return BASE_URL . "{$page['short_url']}/"; + } + } + + // }}} + + // {{{ getBody() + + /** + * Get body + * + * @param string $id id + * @param Toolkit_Template_Page_BodyFactory $bodyFactory body factory + * + * @return string + * @access public + */ + public function getBody( + $id, + Toolkit_Template_Page_BodyFactory $bodyFactory + ) { + $body = $bodyFactory->getPageBodyBuilder($id); + return $body->getContent($id); + } + + // }}} + + /** + * is member only + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway gateway + * @param string $id id + * + * @return boolean + * @access public + */ + public static function isMemberOnly(/*{{{*/ + Toolkit_Toolbox_GatewayAbstract $gateway, + $id + ) { + $page = $gateway->find($id); + + if ($page['parent'] == MEMBERS_CATEGORY) { + return true; + } else { + return false; + } + }/*}}}*/ +} diff --git a/Toolkit/Template/Page/Bad.php b/Toolkit/Template/Page/Bad.php new file mode 100644 index 0000000..fed4965 --- /dev/null +++ b/Toolkit/Template/Page/Bad.php @@ -0,0 +1,42 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_Bad + * + * Description of Toolkit_Template_Page_Bad + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_Bad +{ + /** + * Description of getContent + * + * @access public + * @return string + */ + public function getContent() + { + return '

    Sorry this page is down!

    '; + } +} +?> diff --git a/Toolkit/Template/Page/BodyFactory.php b/Toolkit/Template/Page/BodyFactory.php new file mode 100644 index 0000000..a160580 --- /dev/null +++ b/Toolkit/Template/Page/BodyFactory.php @@ -0,0 +1,216 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_BodyFactory + * + * Description of Toolkit_Template_Page_BodyFactory + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_BodyFactory +{ + // {{{ properties + + /** + * description of $_breadCrumbsFactory + * + * @var string + * @access private + */ + private $_breadCrumbsFactory; + + /** + * description of $_pageGateway + * + * @var string + * @access private + */ + private $_pageGateway; + + /** + * description of $_paragraphGateway + * + * @var string + * @access private + */ + private $_paragraphGateway; + + /** + * description of $_cache + * + * @var string + * @access private + */ + private $_cache; + + /** + * description of $_keywordReplacement + * + * @var string + * @access private + */ + private $_keywordReplacement; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory breadCrumbsFactory + * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway pageGateway + * @param Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway paragraphGateway + * @param Toolkit_Template_KeywordReplacement $keywordReplacement keywordReplacement + * @param Cache_Lite $cache cache + * + * @access public + */ + public function __construct( + Toolkit_BreadCrumbsFactory $breadCrumbsFactory, + Toolkit_Toolbox_PageGatewayAbstract $pageGateway, + Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway, + Toolkit_Template_KeywordReplacement $keywordReplacement, + Cache_Lite $cache + ) { + $this->_breadCrumbsFactory = $breadCrumbsFactory; + $this->_pageGateway = $pageGateway; + $this->_paragraphGateway = $paragraphGateway; + $this->_keywordReplacement = $keywordReplacement; + $this->_cache = $cache; + + } + + // }}} + // {{{ getPageBodyBuilder() + + /** + * description of getPageBodyBuilder + * + * @param string $id ID + * + * @return \Toolkit_Members_SiteMapPage|\Toolkit_Template_Page_SiteMap + * |\Toolkit_Template_Page_Bad|\Toolkit_Template_Page_GoogleSearch + * |\Toolkit_Template_Page_Member|\Toolkit_Template_Page_Toolbox + * @access public + */ + public function getPageBodyBuilder($id) + { + $page = $this->_pageGateway->find($id); + + $forgotPassword = (isset($_GET['forgot']) && $_GET['forgot'] == 1); + $siteMap = (isset($_GET['sitemap']) && $_GET['sitemap'] == 1); + $memberDbSiteMap = ( isset($_GET['memberDbSiteMap']) + && $_GET['memberDbSiteMap'] == 1); + $pageDoesNotExist = ($page === false); + $pageIsTurnedOff = ( is_array($page) + && !$page['active'] + && !strstr($_SERVER['HTTP_REFERER'], 'admin/') + && !$_REQUEST['preview']); + $googleSearch = ( defined('GOOGLE_SEARCH') + && GOOGLE_SEARCH + && isset($_GET['query']) + && !empty($_GET['query'])); + $memberPage = ( defined('MEMBERS_DB') + && MEMBERS_DB + && $page['include_members'] + // && ( + // (isset($page['member_categories']) + // && is_array($page['member_categories']) + // && !empty($page['member_categories'])) + // || + // (isset($page['member_regions']) + // && is_array($page['member_regions']) + // && !empty($page['member_regions'])) + // ) + ); + + if ($forgotPassword) { + die('Toolkit_Template_Page_BodyFactory::getPageBodyBuilder'); + } elseif ($memberDbSiteMap) { + return new Toolkit_Members_SiteMapPage( + Toolkit_Database::getInstance(), + $this->_pageGateway + ); + } elseif ($siteMap) { + return new Toolkit_Template_Page_SiteMap( + Toolkit_Database::getInstance(), + $this->_pageGateway + ); + } elseif ($pageDoesNotExist) { + // page does not exist + // give 301 redirect and go back to index page + header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently'); + header('Location: ' . BASE_URL . 'index.php'); + exit(); + } elseif ($pageIsTurnedOff) { + // page exists, but is turned off + // give 404 redirect and go back to index page + header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); + return new Toolkit_Template_Page_Bad(); + } elseif ($googleSearch) { + return new Toolkit_Template_Page_GoogleSearch(); + } elseif ($memberPage) { + $conf = new Config; + $root =& $conf->parseConfig( + BASE . 'Toolkit/Members/config.ini', + 'IniFile' + ); + + $imageAdapter = new Toolkit_FileServer_ImageAdapter(); + + return new Toolkit_Template_Page_Member( + $id, + new Toolkit_Template_Image_Factory($imageAdapter), + $this->_breadCrumbsFactory, + $this->_pageGateway, + $this->_paragraphGateway, + $this->_keywordReplacement, + $this->_cache, + $root + ); + } else { // regular toolbox page + $imageAdapter = new Toolkit_FileServer_ImageAdapter(); + + $photoGallery = null; + if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) { + $dbh = Toolkit_Database::getInstance(); + $photoGallery = new Toolkit_Photos_Gallery( + $dbh, + new Toolkit_Photos_Display($dbh) + ); + } + + return new Toolkit_Template_Page_Toolbox( + $id, + new Toolkit_Template_Image_Factory($imageAdapter), + $this->_breadCrumbsFactory, + $this->_pageGateway, + $this->_paragraphGateway, + $this->_keywordReplacement, + $this->_cache, + $photoGallery + ); + } + } + + // }}} +} diff --git a/Toolkit/Template/Page/FileLink/Abstract.php b/Toolkit/Template/Page/FileLink/Abstract.php new file mode 100644 index 0000000..a5971e9 --- /dev/null +++ b/Toolkit/Template/Page/FileLink/Abstract.php @@ -0,0 +1,151 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id:$ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Abstract base class for file links + * + * Long description (if any) ... + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +abstract class Toolkit_Template_Page_FileLink_Abstract +{ + // {{{ properties + + + /** + * Database Id + * @var integer + * @access protected + */ + protected $id; + + /** + * Filename + * @var string + * @access protected + */ + protected $filename; + + /** + * Size in bytes of file + * @var integer + * @access protected + */ + protected $bytes; + + /** + * Type of file + * @var string + * @access protected + */ + protected $type; + + /** + * Text to display for link + * @var string + * @access protected + */ + protected $urltext; + + /** + * Paragraph id file belongs to + * @var integer + * @access protected + */ + protected $paragraph; + + /** + * Position of file + * @var integer + * @access protected + */ + protected $pos; + + /** + * File link + * @var string + * @access protected + */ + protected $format = '

    %s

    '; + + /** + * File extension + * @var string + * @access protected + */ + protected $fileExtension; + + // }}} + // {{{ __construct() + + + /** + * Constructor + * + * @param Toolkit_Toolbox_FileExtension $fileExtension file extension helper + * + * @return void + * @access public + */ + public function __construct(Toolkit_Toolbox_FileExtension $fileExtension) + { + $this->fileExtension = $fileExtension; + } + + // }}} + // {{{ readFileArray() + + + /** + * Reads the file array of info and populates the object + * + * @param array $file file data + * + * @return void + * @access public + */ + public function readFileArray (array $file) + { + foreach ($file as $key => $value) { + $this->$key = $value; + } + } + + // }}} + // {{{ getLink() + + /** + * Abstract method to subclass + * + * generates the appropriate link for the type of file + * + * @access public + */ + abstract public function getLink(); + + // }}} +} diff --git a/Toolkit/Template/Page/FileLink/Factory.php b/Toolkit/Template/Page/FileLink/Factory.php new file mode 100644 index 0000000..fca84a0 --- /dev/null +++ b/Toolkit/Template/Page/FileLink/Factory.php @@ -0,0 +1,50 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_FileLink_Factory + * + * Description of Toolkit_Template_Page_FileLink_Factory + * + * @category Toolkit + * @package Template/Page/FileLink + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_FileLink_Factory +{ + /** + * Create Link Renderer + * + * @param array $file File array + * + * @return object Either Image or File object + * @access public + */ + static public function createLinkRenderer(array $file) + { + $fileType = substr($file['filename'], 0, 2); + $fileExt = new Toolkit_Toolbox_FileExtension; + $renderer = ($fileType == 'is') + ? new Toolkit_Template_Page_FileLink_Image($fileExt) + : new Toolkit_Template_Page_FileLink_File($fileExt); + + $renderer->readFileArray($file); + return $renderer; + } +} diff --git a/Toolkit/Template/Page/FileLink/File.php b/Toolkit/Template/Page/FileLink/File.php new file mode 100644 index 0000000..bd67023 --- /dev/null +++ b/Toolkit/Template/Page/FileLink/File.php @@ -0,0 +1,57 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_Page_FileLink_File + * + * Description of Toolkit_Template_Page_FileLink_File + * + * @category Toolkit + * @package Template/Page/FileLink + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_FileLink_File + extends Toolkit_Template_Page_FileLink_Abstract +{ + // {{{ getLink() + + /** + * Gets the link of a file + * + * @return string $link Formatted string + * @access public + */ + public function getLink() + { + $folder = substr($this->filename, 2, 2); + $urltext = urlencode($this->urltext); + $url = UPLOADED_FILES . "_ORIGINAL_/{$this->filename}"; + + $link = sprintf( + $this->format, + $this->fileExtension->getClassForType($this->filename), + $url, + $this->urltext + ); + return $link; + } + + // }}} +} diff --git a/Toolkit/Template/Page/FileLink/Image.php b/Toolkit/Template/Page/FileLink/Image.php new file mode 100644 index 0000000..2067bfa --- /dev/null +++ b/Toolkit/Template/Page/FileLink/Image.php @@ -0,0 +1,58 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_FileLink_Image + * + * Description of Toolkit_Template_Page_FileLink_Image + * + * @category Toolkit + * @package Template/Page/FileLink + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_FileLink_Image + extends Toolkit_Template_Page_FileLink_Abstract +{ + // {{{ getLink() + + /** + * Gets link of an image + * + * @return string $link Formatted string + * @access public + */ + public function getLink() + { + $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/glm.js'; + + $folder = substr($this->filename, 2, 2); + $urltext = urlencode($this->urltext); + $url = ORIGINAL . $this->filename; + + $link = sprintf( + $this->format, + $this->fileExtension->getClassForType($this->filename), + $url, + $this->urltext + ); + return $link; + } + + // }}} +} diff --git a/Toolkit/Template/Page/GoogleSearch.php b/Toolkit/Template/Page/GoogleSearch.php new file mode 100644 index 0000000..3a608be --- /dev/null +++ b/Toolkit/Template/Page/GoogleSearch.php @@ -0,0 +1,42 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_GoogleSearch + * + * Description of Toolkit_Template_Page_GoogleSearch + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_GoogleSearch +{ + /** + * Description for getContent() + * + * @return string + * @access public + */ + public function getContent() + { + return '
    '; + } +} +?> diff --git a/Toolkit/Template/Page/IBody.php b/Toolkit/Template/Page/IBody.php new file mode 100644 index 0000000..3d70bef --- /dev/null +++ b/Toolkit/Template/Page/IBody.php @@ -0,0 +1,39 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_IBody + * + * Description of Toolkit_Template_Page_IBody + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +interface Toolkit_Template_Page_IBody +{ + /** + * Description of getContent + * + * @access public + * @return unknown + */ + public function getContent(); +} +?> diff --git a/Toolkit/Template/Page/Member.php b/Toolkit/Template/Page/Member.php new file mode 100644 index 0000000..725f3f8 --- /dev/null +++ b/Toolkit/Template/Page/Member.php @@ -0,0 +1,361 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_Member + * + * Description of Toolkit_Template_Page_Member + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_Member extends Toolkit_Template_Page_Toolbox +{ + // {{{ properties + + /** + * Description of $_configContainer + * + * @var Config_Container + * @access private + */ + private $_configContainer; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param int $id ID + * @param Toolkit_Template_Image_Factory $imageFactory Image Factory + * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory Breadcrumbs Factory + * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway Page Gateway + * @param Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway Paragraph Gateway + * @param Toolkit_Template_KeywordReplacement $keywordReplacement Keyword Replacement + * @param Cache_Lite $cache Cache + * @param Config_Container $config Config Container + * + * @access public + */ + public function __construct( + $id, + Toolkit_Template_Image_Factory $imageFactory, + Toolkit_BreadCrumbsFactory $breadCrumbsFactory, + Toolkit_Toolbox_PageGatewayAbstract $pageGateway, + Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway, + Toolkit_Template_KeywordReplacement $keywordReplacement, + Cache_Lite $cache, + Config_Container $config + ) { + $this->id = $id; + $this->imageFactory = $imageFactory; + $this->breadCrumbsFactory = $breadCrumbsFactory; + $this->pageGateway = $pageGateway; + $this->paragraphGateway = $paragraphGateway; + $this->keywordReplacement = $keywordReplacement; + $this->cache = $cache; + $this->_configContainer = $config; + } + + // }}} + + // {{{ getBreadCrumbs() + + /** + * Gets breadcrumbs html array + * + * @param int $id ID + * + * @return array + * @access public + */ + protected function getBreadCrumbs($id) + { + $stack = parent::getbreadCrumbsArray($id); + + $lastNode = array_pop($stack); + $anchor = '' . $lastNode . ''; + array_push($stack, $anchor); + + array_push($stack, 'Member Name'); + + return parent::getBreadCrumbsHtml($stack); + } + + // }}} + // {{{ _getMemberSearchResults() + + /** + * Get member search results + * + * @param int $id ID + * + * @return string $html + * @access private + */ + private function _getMemberSearchResults($id) + { + $memberMap = false; + $page = $this->pageGateway->find($id); + $html = ''; + if ($page['include_member_map']) { + $memberMap = true; + $googleMap = new Toolkit_Members_Map(); + $html = $googleMap->toHtml(); + } + + $dbh = Toolkit_Database::getInstance(); + + $searchQuery = new Toolkit_Members_SearchQueryGenerator( + true, + $this->_configContainer + ); + + $sql = $searchQuery->getQuery($dbh); + $searchList = new Toolkit_Members_SearchList( + $dbh, + 50, + null, + null, + true + ); + + $searchList->setConfig($this->_configContainer); + $searchList->setMemberMap($memberMap); + $searchList->setPageGateway($this->pageGateway); + $searchList->setQuery($sql); + // if you add any boolean field to this sort + // you'll need to make sure you have a case if the boolean field is null + // in the SearchGenerator or it will have inconsitant results + $searchList->setDefaultSort(array('member_name' => 'ASC')); + // Rendering Engine to use + $rEngine = new Structures_DataGrid_Renderer_Flexy(); + // Templating Engine to use + $tEngine = new HTML_Template_Flexy( + Toolkit_Members::getFlexyOptions() + ); + $rEngine->setContainer($tEngine); + + $html .= $searchList->toHtml($rEngine); + + return $html; + } + + // }}} + // {{{ _getMemberSearchForm() + + /** + * Gets member search form + * + * @param int $id ID + * + * @return mixed $html or mixed from Common.php + * @access private + */ + private function _getMemberSearchForm($id) + { + $page = $this->pageGateway->find($id); + $html = ''; + if ($page['include_member_map']) { + $googleMap = new Toolkit_Members_Map(); + $html = $googleMap->toHtml(); + } + + $form = new Toolkit_Members_UserSearchForm( + 'SearchForm', + 'get', + BASE_URL . "index.php?catid={$_GET['catid']}", + null, + null, + true + ); + + $res = $form->setCatid($_GET['catid']); + if (!PEAR::isError($res)) { + $dbh = Toolkit_Database::getInstance(); + $form->setPageMemberCategories($this->pageGateway); + $form->setPageMemberRegions($this->pageGateway); + $form->configureForm($dbh, $this->_configContainer); + $html .= $form->toHtml( + Toolkit_Members::getFlexyOptions(), + $this->pageGateway + ); + } else { + return Toolkit_Common::handleError($res); + } + + return $html; + } + + // }}} + // {{{ _getMemberProfilePage() + + /** + * Gets member profile page + * + * @param int $id ID + * + * @return mixed + * @access private + */ + private function _getMemberProfilePage($id) + { + try { + $profileCreator = new Toolkit_Members_ProfilePage( + Toolkit_Database::getInstance(), + $this->pageGateway, + $_GET['member_id'] + ); + + $tEngine = new HTML_Template_Flexy( + Toolkit_Members::getFlexyOptions() + ); + + $profileWriter = new Toolkit_Members_ProfileWriter( + new Cache_Lite(Toolkit_Members::getCacheOptions()), + $tEngine + ); + + $profileWriter->setTemplate('memberDetail.tpl'); + $profileWriter->attach( + new Toolkit_Members_Exposure( + $profileCreator->getMemberId(), + 'detail' + ) + ); + + $profileCreator->setCatid($id); + $profileCreator->setConfig($this->_configContainer); + $profileCreator->setImagePath(MEMBER_RESIZED); + + return $profileWriter->toHtml($profileCreator); + } catch (PEAR_Exception $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + /** + * Description for _getPageCoupons + * + * @param int $id ID + * + * @return string|void + * @access private + */ + private function _getPageCoupons($id) + { + $page = $this->pageGateway->find($id); + if (!$page['include_coupons']) { + return; + } + + $widget = new Toolkit_Coupons_PageWidget( + new Toolkit_Coupons_WebCouponFactory(), + new Toolkit_Coupons_Coupons() + ); + + $flexyOpts = Toolkit_Coupons_Controller::getFlexyOptions(); + $tEngine = new HTML_Template_Flexy($flexyOpts); + + $widget->addPageCategories( + Toolkit_Database::getInstance(), + $id + ); + + $searchForm = new Toolkit_Coupons_UserSearch( + 'coupon_search', + 'get', + BASE_URL . 'index.php' + ); + $searchForm->configureForm( + Toolkit_Database::getInstance(), + $id + ); + + $widget->setSearchForm($searchForm); + + $couponForm = new HTML_QuickForm( + 'coupon_form', + 'post', + BASE_URL . 'Toolkit/Coupons/print.php' + ); + $renderer =& $couponForm->defaultRenderer(); + $renderer->clearAllTemplates(); + return $widget->toHtml($couponForm, $tEngine, 'coupons.html'); + } + // {{{ getContent() + + /** + * Description of getContent() + * + * @return string + * @access public + */ + public function getContent() + { + $breadCrumbsBuilder = $this->breadCrumbsFactory->createBreadCrumbsHelper(); + $page = $this->pageGateway->find($this->id); + + $coupons = null; + if (defined('COUPONS') && COUPONS) { + $coupons = $this->_getPageCoupons($this->id); + } + + if (filter_input(INPUT_GET, 'member_id', FILTER_VALIDATE_INT)) { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $profile = $this->_getMemberProfilePage($this->id); + + return $breadCrumbs . + $profile; + } elseif (!$page['search_form']) { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $searchResults = $this->_getMemberSearchResults($this->id); + $secondaryParagraphs = $this->getSecondaryParagraphs($this->id); + $primaryParagraph = $this->getPrimaryParagraph($this->id); + + return $breadCrumbs . + $primaryParagraph . + $searchResults . + $coupons . + $secondaryParagraphs; + } elseif (isset($_GET['search'])) { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $searchResults = $this->_getMemberSearchResults($this->id); + + return $breadCrumbs . + $searchResults; + } else { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $searchForm = $this->_getMemberSearchForm($this->id); + $secondaryParagraphs = $this->getSecondaryParagraphs($this->id); + $primaryParagraph = $this->getPrimaryParagraph($this->id); + + return $breadCrumbs . + $primaryParagraph . + $searchForm . + $coupons . + $secondaryParagraphs; + } + } + + // }}} +} diff --git a/Toolkit/Template/Page/SiteMap.php b/Toolkit/Template/Page/SiteMap.php new file mode 100644 index 0000000..3418ede --- /dev/null +++ b/Toolkit/Template/Page/SiteMap.php @@ -0,0 +1,146 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_SiteMap + * + * Description of Toolkit_Template_Page_SiteMap + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_SiteMap +{ + // {{{ properties + + /** + * PDO + * + * @var PDO + * @access private + */ + private $_dbh; + + /** + * description of $_pageGateway + * + * @var string + * @access private + */ + private $_pageGateway; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $dbh PDO + * @param string $pageGatweway Page Gateway + * + * @access public + */ + public function __construct(PDO $dbh, $pageGatweway) + { + $this->_dbh = $dbh; + $this->_pageGateway = $pageGatweway; + } + + // }}} + + // {{{ getContent() + + /** + * Description of getContent() + * + * @return HTML_Template_Flexy + * @access public + */ + public function getContent() + { + $GLOBALS['styleSheets'][] = BASE_URL . 'css/siteMap.css'; + $navArray = $this->getNavArray(0); + $page = new stdClass(); + $tpl = new HTML_Template_Flexy( + $GLOBALS['flexyOptions'] + ); + $page->nav = $navArray; + $tpl->compile('siteMap.html'); + return $tpl->bufferedOutputObject($page); + } + + // }}} + + /** + * Description of getNavArray + * + * @param string $parent Parent + * + * @return array + * @throws Toolkit_Template_Exception + * @access public + */ + public function getNavArray($parent) + { + $where = ''; + if ( defined('MEMBERS_CATEGORY') + && defined('MEMBERS_DB') + && MEMBERS_DB + ) { + $where = 'AND id != ' . MEMBERS_CATEGORY; + } + + try { + $sql = " + SELECT id, navigation_name, parent + FROM pages + WHERE parent = :parent + $where + ORDER BY parent, pos"; + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam( + ':parent', + $parent, + PDO::PARAM_INT + ); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $nav[$row['id']] = array( + 'label' => $row['navigation_name'], + 'url' => Toolkit_Template_Page::getSeoUrl( + $this->_pageGateway, + $row['id'] + ) + ); + $subs = $this->getNavArray($row['id']); + if ($subs) { + $nav[$row['id']]['subs'] = $subs; + } + } + return $nav; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Template_Exception( + 'Unable to fetch pages for sitemap' + ); + } + } +} +?> diff --git a/Toolkit/Template/Page/Toolbox.php b/Toolkit/Template/Page/Toolbox.php new file mode 100644 index 0000000..ceaaa74 --- /dev/null +++ b/Toolkit/Template/Page/Toolbox.php @@ -0,0 +1,452 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_Toolbox + * + * Description of Toolkit_Template_Page_Toolbox + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_Toolbox implements Toolkit_Template_Page_IBody +{ + // {{{ properties + + + /** + * Description of $id + * + * @var int + * @access protected + */ + protected $id; + + /** + * Description of $imageFactory + * + * @var Toolkit_Template_Image_Factory + * @access protected + */ + protected $imageFactory; + + /** + * Description of $breadCrumbsFactory + * + * @var Toolkit_BreadCrumbsFactory + * @access protected + */ + protected $breadCrumbsFactory; + + /** + * Description of $pageGateway + * + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access protected + */ + protected $pageGateway; + + /** + * Description of $paragraphGateway + * + * @var Toolkit_Toolbox_ParagraphGatewayAbstract + * @access protected + */ + protected $paragraphGateway; + + /** + * Description of $keywordReplacement + * + * @var Toolkit_Template_KeywordReplacement + * @access protected + */ + protected $keywordReplacement; + + /** + * Description of $cache + * + * @var Cache_Lite + * @access protected + */ + protected $cache; + + /** + * Description of $photoGallery + * + * @var Toolkit_Photos_Gallery + * @access protected + */ + protected $photoGallery; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param int $id ID + * @param Toolkit_Template_Image_Factory $imageFactory imageFactory + * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory breadCrumbsFactory + * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway Page Gateway + * @param Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway Paragraph Gateway + * @param Toolkit_Template_KeywordReplacement $keywordReplacement Keyword Replacement + * @param Cache_Lite $cache Cache + * @param Toolkit_Photos_Gallery $photoGallery Photo Gallery + * + * @throws RuntimeException + * @access public + */ + public function __construct( + $id, + Toolkit_Template_Image_Factory $imageFactory, + Toolkit_BreadCrumbsFactory $breadCrumbsFactory, + Toolkit_Toolbox_PageGatewayAbstract $pageGateway, + Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway, + Toolkit_Template_KeywordReplacement $keywordReplacement, + Cache_Lite $cache, + Toolkit_Photos_Gallery $photoGallery = null + ) { + if (!filter_var($id, FILTER_VALIDATE_INT)) { + throw new RuntimeException( + "`$id` is not a valid page id - integer required" + ); + } + $this->id = $id; + $this->imageFactory = $imageFactory; + $this->breadCrumbsFactory = $breadCrumbsFactory; + $this->pageGateway = $pageGateway; + $this->paragraphGateway = $paragraphGateway; + $this->keywordReplacement = $keywordReplacement; + $this->cache = $cache; + $this->photoGallery = $photoGallery; + } + + // }}} + + // {{{ getContent() + + /** + * Get content + * + * @return string + * @access public + */ + public function getContent() + { + $breadCrumbsBuilder = $this->breadCrumbsFactory->createBreadCrumbsHelper(); + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $secondaryParagraphs = $this->getSecondaryParagraphs($this->id); + $primaryParagraph = $this->getPrimaryParagraph($this->id); + $coupons = null; + if (defined('COUPONS') && COUPONS) { + $coupons = $this->_getPageCoupons($this->id); + } + $staticPageContent = $this->getStaticPageContent($this->id); + + $photoGalleryContent = null; + if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) { + $photoGalleryContent = $this->photoGallery->getPageGallery($this->id); + } + + return $breadCrumbs . + $primaryParagraph . + $staticPageContent . + $secondaryParagraphs . + $coupons . + $photoGalleryContent; + } + + // }}} + + // {{{ _getPageCoupons() + + /** + * Description for _getPageCoupons + * + * @param int $id ID + * + * @return string|void + * @access private + */ + private function _getPageCoupons($id) + { + $page = $this->pageGateway->find($id); + if (!$page['include_coupons']) { + return; + } + + $widget = new Toolkit_Coupons_PageWidget( + new Toolkit_Coupons_WebCouponFactory(), + new Toolkit_Coupons_Coupons() + ); + + $flexyOpts = Toolkit_Coupons_Controller::getFlexyOptions(); + $tEngine = new HTML_Template_Flexy($flexyOpts); + + $widget->addPageCategories( + Toolkit_Database::getInstance(), + $id + ); + + $searchForm = new Toolkit_Coupons_UserSearch( + 'coupon_search', + 'get', + BASE_URL . 'index.php' + ); + $searchForm->configureForm( + Toolkit_Database::getInstance(), + $id + ); + + $widget->setSearchForm($searchForm); + + $couponForm = new HTML_QuickForm( + 'coupon_form', + 'post', + BASE_URL . 'Toolkit/Coupons/print.php' + ); + $renderer =& $couponForm->defaultRenderer(); + $renderer->clearAllTemplates(); + return $widget->toHtml($couponForm, $tEngine, 'coupons.html'); + } + + // }}} + // {{{ getParagraphFiles() + + /** + * Description for getParagraphFiles() + * + * @param array $files Files array + * + * @return void|string + * @access protected + */ + protected function getParagraphFiles($files) + { + if (!is_array($files)) { + return; + } + + $filesList = ''; + foreach ($files as $file) { + $linkRenderer = Toolkit_Template_Page_FileLink_Factory::createLinkRenderer($file); + $filesList .= $linkRenderer->getLink(); + } + + return $filesList; + } + + // }}} + // {{{ getParagraphImage() + + /** + * Description for getParagraphImage() + * + * @param array $data Image data + * @param string $side Side image is on + * + * @return string Through Toolkit/Template/Image /Left or /Right or /Null + * @access protected + */ + protected function getParagraphImage(array $data, $side) + { + $imageBuilder = $this->imageFactory->getImageBuilder($data, $side); + return $imageBuilder->getImage(TOOLBOX_RESIZED); + } + + // }}} + // {{{ getParagraphLinks() + + /** + * Description for getParagraphLinks() + * + * @return boolean|string + * @access protected + */ + protected function getParagraphLinks() + { + if (!is_array($this->paragraphLinks)) { + return false; + } + + $links = ''; + + return $links; + } + + // }}} + // {{{ getPrimaryParagraph() + + /** + * Description for getPrimaryParagraph() + * + * @param int $id ID + * + * @return string + * @access protected + */ + protected function getPrimaryParagraph($id) + { + $cache = $this->cache->get("page-$id", 'Toolbox'); + + if ($cache) { + return $cache; + } else { + $page = $this->pageGateway->find($id); + + switch ($page['template']) { + case '2' : + case '4' : + case '5' : + $side = 'left'; + break; + + default : + $side = 'right'; + break; + } + + $html = '
    '; + $html .= "

    {$page['title']}

    "; + if ($page['paragraph_links']) { + $html .= $this->getParagraphLinks(); + } + $html .= $this->getParagraphImage($page, $side); + $html .= $this->keywordReplacement->findAndReplace($page['description']); + $html .= '
    '; + + $this->cache->save($html, "page-$id", 'Toolbox'); + } + + return $html; + } + + // }}} + // {{{ getSecondaryParagraphs() + + /** + * Description for getSecondaryParagraphs() + * + * @param int $id ID + * + * @return string + * @throws Toolkit_Template_Exception + * @access protected + */ + protected function getSecondaryParagraphs($id) + { + $cache = $this->cache->get("paragraphs-$id", 'Toolbox'); + + if ($cache) { + return $cache; + } else { + $page = $this->pageGateway->find($id); + $paragraphs = $this->paragraphGateway->findAll($id); + + $side = array('left', 'right'); + switch ($page['template']) { + case '2' : + case '3' : + case '6' : + $key = 0; + $flip = ($page['template'] == 3); + if ($page['templte'] == '3') { + $flip = true; + } + break; + + case '1' : + case '4' : + case '5' : + $key = 1; + $flip = ($page['template'] == 4); + break; + + default : + throw new Toolkit_Template_Exception( + "Invalid page template for page `$id`" + ); + break; + } + + $html = ''; + $linksFormat = '%s'; + foreach ($paragraphs as $paragraph) { + if ($paragraph['active']) { + $html .= '
    '; + $html .= "

    {$paragraph['title']}

    "; + $html .= $this->getParagraphImage($paragraph, $side[$key]); + $html .= $this->keywordReplacement->findAndReplace($paragraph['description']); + + $html .= $this->getParagraphFiles($paragraph['files']); + + if ($paragraph['back_to_top']) { + $html .= 'Back to Top'; + } + + $html .= '
    '; + + $this->paragraphLinks[] = sprintf( + $linksFormat, + $paragraph['id'], + $paragraph['title'] + ); + $key = $flip ? !$key : $key; + } + } + + $this->cache->save($html, "paragraphs-$id", 'Toolbox'); + return $html; + } + } + + // }}} + + // {{{ getStaticPageContent() + + /** + * Description for getStaticPageCOntent() + * + * @param unknown $pageId PageID + * + * @return string + * @access protected + */ + protected function getStaticPageContent($pageId) + { + $html = ''; + + if (file_exists(BASE . "static/$pageId.phtml")) { + ob_start(); + include BASE . "static/$pageId.phtml"; + $html = ob_get_contents(); + ob_end_clean(); + } + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Template/PageControllerAbstract.php b/Toolkit/Template/PageControllerAbstract.php new file mode 100644 index 0000000..dd06879 --- /dev/null +++ b/Toolkit/Template/PageControllerAbstract.php @@ -0,0 +1,115 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_PageControllerAbstract + * + * Description of Toolkit_Template_PageControllerAbstract + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_Template_PageControllerAbstract + extends Toolkit_BaseControllerAbstract implements Toolkit_IController +{ + /** + * Description for getPageGatewayFactory() + * + * @access protected + * @return unknown + */ + abstract protected function getPageGatewayFactory(); + + /** + * Description for getParagraphGatewayFactory() + * + * @access protected + * @return unknown + */ + abstract protected function getParagraphGatewayFactory(); + + /** + * Description for indexAction() + * + * @return void + * @access public + */ + public function indexAction() + { + // Initiate HTML_Template_Flexy. + $template = new HTML_Template_Flexy($this->registry->flexyOptions); + $keywordReplacement = new Toolkit_Template_KeywordReplacement( + new Toolkit_Toolbox_PageGatewayPublish( + $this->registry->dbh + ) + ); + $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory( + $this->getPageGatewayFactory() + ); + // Page object used for merging with the flexy template object. + // now using the page class from toolkit + $glmPage = new Toolkit_Page( + new Toolkit_Template_Page(), + $breadCrumbsFactory, + $this->getPageGatewayFactory(), + $this->getParagraphGatewayFactory(), + new Toolkit_Template_Navigation_Factory(), + $keywordReplacement, + $this->registry->catid + ); + $glmPage->fetchPage(); + /* + if (isset($_GET['member_id']) && is_numeric($_GET['member_id'])) { + // get member name and put in title + $sql = " + SELECT member_name + FROM member + WHERE member_id = {$_GET['member_id']}"; + if ($memData = $toolbox->DB->db_auto_get_data($sql)) { + $member_name = htmlentities(strip_tags($memData[0]['member_name'])); + $glmPage->title = $member_name.' - '.$glmPage->title; + } + } + + if ($catid == HOME_ID && !$_POST) { + $sql = " + SELECT * + FROM bus_category + WHERE featured = true"; + $dbh = Toolkit_Database::getInstance(); + foreach ($dbh->query($sql) as $row) { + $row['link'] = $toolbox->get_seo_url($row['id']); + $glmPage->features[] = $row; + } + } + $glmPage->hasHeadlines = !empty($glmPage->features); + */ + + $glmPage->topScripts = Toolkit_Common::getScripts($GLOBALS['topScripts']); + $glmPage->bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']); + $glmPage->styles = Toolkit_Common::getStyleSheets(); + + // Compile the template.html from the templates directory. + $template->compile('template.html'); + // Merge compiled template with the $glmPage object. + $template->outputObject($glmPage); + } +} +?> diff --git a/Toolkit/Toolbox/BreadCrumbsAbstract.php b/Toolkit/Toolbox/BreadCrumbsAbstract.php new file mode 100644 index 0000000..c32fb66 --- /dev/null +++ b/Toolkit/Toolbox/BreadCrumbsAbstract.php @@ -0,0 +1,119 @@ +dbh = $dbh; + + if (!ctype_digit((string)$id)) { + throw new InvalidArgumentException( + "\$id must be an integer `$id` given" + ); + } + + $this->id = $id; + } + + // }}} + // {{{ getPage() + + protected function getPage($id) + { + try { + $sql = " + SELECT * + FROM pages + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + return $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Could not fetch parent for page `$id`" + ); + } + } + + // }}} + // {{{ __toString() + + public function __toString() + { + return ''; + } + + // }}} + // {{{ getId() + + /** + * @return the $id + */ + public function getId() + { + return $this->id; + } + + // }}} + // {{{ getPageUri() + + abstract protected function getPageUri(array $page); + + // }}} + // {{{ getPath() + + /** + * @return the $path + */ + public function getPath() + { + if ($this->id == HOME_ID) { + return; + } + + $id = $this->id; + $stack = array(); + do { + $page = $this->getPage($id); + + $navigationName = $this->id == $id + ? $page['navigation_name'] + : $this->getPageUri($page); + + $stack[] = $navigationName; + $id = $page['parent']; + } while ($id != 0); + + $reverse = array_reverse($stack); + $this->path = implode(' > ', $reverse); + + return $this->path; + } + + // }}} + // {{{ setId() + + /** + * @param $id the $id to set + */ + public function setId($id) + { + $this->id = $id; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/Database/addIncludeCoupons.sql b/Toolkit/Toolbox/Database/addIncludeCoupons.sql new file mode 100644 index 0000000..7dbf908 --- /dev/null +++ b/Toolkit/Toolbox/Database/addIncludeCoupons.sql @@ -0,0 +1,19 @@ +-- +-- update the pages tables with new field for include_coupons +-- and update the rule for history +-- + +ALTER TABLE toolbox.pages ADD include_coupons BOOLEAN; +ALTER TABLE toolbox.pages ALTER include_coupons SET DEFAULT false; +UPDATE toolbox.pages SET include_coupons = false; + +ALTER TABLE toolbox.pages_draft ADD include_coupons BOOLEAN; +ALTER TABLE toolbox.pages_draft ALTER include_coupons SET DEFAULT false; +UPDATE toolbox.pages_draft SET include_coupons = false; + +ALTER TABLE toolbox.pages_history ADD include_coupons BOOLEAN; +ALTER TABLE toolbox.pages_history ALTER include_coupons SET DEFAULT false; +UPDATE toolbox.pages_history SET include_coupons = false; + + +\i ./procedures/pages_update.sql diff --git a/Toolkit/Toolbox/Database/addIncludeMembers.sql b/Toolkit/Toolbox/Database/addIncludeMembers.sql new file mode 100644 index 0000000..44fba29 --- /dev/null +++ b/Toolkit/Toolbox/Database/addIncludeMembers.sql @@ -0,0 +1,19 @@ +-- +-- update the pages tables with new field for include_members +-- and update the rule for history +-- + +ALTER TABLE toolbox.pages ADD include_members BOOLEAN; +ALTER TABLE toolbox.pages ALTER include_members SET DEFAULT false; +UPDATE toolbox.pages SET include_members = false; + +ALTER TABLE toolbox.pages_draft ADD include_members BOOLEAN; +ALTER TABLE toolbox.pages_draft ALTER include_members SET DEFAULT false; +UPDATE toolbox.pages_draft SET include_members = false; + +ALTER TABLE toolbox.pages_history ADD include_members BOOLEAN; +ALTER TABLE toolbox.pages_history ALTER include_members SET DEFAULT false; +UPDATE toolbox.pages_history SET include_member = false; + + +\i ./procedures/pages_update.sql diff --git a/Toolkit/Toolbox/Database/application.sql b/Toolkit/Toolbox/Database/application.sql new file mode 100644 index 0000000..02859ae --- /dev/null +++ b/Toolkit/Toolbox/Database/application.sql @@ -0,0 +1,33 @@ +CREATE SCHEMA toolbox; +GRANT ALL ON SCHEMA toolbox TO nobody; + +-- +-- Tables +-- +\i ./tables/pages.sql +\i ./tables/pages_history.sql +\i ./tables/pages_draft.sql +\i ./tables/paragraphs.sql +\i ./tables/paragraphs_history.sql +\i ./tables/paragraphs_draft.sql +\i ./tables/files.sql +\i ./tables/files_history.sql +\i ./tables/files_draft.sql + +-- +-- Procedures +-- +\i ./procedures/pages_update.sql +\i ./procedures/pages_pos.sql +\i ./procedures/paragraphs_update.sql +\i ./procedures/paragraphs_pos.sql +\i ./procedures/paragraphs_draft_pos.sql +\i ./procedures/check_paragraph_pos_consistency.sql +-- \i ./procedures/check_pages_pos_consistency.sql +\i ./procedures/files_update.sql +\i ./procedures/files_pos.sql +\i ./procedures/delete_subtree.sql + +-- +-- Modules +-- diff --git a/Toolkit/Toolbox/Database/data/applicationData.sql b/Toolkit/Toolbox/Database/data/applicationData.sql new file mode 100644 index 0000000..b3db82f --- /dev/null +++ b/Toolkit/Toolbox/Database/data/applicationData.sql @@ -0,0 +1,32 @@ +INSERT INTO toolbox.pages(active, template, keyword, navigation_name, paragraph_links) VALUES (TRUE, 1, 'home', 'Home', TRUE); +INSERT INTO toolbox.pages(active, template, parent, pos, navigation_name) VALUES(TRUE, 1, 0, 2, 'Parent'); +INSERT INTO toolbox.pages(active, template, parent, pos, navigation_name) VALUES(TRUE, 1, 2, 1, 'Child'); +INSERT INTO toolbox.pages(active, template, parent, pos, navigation_name) VALUES(TRUE, 1, 2, 2, 'Child Sibling'); +INSERT INTO toolbox.pages(active, template, parent, pos, navigation_name) VALUES(TRUE, 1, 3, 1, 'Grand Child'); +INSERT INTO toolbox.pages(active, template, parent, pos, navigation_name) VALUES(TRUE, 1, 3, 2, 'Grand Child Sibling'); +INSERT INTO toolbox.pages(active, template, parent, pos, navigation_name) VALUES(TRUE, 1, 0, 3, 'Sibling'); + +INSERT INTO toolbox.paragraphs(active, title, description, image, caption, page, pos) VALUES(TRUE, 'Lorem Ipsum Delor', '

    Dictumst quis adipiscing etiam odio et augue, ut, cum cras adipiscing dolor cursus eros in integer in enim, aliquet in, amet tempor porta scelerisque, a eros sociis nec, porta in, lacus lacus, integer phasellus vut sit? Massa turpis porttitor. In, enim pulvinar? Ac et, ac nascetur porttitor magnis natoque duis! Nisi, ac et, aliquet? Cras tempor dignissim! Adipiscing cursus vel, integer dis penatibus vut! Et? Nec lundium lacus nunc nunc tempor a pid cum turpis magnis urna est eu rhoncus porttitor mauris ridiculus eu! Dolor pid porta ac dis lorem phasellus, tincidunt eros montes auctor adipiscing? Sed adipiscing risus scelerisque scelerisque ridiculus tortor, ut aliquam. Aenean enim et. Lectus enim dapibus scelerisque eros elementum nec, sagittis arcu. Purus augue ac.

    +

    Enim tincidunt pid, augue est magna velit lacus in tincidunt cras sed tempor! Sed. Dis adipiscing odio, urna mus! Natoque arcu elit. Dapibus natoque a ridiculus scelerisque nisi cras. Phasellus ultricies natoque augue sagittis mauris adipiscing porta pulvinar integer! Lacus adipiscing sit porta ultricies mus natoque amet porta etiam, mauris. Egestas! Et urna! Platea risus magnis porta magnis in! Integer turpis cursus enim ac, ac? Phasellus enim. Cras enim! Lectus pulvinar, ac porta elementum nec, vut elementum pulvinar dignissim elementum porta placerat porttitor a lundium, turpis velit et mattis augue hac tempor adipiscing, magnis, lectus, pulvinar diam. Scelerisque scelerisque. Nunc sagittis ut proin, tincidunt ultrices velit parturient, sit vel enim. Porta? Ac non! Magna tincidunt arcu augue aenean eros.

    +

    Placerat et placerat massa aliquam aliquet scelerisque, urna lorem! Adipiscing rhoncus, pid natoque turpis, auctor. Placerat sit, non sed, mattis augue dis placerat amet elementum vel habitasse, placerat. Etiam cum magnis arcu nisi a proin mus sit tortor montes! Integer aliquam, pellentesque sed sit. Dis mattis magnis! Enim non tincidunt cursus urna urna magna etiam? Facilisis ultricies dapibus porttitor, turpis ac et placerat urna, urna turpis vel, porta purus ac non! Nunc lorem? Tincidunt quis sagittis ridiculus sit, turpis? A ut ac rhoncus. Aenean tristique a tincidunt. Ac in odio dis et nascetur, est proin. Nisi, aliquam elementum, sed. Nunc sociis. Ut enim, ultricies nascetur a magna porta duis ut tincidunt! Aenean, augue cursus tristique ridiculus, integer eros dolor.

    ', '', '', 1, 1); +INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Paragraph A', '

    Sit, et odio, risus proin adipiscing mattis! Est! Non lorem, et scelerisque sociis! Ac? Porttitor in, pid auctor, etiam hac sagittis dignissim scelerisque elementum? Nisi. Auctor in, lacus, enim vut, ac eros magna cursus nisi et! Vut tortor natoque rhoncus augue est tincidunt tortor in sed elementum, tristique purus. Nec nascetur porta adipiscing cum. Diam porttitor lorem hac parturient cras, pulvinar integer! Vel ac, rhoncus ridiculus ac magna est integer, ut ultrices! Pulvinar hac lundium pid pulvinar dapibus et rhoncus! Montes et pulvinar vut. Sit porta arcu turpis! Dictumst, proin pulvinar et turpis tristique odio aliquam, est odio hac dis? Elit elementum integer adipiscing turpis tincidunt massa? Habitasse dignissim lectus porta, nunc, aliquam est? Integer enim? Lectus, dignissim natoque, turpis.

    ', '', '', TRUE, 1, 1); +INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Paragraph B', '

    Tortor adipiscing ut magna cras elit elit elit, dis! Eros pid scelerisque, aenean sagittis odio tristique elementum sed sit, porta ridiculus! Eros lundium integer? Integer, pulvinar sociis mid! Enim, magna velit mattis et ultrices egestas sed egestas non pulvinar etiam! Urna porta et pulvinar lorem sed aliquam, ridiculus. Dolor aenean integer enim, amet porta enim penatibus, proin a ut tincidunt, turpis magnis lectus quis enim aliquet, mauris in vel quis! Facilisis dolor. Urna eu, amet quis, mattis sed! Phasellus lorem! Non platea. Sit elit sed proin mus, mauris mauris dignissim, tincidunt et augue placerat tristique elementum purus lundium a cursus platea pid, ultricies platea? Elit sed eu diam, elementum sit rhoncus massa, lorem hac, urna natoque sit a tincidunt vel.

    ', '', '', TRUE, 1, 1); +INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Paragraph C', '

    Porta, augue facilisis, arcu massa enim massa phasellus nisi elementum, aliquet sit phasellus sed nunc turpis, augue cum, cum lundium, ridiculus, vut sociis auctor! Tincidunt pulvinar, tempor eu mid amet? Odio, lacus ultrices, nunc purus, cursus in diam mattis et penatibus. Dolor. Elementum pid tincidunt magna penatibus risus, odio aliquet. Dapibus amet eros enim diam? Elit, urna elit porttitor platea. Nascetur proin odio habitasse aenean magnis? Facilisis nascetur? A elementum, lorem diam, phasellus phasellus montes magna proin? Habitasse risus, vel porta mauris tortor velit, egestas tortor augue. Vut sed placerat aliquet enim diam porttitor dignissim, montes, mattis enim! Egestas ultrices? Nec porta lundium dapibus! Dictumst turpis augue integer, proin nec lectus dictumst! Platea urna, rhoncus hac ac adipiscing a augue.

    ', '', '', TRUE, 1, 1); +INSERT INTO toolbox.paragraphs(active, title, description, image, caption, page, pos) VALUES(TRUE, 'Parent Title', '

    Dictumst quis adipiscing etiam odio et augue, ut, cum cras adipiscing dolor cursus eros in integer in enim, aliquet in, amet tempor porta scelerisque, a eros sociis nec, porta in, lacus lacus, integer phasellus vut sit? Massa turpis porttitor. In, enim pulvinar? Ac et, ac nascetur porttitor magnis natoque duis! Nisi, ac et, aliquet? Cras tempor dignissim! Adipiscing cursus vel, integer dis penatibus vut! Et? Nec lundium lacus nunc nunc tempor a pid cum turpis magnis urna est eu rhoncus porttitor mauris ridiculus eu! Dolor pid porta ac dis lorem phasellus, tincidunt eros montes auctor adipiscing? Sed adipiscing risus scelerisque scelerisque ridiculus tortor, ut aliquam. Aenean enim et. Lectus enim dapibus scelerisque eros elementum nec, sagittis arcu. Purus augue ac.

    ', '', '', 2, 1); +INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Parent Paragraph A', '

    Sit, et odio, risus proin adipiscing mattis! Est! Non lorem, et scelerisque sociis! Ac? Porttitor in, pid auctor, etiam hac sagittis dignissim scelerisque elementum? Nisi. Auctor in, lacus, enim vut, ac eros magna cursus nisi et! Vut tortor natoque rhoncus augue est tincidunt tortor in sed elementum, tristique purus. Nec nascetur porta adipiscing cum. Diam porttitor lorem hac parturient cras, pulvinar integer! Vel ac, rhoncus ridiculus ac magna est integer, ut ultrices! Pulvinar hac lundium pid pulvinar dapibus et rhoncus! Montes et pulvinar vut. Sit porta arcu turpis! Dictumst, proin pulvinar et turpis tristique odio aliquam, est odio hac dis? Elit elementum integer adipiscing turpis tincidunt massa? Habitasse dignissim lectus porta, nunc, aliquam est? Integer enim? Lectus, dignissim natoque, turpis.

    ', '', '', TRUE, 2, 1); +INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Parent Paragraph B', '

    Tortor adipiscing ut magna cras elit elit elit, dis! Eros pid scelerisque, aenean sagittis odio tristique elementum sed sit, porta ridiculus! Eros lundium integer? Integer, pulvinar sociis mid! Enim, magna velit mattis et ultrices egestas sed egestas non pulvinar etiam! Urna porta et pulvinar lorem sed aliquam, ridiculus. Dolor aenean integer enim, amet porta enim penatibus, proin a ut tincidunt, turpis magnis lectus quis enim aliquet, mauris in vel quis! Facilisis dolor. Urna eu, amet quis, mattis sed! Phasellus lorem! Non platea. Sit elit sed proin mus, mauris mauris dignissim, tincidunt et augue placerat tristique elementum purus lundium a cursus platea pid, ultricies platea? Elit sed eu diam, elementum sit rhoncus massa, lorem hac, urna natoque sit a tincidunt vel.

    ', '', '', TRUE, 2, 1); +INSERT INTO toolbox.paragraphs(active, title, description, page, pos) VALUES(TRUE, 'Child Title', 'Child Description', 3, 1); +INSERT INTO toolbox.paragraphs(active, title, description, page, pos) VALUES(TRUE, 'Sibling Title', 'Sibling Description', 7, 1); +INSERT INTO toolbox.paragraphs(active, title, page, pos) VALUES(TRUE, 'Sibling Paragraph A', 7, 1); +INSERT INTO toolbox.paragraphs(active, title, page, pos) VALUES(TRUE, 'Sibling Paragraph B', 7, 1); +INSERT INTO toolbox.paragraphs(active, title, page, pos) VALUES(TRUE, 'p Paragraph', 4, 1); +INSERT INTO toolbox.paragraphs(active, title, page, pos) VALUES(TRUE, 'p Paragraph', 5, 1); +INSERT INTO toolbox.paragraphs(active, title, page, pos) VALUES(TRUE, 'p Paragraph', 6, 1); + + +INSERT INTO members.city(state_id, city_name) VALUES (34, 'Cary'); +INSERT INTO members.city(state_id, city_name) VALUES (23, 'Petoskey'); + +INSERT INTO members.member(member_name, member_login, member_passwd, street, lat, lon, phone, process_email, url, city_id, state_id, zip, member_contact_email, mailing_address, primary_contact_fname, primary_contact_lname, active, mailing_city, mailing_state_id, mailing_zip, new_member) values('1111 AAA Test', 'uname', 'pword', '120 E. Lake St.', 45.374893, -84.958404, '(231) 487-0692', 'jamie@gaslightmedia.com', 'http://www.gaslightmedia.com', 3, 23, 49770, 'jamie@gaslightmedia.com', '139 Dove Cottage Ln.', 'Jamie', 'Kahgee', true, 'Cary', 34, 27519, false); + +INSERT INTO coupons.coupons(title, url, sdate, edate, expiration, category, active, member) VALUES ('Coupon Test', 'http://www.google.com', '2010-04-22', '2010-10-22', '2010-10-22', 'Accommodations', true, 1); diff --git a/Toolkit/Toolbox/Database/procedures/check_pages_pos_consistency.sql b/Toolkit/Toolbox/Database/procedures/check_pages_pos_consistency.sql new file mode 100644 index 0000000..085ff72 --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/check_pages_pos_consistency.sql @@ -0,0 +1,38 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS check_pages_pos_consistency ON toolbox.pages; + +-- +-- Function and trigger checking for duplicate positions when a paragraph +-- has been inserted or updated. +-- +-- This trigger only happens after an insert or update and is initially +-- deferred which allows us to wrap our movements in a transaction and +-- examine the results when we are done +-- +-- This is a final check to help ensure data integrity +-- +CREATE OR REPLACE FUNCTION toolbox.check_pages_pos_consistency() RETURNS TRIGGER AS $check_pages_pos_consistency$ + DECLARE + duplicates INTEGER; + BEGIN + + SELECT + INTO duplicates count(*) + FROM toolbox.pages + WHERE parent = NEW.parent + AND pos = NEW.pos; + + IF (duplicates > 1) THEN + RAISE EXCEPTION 'Duplicate page positions!'; + END IF; + + RETURN NULL; + END; +$check_pages_pos_consistency$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER trigger_pages_pos_check_consistency +AFTER INSERT OR UPDATE ON toolbox.pages + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE PROCEDURE toolbox.check_pages_pos_consistency(); diff --git a/Toolkit/Toolbox/Database/procedures/check_paragraph_pos_consistency.sql b/Toolkit/Toolbox/Database/procedures/check_paragraph_pos_consistency.sql new file mode 100644 index 0000000..a6b46ae --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/check_paragraph_pos_consistency.sql @@ -0,0 +1,38 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS check_paragraphs_pos_consistency ON toolbox.paragraphs; + +-- +-- Function and trigger checking for duplicate positions when a paragraph +-- has been inserted or updated. +-- +-- This trigger only happens after an insert or update and is initially +-- deferred which allows us to wrap our movements in a transaction and +-- examine the results when we are done +-- +-- This is a final check to help ensure data integrity +-- +CREATE OR REPLACE FUNCTION toolbox.check_paragraphs_pos_consistency() RETURNS TRIGGER AS $check_paragraphs_pos_consistency$ + DECLARE + duplicates INTEGER; + BEGIN + + SELECT + INTO duplicates count(*) + FROM toolbox.paragraphs + WHERE page = NEW.page + AND pos = NEW.pos; + + IF (duplicates > 1) THEN + RAISE EXCEPTION 'Duplicate page positions!'; + END IF; + + RETURN NULL; + END; +$check_paragraphs_pos_consistency$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER trigger_paragraphs_pos_check_consistency +AFTER INSERT OR UPDATE ON toolbox.paragraphs + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE PROCEDURE toolbox.check_paragraphs_pos_consistency(); diff --git a/Toolkit/Toolbox/Database/procedures/delete_subtree.sql b/Toolkit/Toolbox/Database/procedures/delete_subtree.sql new file mode 100644 index 0000000..55b1781 --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/delete_subtree.sql @@ -0,0 +1,67 @@ +DROP TABLE IF EXISTS WorkingTable; +CREATE LOCAL TEMPORARY TABLE WorkingTable +(id INTEGER NOT NULL) +ON COMMIT DELETE ROWS; + +CREATE OR REPLACE FUNCTION toolbox.delete_subtree (IN dead_guy INTEGER) RETURNS void AS $$ + DECLARE + old_pos INTEGER; -- current position of the target node + old_par INTEGER; -- current parent of the target node + BEGIN + -- defer consraint that forbids (parent = id) + SET CONSTRAINTS ALL DEFERRED; + + -- set the old_pos and old_par variable + SELECT pos + INTO old_pos + FROM toolbox.pages + WHERE id = dead_guy; + + SELECT parent + INTO old_par + FROM toolbox.pages + WHERE id = dead_guy; + + -- mark root of subtree and immediate subordinates + UPDATE toolbox.pages + SET id = CASE WHEN id = dead_guy + THEN -99999 ELSE id END, + parent = CASE WHEN parent = dead_guy + THEN -99999 ELSE parent END + WHERE dead_guy IN (id, parent); + + WHILE EXISTS -- mark leaf nodes + (SELECT * + FROM toolbox.pages + WHERE parent = -99999 + AND id > -99999) + LOOP -- get list of next level subordinates + + DELETE FROM WorkingTable; + INSERT INTO WorkingTable + SELECT id FROM toolbox.pages WHERE parent = -99999; + + -- delete old markers so we don't keep an infinite loop + DELETE FROM toolbox.pages + WHERE parent = -99999; + + -- mark next level of subordinates + UPDATE toolbox.pages + SET parent = -99999 + WHERE parent IN (SELECT id FROM WorkingTable); + + END LOOP; + + -- delete all marked nodes + DELETE FROM toolbox.pages + WHERE id = -99999; + + -- reset all the positions at the target nodes level + UPDATE toolbox.pages + SET pos = pos - 1 + WHERE parent = old_par + AND pos > old_pos; + + SET CONSTRAINTS ALL IMMEDIATE; + END; +$$ LANGUAGE plpgsql; diff --git a/Toolkit/Toolbox/Database/procedures/files_pos.sql b/Toolkit/Toolbox/Database/procedures/files_pos.sql new file mode 100644 index 0000000..d0a27a6 --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/files_pos.sql @@ -0,0 +1,28 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS files_pos ON toolbox.files; + +-- +-- Function and trigger setting a page pos when inserted +-- +CREATE OR REPLACE FUNCTION toolbox.files_pos() RETURNS TRIGGER AS $files_pos$ + DECLARE + new_pos INTEGER; + BEGIN + + SELECT + INTO new_pos COALESCE(MAX(pos) + 1, 1) + FROM toolbox.files + WHERE paragraph = NEW.paragraph; + + NEW.pos := new_pos; + + RETURN NEW; + + END; +$files_pos$ LANGUAGE plpgsql; + +CREATE TRIGGER files_pos +BEFORE INSERT ON toolbox.files + FOR EACH ROW EXECUTE PROCEDURE toolbox.files_pos(); diff --git a/Toolkit/Toolbox/Database/procedures/files_update.sql b/Toolkit/Toolbox/Database/procedures/files_update.sql new file mode 100644 index 0000000..d018224 --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/files_update.sql @@ -0,0 +1,20 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS files_update ON toolbox.files; + +-- +-- Function and trigger copying a file revision +-- everytime it is updated. +-- +CREATE OR REPLACE FUNCTION toolbox.files_update() RETURNS TRIGGER AS $files_update$ + BEGIN + + INSERT INTO toolbox.files_history SELECT NEW.*; + RETURN NEW; + END; +$files_update$ LANGUAGE plpgsql; + +CREATE TRIGGER files_update +AFTER INSERT OR UPDATE ON toolbox.files + FOR EACH ROW EXECUTE PROCEDURE toolbox.files_update(); diff --git a/Toolkit/Toolbox/Database/procedures/pages_pos.sql b/Toolkit/Toolbox/Database/procedures/pages_pos.sql new file mode 100644 index 0000000..9deffe1 --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/pages_pos.sql @@ -0,0 +1,28 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS pages_pos ON toolbox.pages; + +-- +-- Function and trigger setting a page pos when inserted +-- +CREATE OR REPLACE FUNCTION toolbox.pages_pos() RETURNS TRIGGER AS $pages_pos$ + DECLARE + new_pos INTEGER; + BEGIN + + SELECT + INTO new_pos COALESCE(MAX(pos) + 1, 1) + FROM toolbox.pages + WHERE parent = NEW.parent; + + NEW.pos := new_pos; + + RETURN NEW; + + END; +$pages_pos$ LANGUAGE plpgsql; + +CREATE TRIGGER pages_pos +BEFORE INSERT ON toolbox.pages + FOR EACH ROW EXECUTE PROCEDURE toolbox.pages_pos(); diff --git a/Toolkit/Toolbox/Database/procedures/pages_update.sql b/Toolkit/Toolbox/Database/procedures/pages_update.sql new file mode 100644 index 0000000..df5fba3 --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/pages_update.sql @@ -0,0 +1,30 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS pages_update ON toolbox.pages; + +-- +-- Function and trigger copying a page revision +-- everytime it is updated. +-- +CREATE OR REPLACE FUNCTION toolbox.pages_update() RETURNS TRIGGER AS $pages_update$ + BEGIN + + INSERT INTO toolbox.pages_history + (id,active,mobile_active,headline,headline_intro,include_member_map, + keyword,meta_description,meta_title,navigation_name, + paragraph_links,parent,pos,search_form,region,short_url, + template,include_members,include_coupons) + SELECT + NEW.id,NEW.active,NEW.mobile_active,NEW.headline,NEW.headline_intro,NEW.include_member_map, + NEW.keyword,NEW.meta_description,NEW.meta_title,NEW.navigation_name, + NEW.paragraph_links,NEW.parent,NEW.pos,NEW.search_form,NEW.region, + NEW.short_url,NEW.template,NEW.include_members,NEW.include_coupons; + RETURN NEW; + + END; +$pages_update$ LANGUAGE plpgsql; + +CREATE TRIGGER pages_update +AFTER INSERT OR UPDATE ON toolbox.pages + FOR EACH ROW EXECUTE PROCEDURE toolbox.pages_update(); diff --git a/Toolkit/Toolbox/Database/procedures/paragraphs_draft_pos.sql b/Toolkit/Toolbox/Database/procedures/paragraphs_draft_pos.sql new file mode 100644 index 0000000..3eb789d --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/paragraphs_draft_pos.sql @@ -0,0 +1,28 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS paragraphs_draft_pos ON toolbox.paragraphs_draft; + +-- +-- Function and trigger setting a page pos when inserted +-- +CREATE OR REPLACE FUNCTION toolbox.paragraphs_draft_pos() RETURNS TRIGGER AS $paragraphs_draft_pos$ + DECLARE + new_pos INTEGER; + BEGIN + + SELECT + INTO new_pos COALESCE(MAX(pos) + 1, 1) + FROM toolbox.paragraphs_draft + WHERE page = NEW.page; + + NEW.pos := new_pos; + + RETURN NEW; + + END; +$paragraphs_draft_pos$ LANGUAGE plpgsql; + +CREATE TRIGGER paragraphs_draft_pos +BEFORE INSERT ON toolbox.paragraphs_draft + FOR EACH ROW EXECUTE PROCEDURE toolbox.paragraphs_draft_pos(); diff --git a/Toolkit/Toolbox/Database/procedures/paragraphs_pos.sql b/Toolkit/Toolbox/Database/procedures/paragraphs_pos.sql new file mode 100644 index 0000000..9bfe0ee --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/paragraphs_pos.sql @@ -0,0 +1,48 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS paragraphs_pos ON toolbox.paragraphs; + +-- +-- Function and trigger setting a page pos when inserted +-- +CREATE OR REPLACE FUNCTION toolbox.paragraphs_pos() RETURNS TRIGGER AS $paragraphs_pos$ + DECLARE + new_pos INTEGER; + BEGIN + + SELECT + INTO new_pos COALESCE(MAX(pos) + 1, 1) + FROM toolbox.paragraphs + WHERE page = NEW.page; + + -- Always use the new position when doing an insert + IF (TG_OP = 'INSERT') THEN + NEW.pos := new_pos; + ELSIF (TG_OP = 'UPDATE') THEN + -- Only update the paragraph position + -- on an update if we are changing the + -- page the paragraph is assigned to + IF (OLD.page != NEW.page) THEN + NEW.pos := new_pos; + + -- update the old page paragraph positions so + -- we aren't left with any gaps in the sequence + UPDATE toolbox.paragraphs + SET pos = pos - 1 + WHERE pos > OLD.pos + AND page = OLD.page + AND EXISTS (SELECT * -- ensure the old page still exists + FROM toolbox.pages + WHERE id = OLD.page); + END IF; + END IF; + + RETURN NEW; + + END; +$paragraphs_pos$ LANGUAGE plpgsql; + +CREATE TRIGGER paragraphs_pos +BEFORE INSERT OR UPDATE ON toolbox.paragraphs + FOR EACH ROW EXECUTE PROCEDURE toolbox.paragraphs_pos(); diff --git a/Toolkit/Toolbox/Database/procedures/paragraphs_update.sql b/Toolkit/Toolbox/Database/procedures/paragraphs_update.sql new file mode 100644 index 0000000..dd553bc --- /dev/null +++ b/Toolkit/Toolbox/Database/procedures/paragraphs_update.sql @@ -0,0 +1,21 @@ +--DROP LANGUAGE IF EXISTS plpgsql RESTRICT; +CREATE LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS paragraphs_update ON toolbox.paragraphs; + +-- +-- Function and trigger copying a paragraph revision +-- everytime it is updated. +-- +CREATE OR REPLACE FUNCTION toolbox.paragraphs_update() RETURNS TRIGGER AS $paragraphs_update$ + BEGIN + + INSERT INTO toolbox.paragraphs_history SELECT NEW.*; + RETURN NEW; + + END; +$paragraphs_update$ LANGUAGE plpgsql; + +CREATE TRIGGER paragraphs_update +AFTER INSERT OR UPDATE ON toolbox.paragraphs + FOR EACH ROW EXECUTE PROCEDURE toolbox.paragraphs_update(); diff --git a/Toolkit/Toolbox/Database/removeApplication.sql b/Toolkit/Toolbox/Database/removeApplication.sql new file mode 100644 index 0000000..1a393a9 --- /dev/null +++ b/Toolkit/Toolbox/Database/removeApplication.sql @@ -0,0 +1,8 @@ +-- +-- This will drop everything in the toolbox schema. +-- Nothing better be in here except toolbox related objects +-- or it will be dropped +-- +-- The force is strong w/ this one, use it wisely. +-- +DROP SCHEMA IF EXISTS toolbox CASCADE; diff --git a/Toolkit/Toolbox/Database/tables/files.sql b/Toolkit/Toolbox/Database/tables/files.sql new file mode 100644 index 0000000..b6490d2 --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/files.sql @@ -0,0 +1,17 @@ +DROP TABLE IF EXISTS toolbox.files CASCADE; + +CREATE TABLE toolbox.files +(id SERIAL, + filename TEXT, + bytes INTEGER NOT NULL DEFAULT 0, + "type" TEXT NOT NULL, + urltext TEXT, + paragraph INTEGER NOT NULL + REFERENCES toolbox.paragraphs(id) + ON UPDATE CASCADE + ON DELETE CASCADE, + pos INTEGER NOT NULL DEFAULT 1, + PRIMARY KEY (id)); + +GRANT ALL ON toolbox.files_id_seq TO nobody; +GRANT ALL ON toolbox.files TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/files_draft.sql b/Toolkit/Toolbox/Database/tables/files_draft.sql new file mode 100644 index 0000000..8e9c7a1 --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/files_draft.sql @@ -0,0 +1,12 @@ +DROP TABLE IF EXISTS toolbox.files_draft CASCADE; + +CREATE TABLE toolbox.files_draft +(LIKE toolbox.files + INCLUDING DEFAULTS, + FOREIGN KEY (paragraph) REFERENCES toolbox.paragraphs_draft(id) + ON UPDATE CASCADE + ON DELETE CASCADE, + PRIMARY KEY (id) +); + +GRANT ALL ON toolbox.files_draft TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/files_history.sql b/Toolkit/Toolbox/Database/tables/files_history.sql new file mode 100644 index 0000000..47b1665 --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/files_history.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS toolbox.files_history CASCADE; + +CREATE TABLE toolbox.files_history +(LIKE toolbox.files + INCLUDING DEFAULTS, + revision SERIAL NOT NULL +); + +GRANT ALL ON toolbox.files_history_revision_seq TO nobody; +GRANT ALL ON toolbox.files_history TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/pages.sql b/Toolkit/Toolbox/Database/tables/pages.sql new file mode 100644 index 0000000..551f06d --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/pages.sql @@ -0,0 +1,36 @@ +DROP TABLE IF EXISTS toolbox.pages CASCADE; + +CREATE TABLE toolbox.pages +(id SERIAL, + active BOOLEAN NOT NULL + DEFAULT FALSE, + mobile_active BOOLEAN NOT NULL + DEFAULT FALSE, + headline BOOLEAN NOT NULL + DEFAULT FALSE, + headline_intro TEXT, + include_member_map BOOLEAN NOT NULL + DEFAULT FALSE, + keyword TEXT, + meta_description TEXT, + meta_title TEXT, + navigation_name TEXT, + paragraph_links BOOLEAN NOT NULL + DEFAULT FALSE, + parent INTEGER NOT NULL -- 0 is top level + DEFAULT 0, + pos INTEGER NOT NULL + DEFAULT 1, + search_form BOOLEAN NOT NULL + DEFAULT FALSE, + region INTEGER, + short_url TEXT, + template INTEGER NOT NULL, + include_members BOOLEAN DEFAULT FALSE, + include_coupons BOOLEAN DEFAULT FALSE, + PRIMARY KEY (id), + CHECK (id <> parent), -- Page cannot be own parent, + CHECK (pos > 0)); -- Page position cannot fall below zero + +GRANT ALL ON toolbox.pages_id_seq TO nobody; +GRANT ALL ON toolbox.pages TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/pages_draft.sql b/Toolkit/Toolbox/Database/tables/pages_draft.sql new file mode 100644 index 0000000..070b744 --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/pages_draft.sql @@ -0,0 +1,14 @@ +DROP TABLE IF EXISTS toolbox.pages_draft CASCADE; + +CREATE TABLE toolbox.pages_draft +(LIKE toolbox.pages + INCLUDING DEFAULTS, + published_page INTEGER + DEFAULT NULL + REFERENCES toolbox.pages (id) + ON UPDATE CASCADE + ON DELETE CASCADE, + PRIMARY KEY (id) +); + +GRANT ALL ON toolbox.pages_draft TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/pages_history.sql b/Toolkit/Toolbox/Database/tables/pages_history.sql new file mode 100644 index 0000000..e1d84d1 --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/pages_history.sql @@ -0,0 +1,12 @@ +DROP TABLE IF EXISTS toolbox.pages_history CASCADE; + +CREATE TABLE toolbox.pages_history +(LIKE toolbox.pages + INCLUDING DEFAULTS, + revision_timestamp TIMESTAMP NOT NULL + DEFAULT CURRENT_TIMESTAMP, + revision SERIAL NOT NULL +); + +GRANT ALL ON toolbox.pages_history_revision_seq TO nobody; +GRANT ALL ON toolbox.pages_history TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/pages_mobile.sql b/Toolkit/Toolbox/Database/tables/pages_mobile.sql new file mode 100644 index 0000000..e6d816f --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/pages_mobile.sql @@ -0,0 +1,15 @@ +DROP TABLE IF EXISTS toolbox.pages_mobile CASCADE; + +CREATE TABLE toolbox.pages_mobile +(id SERIAL, + page INTEGER NOT NULL + REFERENCES toolbox.pages(id) + ON DELETE CASCADE, + mobile_active BOOLEAN NET NULL + DEFAULT FALSE, +PRIMARY KEY (id)); + +GRANT ALL ON toolbox.pages_mobile TO nobody; +GRANT ALL ON toolbox.pages_mobile_id_seq TO nobody; + +CREATE UNIQUE INDEX page_mobile_page_indx ON toolbox.pages_mobile(page); diff --git a/Toolkit/Toolbox/Database/tables/pages_preview.sql b/Toolkit/Toolbox/Database/tables/pages_preview.sql new file mode 100644 index 0000000..3f4e5ae --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/pages_preview.sql @@ -0,0 +1,7 @@ +CREATE TEMPORARY TABLE toolbox.pages_preview +(LIKE toolbox.pages + INCLUDING DEFAULTS, + PRIMARY KEY (id) +); + +GRANT ALL ON toolbox.pages_preview TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/paragraphs.sql b/Toolkit/Toolbox/Database/tables/paragraphs.sql new file mode 100644 index 0000000..26aa4ee --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/paragraphs.sql @@ -0,0 +1,23 @@ +DROP TABLE IF EXISTS toolbox.paragraphs CASCADE; + +CREATE TABLE toolbox.paragraphs +(id SERIAL, + active BOOLEAN NOT NULL + DEFAULT TRUE, + back_to_top BOOLEAN NOT NULL + DEFAULT FALSE, + caption TEXT, + description TEXT, + image TEXT, + page INTEGER NOT NULL + REFERENCES toolbox.pages (id) + ON UPDATE CASCADE + ON DELETE CASCADE, + pos INTEGER NOT NULL + DEFAULT 1, + title TEXT, + PRIMARY KEY (id), + CHECK (pos > 0)); -- paragraph position cannot fall below zero + +GRANT ALL ON toolbox.paragraphs_id_seq TO nobody; +GRANT ALL ON toolbox.paragraphs TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/paragraphs_draft.sql b/Toolkit/Toolbox/Database/tables/paragraphs_draft.sql new file mode 100644 index 0000000..85c3e33 --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/paragraphs_draft.sql @@ -0,0 +1,12 @@ +DROP TABLE IF EXISTS toolbox.paragraphs_draft CASCADE; + +CREATE TABLE toolbox.paragraphs_draft +(LIKE toolbox.paragraphs + INCLUDING DEFAULTS, + FOREIGN KEY (page) REFERENCES toolbox.pages_draft(id) + ON UPDATE CASCADE + ON DELETE CASCADE, + PRIMARY KEY (id) +); + +GRANT ALL ON toolbox.paragraphs_draft TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/paragraphs_history.sql b/Toolkit/Toolbox/Database/tables/paragraphs_history.sql new file mode 100644 index 0000000..6515b02 --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/paragraphs_history.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS toolbox.paragraphs_history CASCADE; + +CREATE TABLE toolbox.paragraphs_history +(LIKE toolbox.paragraphs + INCLUDING DEFAULTS, + revision SERIAL NOT NULL +); + +GRANT ALL ON toolbox.paragraphs_history_revision_seq TO nobody; +GRANT ALL ON toolbox.paragraphs_history TO nobody; diff --git a/Toolkit/Toolbox/Database/tables/paragraphs_preview.sql b/Toolkit/Toolbox/Database/tables/paragraphs_preview.sql new file mode 100644 index 0000000..b669e3f --- /dev/null +++ b/Toolkit/Toolbox/Database/tables/paragraphs_preview.sql @@ -0,0 +1,6 @@ +CREATE TEMPORARY TABLE toolbox.paragraphs_preview +(LIKE toolbox.paragraphs + INCLUDING DEFAULTS +); + +GRANT ALL ON toolbox.paragraphs_preview TO nobody; diff --git a/Toolkit/Toolbox/DraftPagesTree.php b/Toolkit/Toolbox/DraftPagesTree.php new file mode 100644 index 0000000..3b02d27 --- /dev/null +++ b/Toolkit/Toolbox/DraftPagesTree.php @@ -0,0 +1,42 @@ +rootNodeStart : $this->subTreeStart; + + if (is_array($leaf) && !empty($leaf)) { + foreach ($tree as $parent => $children) { + foreach ($children as $branch) { + $html .= sprintf($this->leafStart, $branch['id'], null); + $previewUrl = BASE_URL . "index.php?rt=Draft&catid={$branch['id']}"; + + $html .= "{$branch['navigation_name']}"; + + $html .= '
    '; + + $html .= '[Edit] '; + $html .= '[Paragraphs] '; + $html .= '[Preview] '; + $html .= $this->getActiveBall($branch); + + $html .= '
    '; + + $html .= $this->leafEnd; + } + } + } + + $html .= $this->treeEnd; + if ($level) { + $html .= $this->leafEnd; + } + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/EditDraftController.php b/Toolkit/Toolbox/EditDraftController.php new file mode 100644 index 0000000..711c301 --- /dev/null +++ b/Toolkit/Toolbox/EditDraftController.php @@ -0,0 +1,200 @@ +registry->dbh); + $gateway->delete($id); + } + + // }}} + + // {{{ indexAction() + + public function indexAction() + { + if (ctype_digit($_GET['id'])) { + $breadCrumbs = new Toolkit_Toolbox_PageDraftBreadCrumbs( + $this->registry->dbh, + $_GET['id'] + ); + $html = (string) $breadCrumbs; + } + + $form = $this->getForm( + 'EditDraft', + new Toolkit_Toolbox_PageGatewayDraftFactory($this->registry->dbh) + ); + $html .= $form->toHtml($this->registry->dbh); + + return $html; + } + + // }}} + + protected function preview($form) + { + die('preview'); + } + + // {{{ processAction() + + public function processAction() + { + return $this->processForm( + 'EditDraft', + new Toolkit_Toolbox_PageGatewayDraftFactory($this->registry->dbh), + new Cache_Lite($GLOBALS['cacheOptions']) + ); + } + + // }}} + // {{{ publishPage() + + protected function publishPage(HTML_QuickForm $form, Cache_Lite $cache) + { + $pageGatewayDraft = new Toolkit_Toolbox_PageGatewayDraft( + $this->registry->dbh + ); + $pageGatewayPublish = new Toolkit_Toolbox_PageGatewayPublish( + $this->registry->dbh + ); + $paragraphGatewayDraft = new Toolkit_Toolbox_ParagraphGatewayDraft( + $this->registry->dbh + ); + $paragraphGatewayPublish = new Toolkit_Toolbox_ParagraphGatewayPublish( + $this->registry->dbh + ); + + if ($form->validate()) { + $draftPageId = $form->getSubmitValue('id'); + $existingDraft = $pageGatewayDraft->find($draftPageId); + if (is_null($existingDraft['published_page'])) { + $publishId = $pageGatewayPublish->insert( + $form->getSubmitValues() + ); + + $paragraphs = $paragraphGatewayDraft->findAll( + $form->getSubmitValue('id') + ); + + $this->_convertOldFilesToUploadedFiles( + $paragraphGatewayPublish, + $paragraphs, + $publishId + ); + } else { + $pageGatewayPublish->update( + $form->getSubmitValues(), + $existingDraft['published_page'] + ); + + $existingParagraphs = $paragraphGatewayPublish->findAll( + $existingDraft['published_page'] + ); + + foreach ($existingParagraphs as $paragraph) { + $paragraphGatewayPublish->delete($paragraph['id']); + } + + $updatedParagraphs = $paragraphGatewayDraft->findAll( + $form->getSubmitValue('id') + ); + + $this->_convertOldFilesToUploadedFiles( + $paragraphGatewayPublish, + $updatedParagraphs, + $existingDraft['published_page'] + ); + } + + $pageGatewayDraft->delete($draftPageId); + $cache->clean('Nav'); + if ($existingDraft['published_page']) { + $cache->remove("page-{$existingDraft['published_page']}", 'Toolbox'); + $cache->remove("paragraphs-{$existingDraft['published_page']}", 'Toolbox'); + $cache->remove("sectionLinks-{$existingDraft['published_page']}", 'Toolbox'); + } + + header('Location: ' . BASE_URL . 'admin/toolbox.php'); + exit(); + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml(); + + return $return; + } + } + + // }}} + + // {{{ _convertOldFilesToUploadedFiles() + + private function _convertOldFilesToUploadedFiles( + Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway, + &$paragraphs, + $newPageId + ) { + if (is_array($paragraphs)) { + foreach ($paragraphs as &$paragraph) { + if (is_array($paragraph['files'])) { + $paragraph['uploaded_files'] = array( + 'urltext' => array(), + 'filename' => array(), + 'bytes' => array(), + 'type' => array() + ); + foreach ($paragraph['files'] as $file) { + $paragraph['uploaded_files']['urltext'][] = $file['urltext']; + $paragraph['uploaded_files']['filename'][] = $file['filename']; + $paragraph['uploaded_files']['bytes'][] = $file['bytes']; + $paragraph['uploaded_files']['type'][] = $file['type']; + } + } + $paragraph['page'] = $newPageId; + $paragraphGateway->insert($paragraph); + } + } + } + + // }}} + + // {{{ saveDraft() + + protected function saveDraft(HTML_QuickForm $form) + { + $gateway = new Toolkit_Toolbox_PageGatewayDraft($this->registry->dbh); + if ($form->validate()) { + $pageId = $form->getSubmitValue('id'); + if ($pageId) { + $gateway->update($form->getSubmitValues(), $pageId); + } else { + $gateway->insert($form->getSubmitValues()); + } + header('Location: ' . BASE_URL . 'admin/toolbox.php'); + exit(); + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml(); + + return $return; + } + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/EditPageController.php b/Toolkit/Toolbox/EditPageController.php new file mode 100644 index 0000000..65d53a5 --- /dev/null +++ b/Toolkit/Toolbox/EditPageController.php @@ -0,0 +1,148 @@ +registry->dbh); + $gateway->delete($id); + } + + // }}} + + // {{{ indexAction() + + public function indexAction() + { + if ($pageId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $breadCrumbs = new Toolkit_Toolbox_PageBreadCrumbs( + $this->registry->dbh, + $pageId + ); + $html = (string) $breadCrumbs; + } + + $form = $this->getForm( + 'EditPage', + new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh) + ); + $html .= $form->toHtml($this->registry->dbh); + + return $html; + } + + // }}} + + // {{{ processAction() + + public function processAction() + { + return $this->processForm( + 'EditPage', + new Toolkit_Toolbox_PageGatewayPublishFactory($this->registry->dbh), + new Cache_Lite($GLOBALS['cacheOptions']) + ); + } + + // }}} + // {{{ publishPage() + + protected function publishPage(HTML_QuickForm $form, Cache_Lite $cache) + { + $gateway = new Toolkit_Toolbox_PageGatewayPublish($this->registry->dbh); + if ($form->validate()) { + $pageId = $form->getSubmitValue('id'); + if ($pageId) { + $gateway->update($form->getSubmitValues(), $pageId); + } else { + $gateway->insert($form->getSubmitValues()); + } + + $cache->clean('Nav'); + $cache->remove("page-$pageId", 'Toolbox'); + $cache->remove("paragraphs-$pageId", 'Toolbox'); + $cache->remove("sectionLinks-$pageId", 'Toolbox'); + + header('Location: ' . BASE_URL . 'admin/toolbox.php'); + exit(); + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml(); + + return $return; + } + } + + // }}} + + // {{{ saveDraft() + + protected function saveDraft(HTML_QuickForm $form) + { + $pageGatewayDraft = new Toolkit_Toolbox_PageGatewayDraft( + $this->registry->dbh + ); + $paragraphGatewayPublish = new Toolkit_Toolbox_ParagraphGatewayPublish( + $this->registry->dbh + ); + $paragraphGatewayDraft = new Toolkit_Toolbox_ParagraphGatewayDraft( + $this->registry->dbh + ); + + if ($form->validate()) { + $draftId = $pageGatewayDraft->insert($form->getSubmitValues()); + + // drafting an already published page, + // need to bring over the paragraphs + if (ctype_digit($form->getSubmitValue('id'))) { + $paragraphs = $paragraphGatewayPublish->findAll( + $form->getSubmitValue('id') + ); + + if (is_array($paragraphs)) { + foreach ($paragraphs as &$paragraph) { + if (is_array($paragraph['files'])) { + $paragraph['uploaded_files'] = array( + 'urltext' => array(), + 'filename' => array(), + 'bytes' => array(), + 'type' => array() + ); + foreach ($paragraph['files'] as $file) { + $paragraph['uploaded_files']['urltext'][] = $file['urltext']; + $paragraph['uploaded_files']['filename'][] = $file['filename']; + $paragraph['uploaded_files']['bytes'][] = $file['bytes']; + $paragraph['uploaded_files']['type'][] = $file['type']; + } + } + $paragraph['page'] = $draftId; + $paragraphGatewayDraft->insert($paragraph); + } + } + } + + header('Location: ' . BASE_URL . 'admin/toolbox.php?rt=ListDrafts'); + exit(); + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml(); + + return $return; + } + } + + // }}} +} diff --git a/Toolkit/Toolbox/Exception.php b/Toolkit/Toolbox/Exception.php new file mode 100644 index 0000000..4e925dd --- /dev/null +++ b/Toolkit/Toolbox/Exception.php @@ -0,0 +1,3 @@ + diff --git a/Toolkit/Toolbox/FileExtension.php b/Toolkit/Toolbox/FileExtension.php new file mode 100644 index 0000000..93f8925 --- /dev/null +++ b/Toolkit/Toolbox/FileExtension.php @@ -0,0 +1,133 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Toolkit_Toolbox_FileExtension + * + * Description for Toolkit_Toolbox_FileExtension + * + * @category Toolkit + * @package Toolbox + * @author Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +class Toolkit_Toolbox_FileExtension +{ + // {{{ getImage() + + /** + * Description for getImage() + * + * @param string $filename File name + * + * @return string + * @access public + */ + public function getImage($filename) + { + switch (pathinfo($filename, PATHINFO_EXTENSION)) { + case 'avi' : + $img = 'avi.gif'; + break; + + case 'mp3' : + $img = 'mp3.gif'; + break; + + case 'pdf' : + $img = 'pdf.png'; + break; + + case 'xls' : + case 'xlsx' : + $img = 'xls.gif'; + break; + + case 'ppt' : + $img = 'ppt.gif'; + break; + + case 'mov' : + $img = 'mov.gif'; + break; + + case 'cad' : + $img = 'cad.gif'; + break; + + case 'html' : + $img = 'html.gif'; + break; + + case 'doc' : + case 'docx' : + case 'msword' : + $img = 'doc.gif'; + break; + + case 'txt' : + $img = 'txt.png'; + break; + + case 'zip' : + $img = 'zip.png'; + break; + + case 'rar' : + $img = 'rar.gif'; + break; + + case 'png' : // image does not exist yet. + case 'jpeg' : + case 'jpg' : + $img = 'jpg.gif'; + break; + + case 'gif' : + $img = 'gif.gif'; + break; + + case 'wmv' : + $img = 'wmv.gif'; + break; + + default : + $img = 'download.gif'; + break; + } + + return $img; + } + + // }}} + // {{{ getClassForType() + + /** + * Description for getClassForType() + * + * @param string $filename File name + * + * @return string + * @access public + */ + public function getClassForType($filename) + { + $image = $this->getImage($filename); + $pieces = explode('.', $image); + reset($pieces); + return current($pieces); + } + + // }}} +} diff --git a/Toolkit/Toolbox/FormControllerAbstract.php b/Toolkit/Toolbox/FormControllerAbstract.php new file mode 100644 index 0000000..864ebaf --- /dev/null +++ b/Toolkit/Toolbox/FormControllerAbstract.php @@ -0,0 +1,118 @@ +parseConfig( + BASE . 'Toolkit/Members/config.ini', + 'IniFile' + ); + } + + if (defined('COUPONS') && COUPONS) { + $cpnConf = new Config; + $cpnRoot =& $cpnConf->parseConfig( + BASE . 'Toolkit/Coupons/config.ini', + 'IniFile' + ); + } + $tlbConf = new Config; + $tbxRoot =& $tlbConf->parseConfig( + BASE . 'Toolkit/Toolbox/config.ini', + 'IniFile' + ); + + $form = new Toolkit_Toolbox_Forms_EditPage( + 'edit_page', + 'post', + BASE_URL . "admin/toolbox.php?rt=$controller&ac=process" + ); + + $form->configureForm( + $this->registry->dbh, + $factory, + new Toolkit_FileServer_ImageAdapter(), + $memRoot, + $cpnRoot + ); + + return $form; + } + + // }}} + + // {{{ savePage() + + protected function savePage( + Toolkit_Toolbox_PageGatewayAbstract $gateway, + HTML_QuickForm $form + ) { + if ($form->validate()) { + $pageId = $form->getSubmitValue('id'); + if ($pageId) { + $gateway->update($form->getSubmitValues(), $pageId); + } else { + $gateway->insert($form->getSubmitValues()); + } + header('Location: ' . BASE_URL . 'admin/toolbox.php'); + exit(); + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml(); + + return $return; + } + } + + // }}} + + // {{{ processForm() + + protected function processForm( + $controller, + Toolkit_Toolbox_GatewayFactoryAbstract $factory, + Cache_Lite $cache + ) { + $form = $this->getForm($controller, $factory); + + if ($form->isSubmitted()) { + if ($form->getSubmitValue('cancel')) { + // do nothing + $this->cancel(); + } elseif ($form->getSubmitValue('previewPage')) { + $this->preview(); + } elseif ($form->getSubmitValue('saveDraft')) { + // save draft + $return = $this->saveDraft($form); + } elseif ($form->getSubmitValue('publishPage')) { + // publish page + $return = $this->publishPage($form, $cache); + } elseif ($form->getSubmitValue('deletePage')) { + // delete page + $this->delete($form->getSubmitValue('id')); + $navTitle = $form->getSubmitValue('navigation_name'); + $return = "[$navTitle] successfully deleted."; + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml(); + } + } else { + $return = $form->toHtml(); + } + + return $return; + } + + // }}} +} diff --git a/Toolkit/Toolbox/Forms/EditPage.php b/Toolkit/Toolbox/Forms/EditPage.php new file mode 100644 index 0000000..11917fc --- /dev/null +++ b/Toolkit/Toolbox/Forms/EditPage.php @@ -0,0 +1,1157 @@ + + * @release CVS: $Id: EditPage.php,v 1.10 2010/08/15 19:29:57 jamie Exp $: + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ + +require_once BASE . 'Toolkit/Forms/Rules/Image.php'; +require_once BASE . 'Toolkit/Forms/Rules/ShortUrl.php'; + +/** + * Edit Toolbox page + * + * Handles form to insert/edit a toolbox page + * + * @category Toolbox + * @package Toolkit_Toolbox + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Toolbox_Forms_EditPage + extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * How many levels deep do you want to show in the parent select list + * + * 0 = Show All Levels + * + * @var integer + * @access protected + */ + protected $maxDepth = 0; + + /** + * Don't need to register any rules for this form. + * @var array + * @access protected + */ + protected $registeredRules = array(); + + // }}} + + // {{{ configureConstants() + + /** + * Configure form constants + * + * @param PDO $dbh Database handler + * + * @return void + * @access public + */ + public function configureConstants(PDO $dbh) + { + $c = array( + 'id' => $_GET['id'] + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @param Toolkit_Toolbox_GatewayFactoryAbstract $factory Gateway factory + * @param integer $id page id (optional) + * + * @return void + * @access public + */ + public function configureDefaults( + Toolkit_Toolbox_GatewayFactoryAbstract $factory, + $id = null + ) { + if (!is_null($id)) { + $gateway = $factory->createGateway(); + $page = $gateway->find($id); + } else { + $page = array( + 'template' => 1, + 'current_image_thumb' => 'Image not yet uploaded', + 'search_form' => 1 + ); + } + $this->setupDefaults($page); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @param PDO $dbh Database handler + * @param Config_Container $memRoot Configuration object + * @param Config_Container $cpnRoot Configuration object + * + * @return void + * @access public + */ + public function configureElements( + PDO $dbh, + Config_Container $memRoot = null, + Config_Container $cpnRoot = null, + $id = null + ) { + $e = array(); + + if (!is_null($memRoot)) { + $pluralMem = $memRoot->getItem('section', 'listing type') + ->getItem('directive', 'plural') + ->getContent(); + $singularMem = $memRoot->getItem('section', 'listing type') + ->getItem('directive', 'singular') + ->getContent(); + $hasRegions = $memRoot->getItem('section', 'conf') + ->getItem('directive', 'regions') + ->getContent(); + } + + if (!is_null($cpnRoot)) { + $pluralCpn = $cpnRoot->getItem('section', 'listing type') + ->getItem('directive', 'plural') + ->getContent(); + $singularCpn = $cpnRoot->getItem('section', 'listing type') + ->getItem('directive', 'singular') + ->getContent(); + } + + $hideDelete = (!is_null($id) && $id == HOME_ID); + $dir = dir(BASE . 'static'); + $staticPages = array(); + while (false !== ($page = $dir->read())) { + $pieces = explode('.', $page); + if ($pageId = filter_var($pieces[0], FILTER_VALIDATE_INT)) { + $staticPages[] = $pageId; + } + } + $hideDelete = ($hideDelete || in_array($id, $staticPages) || is_null($id)); + + $showParentPage = ($id != HOME_ID); + + // Grouped Elements are defined here. + $submitBtns = array(); + + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'publishPage', + 'display' => 'Publish Page' + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'saveDraft', + 'display' => 'Save as draft' + ); +/* + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'previewPage', + 'display' => 'Preview Changes' + ); +*/ + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'cancel', + 'display' => 'Cancel' + ); + if (!$hideDelete) { + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'deletePage', + 'display' => 'Delete Page' + ); + } + + $templates = array(); + + $options = range(1, 6); + foreach ($options as $i) { + $img = "\"page"; + + $templates[] = array( + 'type' => 'radio', + 'req' => false, + 'name' => 'template', + 'att' => $i, + 'opts' => "Template $i
    $img", + ); + } + + // All Elements are created here. + // This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'pageContentHdr', + 'display' => 'Page Content' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'id' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'published_page' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'navigation_name', + 'display' => 'Navigation Name', + 'opts' => array('size' => 35) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Page Title', + 'opts' => array('size' => 35) + ); + if ($_GET['rt'] == 'EditPage' && $showParentPage) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'parent', + 'display' => 'Parent Page', + 'opts' => array('0' => '-- No Parent --'), + ); + } else { + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'parent' + ); + } + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'opts' => array( + 'cols' => 60, + 'rows' => 60, + 'id' => 'description' + ), + 'noCharLimit' => true + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'file', + 'display' => 'New Image' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'caption', + 'display' => 'Image Caption', + 'opts' => array('size' => 35) + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'current_image_thumb', + 'display' => 'Current Image' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'image', + ); + if (!empty($this->_defaultValues['image']) + || ($this->isSubmitted() && $this->getSubmitValue('remove_image')) + ) { + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_image', + 'display' => 'Remove Current Image' + ); + } + + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'pageAttributesHdr', + 'display' => 'Page Attributes' + ); + if (defined('SHORT_URLS') && SHORT_URLS) { + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'short_url_instructions', + 'display' => '', + 'opts' => "Short URL's Must not contain any spaces or non alpha characters.
    Only A-Z, a-z, 0-9, _(underscore), -(dash) allowed" + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'short_url', + 'display' => 'Short URL', + ); + } + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'keyword', + 'display' => 'Keyword', + 'opts' => array('size' => 35) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'paragraph_links', + 'display' => 'Paragraph Links', + 'opts' => 'Show links to the paragraph headlines at the top of the page', + 'val' => array(0, 1) + ); + + if (!is_null($memRoot)) { + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'memberDbHdr', + 'display' => $pluralMem, + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'include_members', + 'display' => "Members", + 'opts' => "Include Members On Page", + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => ' + + + To include all members, turn this feature on and + don\'t select categories or regions below.
    + To restrict to specific categories, select desired + categories under Category Filter.
    + To restrict to specific regions, select desired + regions under Region Filter. + + ' + ); + // Note that we call to populate this select list at the + // bottom of this function after the element is made + // so we load attributes (classes) into each option as needed. + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'member_categories', + 'display' => 'Category Filter
    (none = all)', + 'opts' => array(), + 'att' => array( + 'multiple' => 'multiple', + 'size' => 7, + 'title' => '-- Select to Add --', + 'id' => 'MemberCategories' + ) + ); + if ($hasRegions) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'member_regions', + 'display' => 'Region Filter
    (none = all)', + 'opts' => array(), + 'att' => array( + 'multiple' => 'multiple', + 'size' => 7, + 'title' => '-- Select to Add --', + 'id' => 'MemberRegions' + ) + ); + } + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'include_member_map', + 'display' => "Google Map", + 'opts' => "Include Map On Page", + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'search_form', + 'display' => "Search Box", + 'opts' => 'Include Search Box', + 'val' => array(0, 1) + ); + } + + if (!is_null($cpnRoot)) { + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'couponsHdr', + 'display' => $pluralCpn + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'include_coupons', + 'display' => "Coupons", + 'opts' => "Include Coupons On Page", + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => ' + + + To include all coupons, turn this feature on and + don\'t select categories below.
    + To restrict to specific categories, select desired + categories under Categories Filter. + + ' + ); + // Note that we call to populate this select list at the + // bottom of this function after the element is made + // so we load attributes (classes) into each option as needed. + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'coupon_categories', + 'display' => 'Category Filter
    (none = all)', + 'opts' => $this->_getCouponCategories($dbh), + 'att' => array( + 'multiple' => 'multiple', + 'size' => 4, + 'title' => '-- Select to Add --', + 'id' => 'CouponCategories' + ) + ); + } + + if (defined('HOME_HEADLINES') && HOME_HEADLINES) { + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'homePageHeadlinesHdr', + 'display' => 'Home Page Headlines' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'headline', + 'display' => 'Headline', + 'opts' => 'Include this page in the Home Page Headlines', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'headline_intro', + 'display' => 'Intro', + 'opts' => array('size' => 55), + 'noCharLimit' => true + ); + } + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + if ($_SERVER['PHP_AUTH_USER'] == 'MediaAdmin' || DEVELOPMENT) { + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'metaHdr', + 'display' => 'Metadata Information' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'meta_title', + 'display' => 'Title Tag', + 'opts' => array('size' => 35) + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'meta_description', + 'display' => 'Description', + 'opts' => array( + 'cols' => 40, + 'rows' => 5 + ), + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + } else { + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'meta_title' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'meta_description' + ); + } + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'templatesHdr', + 'display' => 'Page Layout' + ); + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'page_layout', + 'group' => $templates, + 'seperator' => '', + 'appendName' => false + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + if (isset($_GET['id']) && ctype_digit($_GET['id'])) { + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'templatesHdr', + 'display' => 'Page Information' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'page_id', + 'display' => 'Page ID', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'active_alt', + 'display' => 'State', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'revised', + 'display' => 'Revised', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'created', + 'display' => 'Created Date', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'last_modified', + 'display' => 'Last Modified Date', + ); + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + } + $e[] = array( + 'type' => 'html', + 'req' => false, + 'name' => '', + ); + + // If we are editing a page, show three submit buttons + // otherwise, just show one insert button. + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'submit_buttons', + 'group' => $submitBtns, + 'label' => '', + 'seperator' => '', + 'appendName' => false, + ); + + $this->setupElements($e); + + // Do the same for the pages + if ($_GET['rt'] == 'EditPage' && $showParentPage) { + $this->loadParentPages($dbh); + } + + // Load the member categories after the elements have been created + // so we can get more control how the options are rendered + // ie (adding classes to them) + if (defined('MEMBERS_DB') && MEMBERS_DB) { + $this->loadMemberCategories($dbh); + if ($hasRegions) { + $this->loadMemberRegions($dbh); + } + } + } + + // }}} + // {{{ 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' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Bundle all form configuration calls into one function call + * + * @param PDO $dbh Database handler + * @param Toolkit_Toolbox_GatewayFactoryAbstract $factory Gateway factory + * @param Toolkit_FileServer_ImageApater $is Image Server + * @param Config_Container $memRoot (optional) Configuration object + * @param Config_Container $cpnRoot (optional) Configuration object + * + * @return void + * @access public + */ + public function configureForm( + PDO $dbh, + Toolkit_Toolbox_GatewayFactoryAbstract $factory, + Toolkit_FileServer_ImageAdapter $is, + Config_Container $memRoot = null, + Config_Container $cpnRoot = null + ) { + $this->configureDefaults($factory, $_GET['id']); + $this->configureElements($dbh, $memRoot, $cpnRoot, $_GET['id']); + $this->configureRules($is); + $this->configureFilters(); + $this->configureConstants($dbh); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @param Toolkit_FileServer_ImageAdapter $is Image Server + * + * @return void + * @access public + */ + public function configureRules(Toolkit_FileServer_ImageAdapter $is) + { + $r = array(); + + // Form Rules + $r[] = array( + 'element' => 'short_url', + 'message' => 'ERROR: Short URLs may only contain alpha numeric characters plus - (dash) or _ (underscore)!', + 'type' => 'ShortUrl', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + if (!empty($_FILES['file']['tmp_name'])) { + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $is->getAllowedMimeTypes(), + 'validation' => 'server', + 'reset' => false, + 'force' => false + ); + } + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Error uploading image!', + 'type' => 'Image', + 'format' => array( + 'form' => $this, + 'fieldName' => 'file', + 'imageField' => 'image', + 'is' => $is, + 'deleteExistingImage' => false, + 'injectImage' => array('tgtElement' => 'current_image_thumb') + ), + 'validation' => 'server', + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ getCouponCategories() + + /** + * Fetches all coupon categories + * + * @param PDO $dbh Database handler + * + * @return array coupon categories + */ + private function _getCouponCategories(PDO $dbh) + { + $sql = " + SELECT * + FROM coupon_category + ORDER BY name"; + $couponCats = array(); + foreach ($dbh->query($sql) as $row) { + $couponCats[$row['id']] = $row['name']; + } + return $couponCats; + } + + // }}} + + // {{{ loadParentPages() + + /** + * Load option elements into the parent select list + * + * These options are loaded via this seperate function vs inline w/ the + * element definition b/c we need a little more control defining + * the class names for each option so they will render nice when a user + * is looking at the list. + * + * @param PDO $dbh Database handler + * + * @return void + * @throws PDOException throws exception on sql error + * @access public + */ + public function loadParentPages(PDO $dbh) + { + try { + // 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( + $dbh, + 'pages', + 'id', + 'parent', + 'pos', + 0, + $this->maxDepth + ); + + // unset the home page, this is never an option to have children + // underneath it. + unset($c[HOME_ID]); + + // If we are editing a page, then we don't want that page + // to show up as an option in the select list. + if (is_numeric($_GET['id'])) { + reset($c); + // Get us to the point in the array were this page is located + while (key($c) != $_GET['id'] && current($c) !== false) { + next($c); + } + // Make sure we didn't traverse off the end of the array + if (current($c) !== false) { + // get the starting level we are currently at + $sl = current($c); + // remove this page (the one we're editing) from the + // array and advance the internal array pointer + unset($c[key($c)]); + // now we need to make sure all sub pages beneath this + // page are also not being shown + + // while we don't traverse off the end of the array + while (current($c) !== false) { + // get the current sub level we are at + $csl = current($c); + // if the current sub-level is the same as the + // starting level, that means we have traversed through + // all the sub-pages and can break out of the loop + if ($csl <= $sl) { + break; + } else { + // we are still in a sub-level page, so unset + // this page so it doesn't show, and advance + // the internal array pointer + unset($c[key($c)]); + } + } + } + } + + // Get all the data about each category + $sql = " + SELECT * + FROM pages + WHERE id = ?"; + + $stmt = $dbh->prepare($sql); + // Get the member categories select list element + $e =& $this->getElement('parent'); + 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['navigation_name'], + $i, + array('class' => "level-$x") + ); + } + } catch (PDOException $e) { + Toolkit_Logger::logException('DB error', $e); + throw new Toolkit_Toolbox_Exception( + "Error loading parent pages" + ); + } + } + + // }}} + // {{{ 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 + * + * @param PDO $dbh Database handler + * + * @return void + * @access public + */ + public function loadMemberCategories(PDO $dbh) + { + try { + // 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( + $dbh, + 'category', + 'category_id', + 'parent_id' + ); + + // Get all the data about each category + $sql = " + SELECT * + FROM category + WHERE category_id = ?"; + + $stmt = $dbh->prepare($sql); + // Get the member categories select list element + $e =& $this->getElement('member_categories'); + if (is_array($c)) { + 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) { + Toolkit_Logger::logException('DB error', $e); + throw new Toolkit_Toolbox_Exception( + "Error loading member categories" + ); + } + } + + // }}} + // {{{ loadMemberRegions() + + /** + * Loads member Cities into the select list + * + * Gets an array structure of the member Cities in a sorted order by name + * Then walk through the array and load each category into the select list + * + * @param PDO $dbh Database handler + * + * @return void + * @access public + */ + public function loadMemberRegions(PDO $dbh) + { + try { + // Get all the data about each category + $sql = " + SELECT * + FROM region + ORDER BY region_name"; + + $stmt = $dbh->query($sql); + // Get the member categories select list element + $e =& $this->getElement('member_regions'); + while ($row = $stmt->fetch()) { + // Add the option data to the select list. + $e->addOption($row['region_name'], $row['region_id']); + } + } catch (PDOException $e) { + Toolkit_Logger::logException('DB error', $e); + throw new Toolkit_Toolbox_Exception( + "Error loading member regions" + ); + } + } + + // }}} + + // {{{ setMaxDepth() + + /** + * Sets the max depth level that the parent page select list will show + * + * @param integer $md New max depth + * + * @return void + * @access public + */ + public function setMaxDepth($md) + { + $this->maxDepth = $md; + } + + // }}} + // {{{ setupRenderers() + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + + $required = ''; + $required .= ' * '; + $required .= ''; + + $error = ''; + $error .= '
    {error}
    '; + $error .= ''; + + $baseUrl = BASE_URL; + + $renderer->setFormTemplate( + "
    \n + \n +
    + {hidden} +
    + {requiredNote} + \n + {content} \n +
    \n + \n +
    " + ); + + $renderer->setElementTemplate( + "\n + $required{label}\n + {$error}{$baseUrl}{element}/\n + \n", + 'short_url' + ); + $renderer->setElementTemplate( + "\n + $required{label}$error{element} + ", + 'description' + ); + $renderer->setElementTemplate( + "\n + $required{label}$error{element} + ", + 'submit_buttons' + ); + $renderer->setElementTemplate( + "\n + $required{label}$error{element}\n + ", + 'edit' + ); + + $renderer->setElementTemplate( + "\n + $required{label}$error{element}\n + \n", + 'page_layout' + ); + $renderer->setGroupTemplate( + "\n + {content}\n +
    \n", + 'page_layout' + ); + $renderer->setGroupElementTemplate( + "\n + {element}
    {label}\n + \n", + 'page_layout' + ); + } + + // }}} + + // {{{ toHtml() + + /** + * Handles how to display the current step the user is at in the form + * + * @return string rendered html form + * @access public + */ + public function toHtml() + { + $GLOBALS['topScripts'][] + = GLM_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.js'; + $GLOBALS['bottomScripts'][] + = BASE_URL . 'Toolkit/Toolbox/libjs/edit-page.js'; + + $GLOBALS['styleSheets'][] + = GLM_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.css'; + $GLOBALS['styleSheets'][] + = BASE_URL . 'css/contactform.css'; + $GLOBALS['styleSheets'][] + = BASE_URL . 'Toolkit/Toolbox/styles.css'; + + $this->setupRenderers(); + + return parent::toHtml(); + } + + // }}} +} diff --git a/Toolkit/Toolbox/Forms/EditParagraph.php b/Toolkit/Toolbox/Forms/EditParagraph.php new file mode 100644 index 0000000..5b808f7 --- /dev/null +++ b/Toolkit/Toolbox/Forms/EditParagraph.php @@ -0,0 +1,503 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditParagraph.php,v 1.4 2010/07/20 18:39:40 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +require_once BASE . 'Toolkit/Forms/Rules/Image.php'; + +/** + * Edit a page paragraph form + * + * @category Toolbox + * @package Toolkit_Toolbox + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Toolbox_Forms_EditParagraph extends Toolkit_FormBuilder +{ + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @param Toolkit_Toolbox_GatewayFactoryAbstract $factory Gateway factory + * @param integer $id pargraph id (optional) + * @return void + * @access public + */ + public function configureDefaults( + Toolkit_Toolbox_GatewayFactoryAbstract $factory, + Toolkit_Toolbox_FileExtension $fileExtension, + $id = null + ) { + if (!is_null($id)) { + $gateway = $factory->createGateway(); + $paragraph = $gateway->find($id); + if ( isset($paragraph['files']) + && is_array($paragraph['files']) + ) { + $files = array(); + foreach ($paragraph['files'] as $file) { + $linkRenderer + = Toolkit_Template_Page_FileLink_Factory::createLinkRenderer( + $file + ); + $fileLink = $linkRenderer->getLink(); + $extImg = $fileExtension->getImage($file['filename']); + $id = preg_replace('/[^A-Za-z0-9]/', '', $file['urltext']); + $files[] = ' +
  • + + '.$fileLink.' + File Name: +
    + + + + +
  • '; + } + $paragraph['uploaded_files'] = '
      ' . implode('', $files) . '
    '; + } + } else { + $paragraph = array( + 'current_image_thumb' => 'Image not yet uploaded', + 'page' => $_GET['pageid'], + 'active' => true, + ); + } + + $this->setupDefaults($paragraph); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @param PDO $dbh Database handler + * + * @return void + * @access public + */ + public function configureElements(PDO $dbh) + { + $e = array(); + // Grouped Elements are defined here. + $submitBtns = array(); + + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'saveParagraph', + 'display' => 'Save Paragraph' + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'cancel', + 'display' => 'Cancel' + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'deleteParagraph', + 'display' => 'Delete Paragraph' + ); + + // All Elements are created here. + // This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'id' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'active' + ); + if ($_GET['rt'] == 'Paragraphs') { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'page', + 'display' => 'Page', + 'opts' => array(), + ); + } else { + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'page' + ); + } + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Title', + 'opts' => array('size' => 40) + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'opts' => array( + 'cols' => 60, + 'rows' => 60, + 'id' => 'description' + ), + 'noCharLimit' => true + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'file', + 'display' => 'New Image' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'caption', + 'display' => 'Image Caption', + 'opts' => array('size' => 35) + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'current_image_thumb', + 'display' => 'Current Image' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'image', + ); + if (!empty($this->_defaultValues['image'])) { + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_image', + 'display' => 'Remove Current Image' + ); + } + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'back_to_top', + 'display' => "Insert 'Back to Top' link", + 'opts' => 'Yes', + 'val' => array(0, 1) + ); + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'templatesHdr', + 'display' => 'Files' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fileurltext', + 'display' => 'New File Name', + 'opts' => array('size' => 35) + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'filename', + 'display' => 'New File', + 'opts' => array('id' => 'filename') + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'uploaded_files', + 'display' => 'Uploaded Files', + 'opts' => '
      ' + ); + + // If we are editing a page, show three submit buttons + // otherwise, just show one insert button. + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'submit_buttons', + 'group' => $submitBtns, + 'label' => '', + 'seperator' => '', + 'appendName' => false, + ); + + $this->setupElements($e); + // Do the same for the pages + if ($_GET['rt'] == 'Paragraphs') { + $this->loadParagraphPages($dbh); + } + } + + // }}} + // {{{ 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' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Bundle all form configuration calls into one function call + * + * @param PDO $dbh Database handler $dbh Database handler + * @param Toolkit_Toolbox_GatewayFactoryAbstract $factory Gateway factory + * @param Toolkit_FileServer_ImageAdapter $is Image adapter for file server + * @param Toolkit_FileServer_FileAdapter $fs File adapter for file server + * + * @return void + * @access public + */ + public function configureForm( + PDO $dbh, + Toolkit_Toolbox_GatewayFactoryAbstract $factory, + Toolkit_FileServer_ImageAdapter $is, + Toolkit_FileServer_FileAdapter $fs, + Toolkit_Toolbox_FileExtension $fileExtension + ) { + $this->configureDefaults($factory, $fileExtension, $_GET['id']); + $this->configureElements($dbh); + $this->configureRules($is, $fs); + $this->configureFilters(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @param Toolkit_FileServer_ImageAdapter $is Image adapter for file server + * @param Toolkit_FileServer_FileAdapter $fs File adapter for file server + * + * @return void + * @access public + */ + public function configureRules( + Toolkit_FileServer_ImageAdapter $is, + Toolkit_FileServer_FileAdapter $fs + ) { + $r = array(); + // Form Rules + if (!empty($_FILES['file']['tmp_name'])) { + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $is->getAllowedMimeTypes(), + 'validation' => 'server', + 'reset' => false, + 'force' => false + ); + } + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Error uploading image!', + 'type' => 'Image', + 'format' => array( + 'form' => $this, + 'fieldName' => 'file', + 'imageField' => 'image', + 'is' => $is, + 'deleteExistingImage' => false, + 'injectImage' => array('tgtElement' => 'current_image_thumb') + ), + 'validation' => 'server', + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ loadParagraphPages() + + /** + * Load option elements into the parent select list + * + * These options are loaded via this seperate function vs inline w/ the + * element definition b/c we need a little more control defining + * the class names for each option so they will render nice when a user + * is looking at the list. + * + * @param PDO $dbh Database handler + * + * @return void + * @throws PDOException throws exception on sql error + * @access public + */ + public function loadParagraphPages(PDO $dbh) + { + try { + // 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( + $dbh, + 'pages', + 'id', + 'parent', + 'pos' + ); + + // Get all the data about each category + $sql = " + SELECT * + FROM pages + WHERE id = ?"; + + $stmt = $dbh->prepare($sql); + // Get the member categories select list element + $e =& $this->getElement('page'); + foreach ($c as $i => $j) { + $stmt->execute(array($i)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + // 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['navigation_name'], $i, array('class' => "level-$x")); + } + } catch (PDOException $e) { + Toolkit_Logger::logException('DB error', $e); + throw new Toolkit_Toolbox_Exception( + "Error loading parent pages for paragraph" + ); + } + } + + // }}} + + // {{{ setupRenderers() + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + + $required = ''; + $required .= ' * '; + $required .= ''; + + $error = ''; + $error .= '
      {error}
      '; + $error .= ''; + + $renderer->setElementTemplate( + "\n + $required{label}$error{element} + ", + 'submit_buttons' + ); + $renderer->setElementTemplate( + "\n + $required{label}$error{element}\n + ", + 'insert' + ); + + $renderer->setElementTemplate( + "\n + $required{label}$error{element} + ", + 'description' + ); + } + + // }}} + + // {{{ toHtml() + + /** + * Handles how to display the current step the user is at in the form + * + * @param PDO $dbh Database handler + * + * @return string rendered html form + * @access public + */ + public function toHtml(PDO $dbh) + { + $GLOBALS['topScripts'][] + = GLM_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'ckeditor/current/ckeditor.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/plugins/ajaxUpload/3.9/ajaxupload.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js'; + $GLOBALS['bottomScripts'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8.13/development-bundle/ui/minified/jquery.ui.sortable.min.js'; + $GLOBALS['bottomScripts'][] + = BASE_URL . 'Toolkit/Toolbox/libjs/edit-paragraph.js'; + + $GLOBALS['styleSheets'][] = BASE_URL . 'css/contactform.css'; + $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Toolbox/styles.css'; + $GLOBALS['styleSheets'][] + = GLM_APP_BASE_URL . 'libjs/jqueryui/1.8.13/css/smoothness/jquery-ui-1.8.13.custom.css'; + + $this->setupRenderers(); + $out + = ($_REQUEST['g'] == '1') + ? '
      Form Submit Successfull!
      ' + : ''; + + return $out . parent::toHtml(); + } + + // }}} +} diff --git a/Toolkit/Toolbox/Forms/SearchForm.php b/Toolkit/Toolbox/Forms/SearchForm.php new file mode 100644 index 0000000..d5e5d1c --- /dev/null +++ b/Toolkit/Toolbox/Forms/SearchForm.php @@ -0,0 +1,174 @@ + 'Search'); + + $this->setupConstants($c); + } + + // }}} + // {{{ 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' => 'hidden', + 'req' => false, + 'name' => 'rt' + ); + + $elements = array(); + + $elements[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'q', + 'opts' => array( + 'size' => 75, + 'id' => 'q' + ) + ); + $elements[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => 'Search Page Titles' + ); + + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'fields', + 'group' => $elements, + 'seperator' => '', + 'appendName' => false + ); + $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' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Bundle all form configuration calls into one function call + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureConstants(); + $this->configureElements(); + $this->configureFilters(); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + + $required = ''; + $required .= ' * '; + $required .= ''; + + $error = ''; + $error .= '
      {error}
      '; + $error .= ''; + + $renderer->setElementTemplate( + "\n + $required{label}$error{element}\n + \n", + 'fields' + ); + } + + // }}} + + // {{{ toHtml() + + /** + * Handles how to display the current step the user is at in the form + * + * @return string rendered html form + * @access public + */ + public function toHtml() + { + $GLOBALS['styleSheets'][] + = BASE_URL . 'css/contactform.css'; + $GLOBALS['styleSheets'][] + = BASE_URL . 'Toolkit/Toolbox/styles.css'; + + $this->setupRenderers(); + + return parent::toHtml(); + } + + // }}} +} diff --git a/Toolkit/Toolbox/GatewayAbstract.php b/Toolkit/Toolbox/GatewayAbstract.php new file mode 100644 index 0000000..6c75f35 --- /dev/null +++ b/Toolkit/Toolbox/GatewayAbstract.php @@ -0,0 +1,32 @@ +dbh = $dbh; + } + + // }}} + // {{{ find() + + abstract public function find($id); + + // }}} + // {{{ update() + + abstract public function update(array $data, $id); + + // }}} + // {{{ insert() + + abstract public function insert(array $data); + + // }}} +} diff --git a/Toolkit/Toolbox/GatewayFactoryAbstract.php b/Toolkit/Toolbox/GatewayFactoryAbstract.php new file mode 100644 index 0000000..7294fda --- /dev/null +++ b/Toolkit/Toolbox/GatewayFactoryAbstract.php @@ -0,0 +1,12 @@ +dbh = $dbh; + } + + abstract public function createGateway(); +} diff --git a/Toolkit/Toolbox/IndexController.php b/Toolkit/Toolbox/IndexController.php new file mode 100644 index 0000000..f40736d --- /dev/null +++ b/Toolkit/Toolbox/IndexController.php @@ -0,0 +1,36 @@ +configureForm(); + + $html = $searchForm->toHtml(); + + $toolboxConfig = new Config; + $toolboxConfigRoot =& $toolboxConfig->parseConfig( + BASE . 'Toolkit/Toolbox/config.ini', + 'IniFile' + ); + $tree = new Toolkit_Toolbox_PagesTree($toolboxConfigRoot); + $html .= $tree->toHtml( + new Toolkit_Toolbox_PageGatewayPublish($this->registry->dbh) + ); + + return $html; + } + + // }}} +} diff --git a/Toolkit/Toolbox/ListDraftsController.php b/Toolkit/Toolbox/ListDraftsController.php new file mode 100644 index 0000000..aac13e8 --- /dev/null +++ b/Toolkit/Toolbox/ListDraftsController.php @@ -0,0 +1,26 @@ +parseConfig( + BASE . 'Toolkit/Toolbox/config.ini', + 'IniFile' + ); + $tree = new Toolkit_Toolbox_DraftPagesTree($toolboxConfigRoot); + $html .= $tree->toHtml( + new Toolkit_Toolbox_PageGatewayDraft($this->registry->dbh) + ); + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/Navigation.php b/Toolkit/Toolbox/Navigation.php new file mode 100644 index 0000000..21c851b --- /dev/null +++ b/Toolkit/Toolbox/Navigation.php @@ -0,0 +1,105 @@ +menu = $menu; + $this->rEngine = $rEngine; + $this->currIndex = 'listToolbox'; + } + + // }}} + // {{{ setNavTemplates() + + protected function setNavTemplates() + { + $tpl = '
    • {Title}
    • '; + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_INACTIVE, + sprintf($tpl, '{url}', '{desc}', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVE, + sprintf($tpl, '{url}', '{desc}', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVEPATH, + sprintf($tpl, '{url}', '{desc}', '{Title}') + ); + $this->rEngine->setMenuTemplate('', ''); + $this->rEngine->setRowTemplate('
        ', '
      '); + } + + // }}} + // {{{ setCurrentIndex() + + protected function setCurrentIndex() + { + $this->menu->forceCurrentIndex($_GET['rt']); + } + + // }}} + // {{{ getNavSructure() + // @codeCoverageIgnoreStart + + /** + * Sets up a multi dimensional array used for the nav structure + * + * @param Config_Container $c Application configuration + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure(Config_Container $c) + { + // get reference to [listing type] section of config file + $appName = $c->getItem('section', 'conf') + ->getItem('directive', 'applicationName') + ->getContent(); + + $nav = array( + 'publishedPages' => array( + 'Title' => "Published Pages", + 'url' => BASE_URL . 'admin/toolbox.php', + 'desc' => "Display all the published pages", + ), + 'draftPages' => array( + 'Title' => 'Page Drafts', + 'url' => BASE_URL . 'admin/toolbox.php?rt=ListDrafts', + 'desc' => 'Display all the page drafts' + + ), + 'editPage' => array( + 'Title' => "Create New Page", + 'url' => BASE_URL . 'admin/toolbox.php?rt=EditPage', + 'desc' => "Create a new {$appName} Page" + ), + ); + + if (isset($_GET['rt']) && $_GET['rt'] == 'Paragraphs') { + $nav['editParagraph'] = array( + 'Title' => "Create Page Paragraph", + 'url' => BASE_URL . "admin/toolbox.php?rt=Paragraphs&ac=edit&pageid={$_GET['pageid']}", + 'desc' => "Edit a Page Paragraph" + ); + } elseif (isset($_GET['rt']) && $_GET['rt'] == 'ParagraphsDraft') { + $nav['editParagraph'] = array( + 'Title' => "Create Page Paragraph", + 'url' => BASE_URL . "admin/toolbox.php?rt=ParagraphsDraft&ac=edit&pageid={$_GET['pageid']}", + 'desc' => "Edit a Page Paragraph" + ); + } + + return $nav; + } + + // @codeCoverageIgnoreEnd + // }}} +} +?> diff --git a/Toolkit/Toolbox/Page.php b/Toolkit/Toolbox/Page.php new file mode 100644 index 0000000..681e56f --- /dev/null +++ b/Toolkit/Toolbox/Page.php @@ -0,0 +1,322 @@ +_id = (int) $id; + } else { + throw new Toolkit_Toolbox_Exception("Invalid page id `$id`"); + } + } + + $this->content = $cf->getComponent('content', $data); + $this->members = $cf->getComponent('members', $data); + $this->coupons = $cf->getComponent('coupons', $data); + $this->attributes = $cf->getComponent('attributes', $data); + $this->headlines = $cf->getComponent('headlines', $data); + $this->metaData = $cf->getComponent('metadata', $data); + $this->_createDate = $data['createDate']; + $this->_lastModifiedDate = $data['lastModifiedDate']; + $this->_revisions = $data['revisions']; + } + + // }}} + + // {{{ delete() + + /** + * Delete a toolbox page + * + * @param PDO $dbh Database handler + * @param integer $id Toolbox page id to delete + * + * @return boolean Result of delete query + * @access public + * @throws Toolkit_Toolbox_Exception + */ + public static function delete(PDO $dbh, $id) + { + try { + $sql = " + DELETE FROM bus_category + WHERE id = :id"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Error deleting the toolbox page `$id`" + ); + } + } + + // }}} + + // {{{ fetch() + + public static function fetch(PDO $dbh, $id) + { + if (!ctype_digit((string)$id)) { + throw new Toolkit_Toolbox_Exception("Invalid page id `$id`"); + } + try { + $sql = " + SELECT * + FROM bus_category + WHERE id = :id"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $d = $stmt->fetch(); + + $sql = " + SELECT * + FROM bus_cat_member + WHERE catid = :id"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + $d['memberCat'] = array(); + while ($row = $stmt->fetch()) { + $d['memberCat'][] = $row['memb_type']; + } + + $sql = " + SELECT * + FROM coupon_categories2toolbox_pages + WHERE toolbox_catid = :id"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + $d['couponCat'] = array(); + while ($row = $stmt->fetch()) { + $d['couponCat'][] = $row['category_id']; + } + + $sql = " + SELECT CASE + WHEN active THEN 'Active' + ELSE 'In-Active' + END AS active + FROM bus_category + WHERE id = :id"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(); + $d['active'] = $row['active']; + + $sql = " + SELECT to_char(min(revision_timestamp), 'FMDay, DD Month FMHH12:MIpm') AS created, + to_char(max(revision_timestamp), 'FMDay, DD Month FMHH12:MIpm') AS last_modified, + count(*) AS total + FROM bus_category_history + WHERE id = :id"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(); + $d['revisions'] = $row['total']; + $d['createDate'] = $row['created']; + $d['lastModifiedDate'] = $row['last_modified']; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Error retrieving defaults for page `$id`" + ); + } + + return new self(new Toolkit_Toolbox_ComponentFactory(), $d, $id); + } + + // }}} + // {{{ getBusCategoryData() + public function getBusCategoryData() + { + if ($this->content->getRemoveImage()) { + $this->content->setImage(Toolkit_Toolbox_ImageFactory::getImage()); + $this->content->setImageName(null); + } + return array( + 'intro' => $this->content->getIntro(), + 'description' => $this->content->getDescription(), + 'image' => $this->content->getImage()->getSrc(), + 'imagename' => $this->content->getImageName(), + 'parent' => $this->attributes->getParent(), + 'category' => $this->attributes->getCategory(), + 'keyword' => $this->attributes->getKeyword(), + 'template' => $this->attributes->getTemplate(), + 'section_links' => $this->attributes->getSectionLinks(), + 'short_url' => $this->attributes->getShortUrl(), + 'featured' => $this->headlines->getFeatured(), + 'feature_intro' => $this->headlines->getFeatureIntro(), + 'no_search_form' => $this->members->getSearch(), + 'include_member_map' => $this->members->getMap(), + 'meta_descr' => $this->metaData->getDescription(), + 'title' => $this->metaData->getTitle(), + ); + } + + // }}} + + // {{{ save() + public function save(PDO $dbh) + { + try { + $dbh->beginTransaction(); + + $busCategoryData = $this->getBusCategoryData(); + + $busCategorySql = Toolkit_Common::createSQLInsert( + 'bus_category', + array_keys($busCategoryData) + ); + + $stmt = Toolkit_Common::prepareQuery( + $dbh, + 'bus_category', + $busCategorySql, + $busCategoryData + ); + + $stmt->execute(); + $catidSql = " + SELECT * + FROM bus_category + ORDER BY id DESC LIMIT 1"; + + $row = $dbh->query($catidSql)->fetch(PDO::FETCH_ASSOC); + $this->_id = (int) $row['id']; + + $this->coupons->saveCategories($dbh, $this->_id); + $this->members->saveCategories($dbh, $this->_id); + + return $dbh->commit(); + } catch (PDOException $e) { + $dbh->rollback(); + Toolkit_Logger::logException('db error', $e); + throw new Toolkit_Toolbox_Exception('Error saving page in Database'); + } + } + + // }}} + + // {{{ update() + public function update(PDO $dbh) + { + try { + if (!isset($this->_id)) { + throw new RuntimeException('Page does not exist yet'); + } + $dbh->beginTransaction(); + + $busCategoryData = $this->getBusCategoryData(); + + $busCategorySql = Toolkit_Common::createSQLUpdate( + 'bus_category', + array_keys($busCategoryData), + array("id = {$this->_id}") + ); + + $stmt = Toolkit_Common::prepareQuery( + $dbh, + 'bus_category', + $busCategorySql, + $busCategoryData + ); + + $stmt->execute(); + + $this->coupons->updateCategories($dbh, $this->_id); + $this->members->updateCategories($dbh, $this->_id); + + return $dbh->commit(); + + } catch (PDOException $e) { + Toolkit_Logger::logException('db error', $e); + throw new Toolkit_Toolbox_Exception('Error updating page in Database'); + } catch (RuntimeException $e) { + Toolkit_Logger::logException('Runtime Error', $e); + throw new Toolkit_Toolbox_Exception($e->getMessage()); + } + } + + // }}} + + // {{{ getCreateDate() + + public function getCreateDate() + { + return $this->_createDate; + } + + // }}} + // {{{ getLastModificationDate() + + public function getLastModificationDate() + { + return $this->_lastModifiedDate; + } + + // }}} + // {{{ getNumberOfRevisions() + + public function getNumberOfRevisions() + { + return $this->_revisions; + } + + // }}} + // {{{ getActive() + + public function getActive() + { + return $this->_active; + } + + // }}} + // {{{ getActiveText() + + public function getActiveText() + { + return $this->_active ? 'Active' : 'In-Active'; + } + + // }}} + + public function getId() + { + return $this->_id; + } +} +?> diff --git a/Toolkit/Toolbox/PageBreadCrumbs.php b/Toolkit/Toolbox/PageBreadCrumbs.php new file mode 100644 index 0000000..ef85626 --- /dev/null +++ b/Toolkit/Toolbox/PageBreadCrumbs.php @@ -0,0 +1,12 @@ +{$page['navigation_name']}"; + } +} +?> diff --git a/Toolkit/Toolbox/PageDraftBreadCrumbs.php b/Toolkit/Toolbox/PageDraftBreadCrumbs.php new file mode 100644 index 0000000..b880f28 --- /dev/null +++ b/Toolkit/Toolbox/PageDraftBreadCrumbs.php @@ -0,0 +1,72 @@ +{$page['navigation_name']}"; + } + + // }}} + // {{{ getDraft() + + protected function getDraft($id) + { + try { + $sql = " + SELECT * + FROM pages_draft + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + return $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Could not fetch parent for page `$id`" + ); + } + } + + // }}} + // {{{ getPath() + + /** + * @return the $path + */ + public function getPath() + { + if ($this->id == HOME_ID) { + return; + } + + $draft = $this->getDraft($this->id); + $stack = array($draft['navigation_name']); + + $publishedPage = $this->getPage($draft['published_page']); + $id = $publishedPage['parent']; + while ($id != 0) { + $page = $this->getPage($id); + + $navigationName = $this->getPageUri($page); + + $stack[] = $navigationName; + $id = $page['parent']; + } + + $reverse = array_reverse($stack); + $this->path = implode(' > ', $reverse); + + return $this->path; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/PageGatewayAbstract.php b/Toolkit/Toolbox/PageGatewayAbstract.php new file mode 100644 index 0000000..727b341 --- /dev/null +++ b/Toolkit/Toolbox/PageGatewayAbstract.php @@ -0,0 +1,280 @@ +dbh->prepare($sql); + $stmt->bindParam(':parent', $parent, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Error fetching all pages by parent `$parent`" + ); + } + } + + // }}} + // {{{ findByKeyword() + + abstract public function findByKeyword($keyword); + + // }}} + // {{{ findTopParent() + + abstract public function findTopParent($pageId); + + // }}} + // {{{ findPage() + + protected function findPage($id, $pageSql) + { + // if the page has already been fetched, just return it. + if (is_array($this->page) && $this->page['id'] == $id) { + return $this->page; + } + + $pageStatsSql = " + SELECT count(*) AS revised, + MIN(revision_timestamp) AS created, + MAX(revision_timestamp) AS last_modified + FROM pages_history + WHERE id = :id"; + + $pageStmt = $this->dbh->prepare($pageSql); + $pageStmt->bindParam(':id', $id, PDO::PARAM_INT); + $pageStmt->execute(); + + $page = $pageStmt->fetch(PDO::FETCH_ASSOC); + + if ($page === false) { // Page doesn't exist + return false; + } + + if ($this->hasMemberDb()) { + $page['member_categories'] + = $this->getMemberCategoriesForPage($id); + $page['member_regions'] + = $this->getMemberRegionsForPage($id); + } + + if ($this->hasCouponDb()) { + $page['coupon_categories'] + = $this->getCouponCategoriesForPage($id); + } + + if ($this->hasPhotoGallery()) { + $page['photo_galleries'] + = $this->getPhotoGalleriesForPage($id); + } + + $pageStatsStmt = $this->dbh->prepare($pageStatsSql); + $pageStatsStmt->bindParam(':id', $id, PDO::PARAM_INT); + $pageStatsStmt->execute(); + + $pageStats = $pageStatsStmt->fetch(PDO::FETCH_ASSOC); + + $date = new Date(); + $date->setDate(strtotime($pageStats['created']), DATE_FORMAT_UNIXTIME); + $pageStats['created'] = $date->format('%D %r'); + $date->setDate(strtotime($pageStats['last_modified']), DATE_FORMAT_UNIXTIME); + $pageStats['last_modified'] = $date->format('%D %r'); + $page = array_merge($page, $pageStats); + + if (!empty($page['image'])) { + $imgFormat = "\"%s\""; + $page['current_image_original'] = sprintf( + $imgFormat, + $page['image'], + TOOLBOX_ORIGINAL . $page['image'] + ); + $page['current_image_resized'] = sprintf( + $imgFormat, + $page['image'], + TOOLBOX_RESIZED . $page['image'] + ); + $page['current_image_midsized'] = sprintf( + $imgFormat, + $page['image'], + TOOLBOX_MIDSIZED . $page['image'] + ); + $page['current_image_thumb'] = sprintf( + $imgFormat, + $page['image'], + TOOLBOX_THUMB . $page['image'] + ); + } else { + $page['current_image_original'] = 'Image not yet uploaded'; + $page['current_image_resized'] = 'Image not yet uploaded'; + $page['current_image_midsized'] = 'Image not yet uploaded'; + $page['current_image_thumb'] = 'Image not yet uploaded'; + } + + $this->page = $page; + return $this->page; + } + + // }}} + + // {{{ getCurrentPage() + + /** + * Gets the current page for the template if it exists + * + * @return mixed array of current page or false if no current page is set + * @access public + */ + public function getCurrentPage() + { + return is_array($this->page) ? $this->page : false; + } + + // }}} + // {{{ getHomePageHeadlines() + + public function getHomePageHeadlines() + { + $wordCounter = array( + 1 => 'one', + 2 => 'two', + 3 => 'three', + 4 => 'four' + ); + $headlines = array(); + $sql = " + SELECT p1.id, p1.navigation_name, p1.headline_intro, p2.image + FROM pages p1 join paragraphs p2 on (p1.id = p2.page) + WHERE p1.headline = true + AND p1.active = true + AND p2.pos = 1 + ORDER BY p1.parent, p1.pos"; + + $count = 1; + foreach ($this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) { + $headlines[] = array( + 'count' => $wordCounter[$count], + 'href' => Toolkit_Template_Page::getSeoUrl($this, $row['id']), + 'img' => ($row['image']) + ? HOMEPAGE_HEADLINE_THUMB . $row['image'] + : '', + 'header' => $row['navigation_name'], + 'descr' => nl2br($row['headline_intro']), + ); + if (++$count > 4) { + $count = 1; + } + } + + return $headlines; + } + + // }}} + + // {{{ setPageVars() + + protected function setPageVars(PDOStatement &$stmt, $data) + { + if ($this->hasHeadlines()) { + $data['headline'] = (bool)$data['headline']; + $stmt->bindParam( + ':headline', + $data['headline'], + PDO::PARAM_BOOL + ); + $stmt->bindParam(':headline_intro', $data['headline_intro']); + } + + if ($this->hasMemberDb()) { + $data['include_member_map'] = (bool)$data['include_member_map']; + $data['search_form'] = (bool)$data['search_form']; + $stmt->bindParam( + ':include_member_map', + $data['include_member_map'], + PDO::PARAM_BOOL + ); + $stmt->bindParam( + ':search_form', + $data['search_form'], + PDO::PARAM_BOOL + ); + } + + $stmt->bindParam(':keyword', $data['keyword']); + $stmt->bindParam(':meta_title', $data['meta_title']); + $stmt->bindParam(':meta_description', $data['meta_description']); + $stmt->bindParam(':navigation_name', $data['navigation_name']); + $stmt->bindParam(':parent', $data['parent']); + $stmt->bindParam(':paragraph_links', $data['paragraph_links']); + $stmt->bindParam(':short_url', $data['short_url']); + $stmt->bindParam(':template', $data['template']); + $stmt->bindParam(':include_members', $data['include_members']); + $stmt->bindParam(':include_coupons', $data['include_coupons']); + } + + // }}} + // {{{ setParagraphVars() + + protected function setParagraphVars(PDOStatement &$stmt, $data) + { + if ($data['remove_image']) { + $data['image'] = ''; + } + $stmt->bindParam(':title', $data['title']); + $stmt->bindParam(':description', $data['description']); + $stmt->bindParam(':image', $data['image']); + $stmt->bindParam(':caption', $data['caption']); + } + + // }}} +} diff --git a/Toolkit/Toolbox/PageGatewayDraft.php b/Toolkit/Toolbox/PageGatewayDraft.php new file mode 100644 index 0000000..2b51dfe --- /dev/null +++ b/Toolkit/Toolbox/PageGatewayDraft.php @@ -0,0 +1,553 @@ +dbh->prepare($pageSql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to delete page draft `$id`" + ); + } + } + + // }}} + public function findNavItem($id) + { + $sql = " + SELECT id,navigation_name,parent,short_url + FROM pages + WHERE id = :id"; + + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':id', + $id, + PDO::PARAM_INT + ); + $stmt->execute(); + return $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception("Unable to find page `$id`"); + } + } + // {{{ find() + + public function find($id) + { + $pageSql = " + SELECT p1.*, p1.id AS page_id, + CASE p1.active + WHEN true THEN 'active' + ELSE 'In-Active' + END AS active, p2.title, p2.description, p2.image, p2.caption + FROM pages_draft p1 + LEFT JOIN paragraphs_draft p2 + ON p1.id = p2.page + WHERE p1.id = :id + AND (p2.pos = 1 OR p2.pos IS NULL)"; + + try { + return $this->findPage($id, $pageSql); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to find page draft `$id`" + ); + } + } + + // }}} + // {{{ findAll() + + public function findAll() + { + try { + $sql = " + SELECT * + FROM pages_draft + ORDER by parent, pos"; + + return $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + 'Error fetching all draft pages' + ); + } + } + + // }}} + // {{{ findByKeyword() + + public function findByKeyword($keyword) + { + try { + $pageSql = " + SELECT id + FROM pages_draft + WHERE keyword = :keyword"; + + $stmt = $this->dbh->prepare($pageSql); + $stmt->bindParam(':keyword', $keyword); + $stmt->execute(); + + // Bind by column number + $stmt->bindColumn(1, $id); + + $stmt->fetch(PDO::FETCH_ASSOC); + + return $this->find($id); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to find page draft `$id`" + ); + } + } + + // }}} + // {{{ findTopParent() + + public function findTopParent($pageId, $useDraftTable = true) + { + if (!ctype_digit((string)$pageId)) { + throw new runtimeException("Invalid pageId `$pageId` to fetch"); + } + + try { + if ($useDraftTable) { + $sql = " + SELECT * + FROM pages_draft + WHERE id = :id"; + } else { + $sql = " + SELECT * + FROM pages + WHERE id = :id"; + } + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $pageId, PDO::PARAM_INT); + $stmt->execute(); + + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($row['parent'] == '0') { + return $row['id']; + } else { + return $this->findTopParent($row['parent'], false); + } + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to find parent for page `$pageId`" + ); + } + } + + // }}} + + // {{{ insert() + + public function insert(array $data) + { + if (empty($data['published_page'])) { + settype($data['published_page'], 'null'); + } + + if ($this->hasHeadlines()) { + $headlineColumns = 'headline, headline_intro,'; + $headlineParams = ':headline, :headline_intro,'; + } + + if ($this->hasMemberDb()) { + $memberColumns = 'include_member_map, search_form, '; + $memberParams = ':include_member_map, :search_form, '; + } + + $pageSql = " + INSERT INTO pages_draft ( + $headlineColumns $memberColumns keyword, meta_title, + meta_description, navigation_name, parent, paragraph_links, + short_url, template, published_page, include_members, include_coupons) + VALUES ( + $headlineParams $memberParams :keyword, :meta_title, + :meta_description, :navigation_name, :parent, + :paragraph_links, :short_url, :template, :published_page, :include_members, :include_coupons)"; + + $paragraphSql = " + INSERT INTO paragraphs_draft ( + active, title, description, image, caption, page) + VALUES ( + true, :title, :description, :image, :caption, :page)"; + + try { + $this->dbh->beginTransaction(); + + $pageStmt = $this->dbh->prepare($pageSql); + $this->setPageVars($pageStmt, $data); + $pageStmt->bindParam(':published_page', $data['published_page']); + $pageStmt->execute(); + + $row = $this->dbh + ->query('select id from pages_draft order by id desc limit 1') + ->fetch(PDO::FETCH_ASSOC); + + if (defined('MEMBERS_DB') && MEMBERS_DB) { + $this->_updateMemberCategories( + $data['member_categories'], + $row['id'] + ); + } + + if (defined('COUPONS') && COUPONS) { + $this->_updateCouponCategories( + $data['coupon_categories'], + $row['id'] + ); + $this->_updateMemberCities( + $data['member_regions'], + $row['id'] + ); + } + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->bindParam(':page', $row['id']); + $paragraphStmt->execute(); + + $this->dbh->commit(); + + return $row['id']; + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to insert page draft [$content]" + ); + } + } + + // }}} + + // {{{ update() + + public function update(array $data, $id) + { + if ($this->hasHeadlines()) { + $headlineColumns = ' + headline = :headline, + headline_intro = :headline_intro, '; + } + + if ($this->hasMemberDb()) { + $memberColumns = ' + include_member_map = :include_member_map, + search_form = :search_form, '; + } + + $pageSql = " + UPDATE pages_draft + SET $headlineColumns + $memberColumns + keyword = :keyword, + meta_title = :meta_title, + meta_description = :meta_description, + navigation_name = :navigation_name, + parent = :parent, + paragraph_links = :paragraph_links, + short_url = :short_url, + template = :template, + include_members = :include_members, + include_coupons = :include_coupons + WHERE id = :id"; + + $paragraphSql = " + UPDATE paragraphs_draft + SET title = :title, + description = :description, + image = :image, + caption = :caption + WHERE page = :page + AND pos = 1"; + + try { + $this->dbh->beginTransaction(); + + $pageStmt = $this->dbh->prepare($pageSql); + $this->setPageVars($pageStmt, $data); + $pageStmt->bindParam(':id', $id, PDO::PARAM_INT); + $pageStmt->execute(); + + if (defined('MEMBERS_DB') && MEMBERS_DB) { + $this->_updateMemberCategories($data['member_categories'], $id); + $this->_updateMemberCities($data['member_regions'], $id); + } + if (defined('COUPONS') && COUPONS) { + $this->_updateCouponCategories($data['coupon_categories'], $id); + } + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->bindParam(':page', $id); + $paragraphStmt->execute(); + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to update page draft [$content]" + ); + } + } + + // }}} + + // {{{ _updateMemberCategories() + + private function _updateMemberCategories(array $data = null, $id) + { + $deleteCatsSql = " + DELETE FROM member_categories2toolbox_pages_draft + WHERE page = :id"; + $delStmt = $this->dbh->prepare($deleteCatsSql); + $delStmt->bindParam(':id', $id, PDO::PARAM_INT); + $delStmt->execute(); + + if (is_array($data)) { + $insertCatsSql = " + INSERT INTO member_categories2toolbox_pages_draft (page, category) + VALUES (:page, :category)"; + $insStmt = $this->dbh->prepare($insertCatsSql); + $insStmt->bindParam(':page', $id, PDO::PARAM_INT); + foreach ($data as $category) { + $insStmt->bindParam(':category', $category, PDO::PARAM_INT); + $insStmt->execute(); + } + } + } + + // }}} + // {{{ getMemberCategoriesForPage() + + protected function getMemberCategoriesForPage($id) + { + try { + $sql = " + SELECT * + FROM member_categories2toolbox_pages_draft + WHERE page = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $categories = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $categories[] = $row['category']; + } + + return $categories; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch member categories for page draft `$id`" + ); + } + } + + // }}} + + // {{{ _updateMemberCities() + + private function _updateMemberCities(array $data = null, $id) + { + $deleteCitiesSql = " + DELETE FROM member_regions2toolbox_pages_draft + WHERE page = :id"; + $delStmt = $this->dbh->prepare($deleteCitiesSql); + $delStmt->bindParam(':id', $id, PDO::PARAM_INT); + $delStmt->execute(); + + if (is_array($data)) { + $insertCitiesSql = " + INSERT INTO member_regions2toolbox_pages_draft (page, region) + VALUES (:page, :region)"; + $insStmt = $this->dbh->prepare($insertCitiesSql); + $insStmt->bindParam(':page', $id, PDO::PARAM_INT); + foreach ($data as $region) { + $insStmt->bindParam(':region', $region, PDO::PARAM_INT); + $insStmt->execute(); + } + } + } + + // }}} + // // {{{ getMemberRegionsForPage() + + protected function getMemberRegionsForPage($id) + { + try { + $sql = " + SELECT * + FROM member_regions2toolbox_pages_draft + WHERE page = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $regions = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $regions[] = $row['region']; + } + + return $regions; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch member regions for page `$id`" + ); + } + } + + // }}} + // {{{ getMemberCitiesForPage() + + protected function getMemberCitiesForPage($id) + { + try { + $sql = " + SELECT * + FROM member_regions2toolbox_pages_draft + WHERE page = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $regions = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $regions[] = $row['region']; + } + + return $regions; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch member regions for page `$id`" + ); + } + } + + // }}} + + // {{{ _updateCouponCategories() + + private function _updateCouponCategories(array $data = null, $id) + { + $deleteCatsSql = " + DELETE FROM coupon_categories2toolbox_pages_draft + WHERE page = :id"; + $delStmt = $this->dbh->prepare($deleteCatsSql); + $delStmt->bindParam(':id', $id, PDO::PARAM_INT); + $delStmt->execute(); + + if (is_array($data)) { + $insertCatsSql = " + INSERT INTO coupon_categories2toolbox_pages_draft (page, category) + VALUES (:page, :category)"; + $insStmt = $this->dbh->prepare($insertCatsSql); + $insStmt->bindParam(':page', $id, PDO::PARAM_INT); + foreach ($data as $category) { + $insStmt->bindParam(':category', $category, PDO::PARAM_INT); + $insStmt->execute(); + } + } + } + + // }}} + // {{{ getCouponCategoriesForPage() + + protected function getCouponCategoriesForPage($id) + { + try { + $sql = " + SELECT * + FROM coupon_categories2toolbox_pages_draft + WHERE page = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $categories = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $categories[] = $row['category']; + } + + return $categories; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch coupon categories for page draft `$id`" + ); + } + } + + // }}} + + // {{{ getPhotoGalleriesForPage() + + protected function getPhotoGalleriesForPage($id) + { + try { + $sql = " + SELECT pc.* + FROM photo_category pc + JOIN photo_category_bus pcb + ON (pc.id = pcb.photocat_id) + JOIN pages_draft pd + ON (pd.published_page = pcb.buscat_id) + WHERE pcb.buscat_id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $photoGalleries = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $photoGalleries[$row['id']] = $row['category']; + } + + return $photoGalleries; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch member categories for page `$id`" + ); + } + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/PageGatewayDraftFactory.php b/Toolkit/Toolbox/PageGatewayDraftFactory.php new file mode 100644 index 0000000..1375f78 --- /dev/null +++ b/Toolkit/Toolbox/PageGatewayDraftFactory.php @@ -0,0 +1,10 @@ +dbh); + } +} +?> diff --git a/Toolkit/Toolbox/PageGatewayPublish.php b/Toolkit/Toolbox/PageGatewayPublish.php new file mode 100644 index 0000000..6fdbf0f --- /dev/null +++ b/Toolkit/Toolbox/PageGatewayPublish.php @@ -0,0 +1,611 @@ +dbh->beginTransaction(); + + $this->dbh->query($createTableSql); + + $stmt = $this->dbh->prepare($pageSql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to delete subtree `$id`" + ); + } + } + + // }}} + + // {{{ find() + + public function find($id) + { + $pageSql = " + SELECT p1.*, p1.id AS page_id, p1.id AS published_page, + CASE p1.active + WHEN CAST(1 AS BOOLEAN) THEN 'active' + ELSE 'In-Active' + END AS active_alt, p2.title, p2.description, p2.image, p2.caption + FROM pages p1 + LEFT JOIN paragraphs p2 + ON p1.id = p2.page + WHERE p1.id = :id + AND (p2.pos = 1 OR p2.pos IS NULL)"; + + try { + return $this->findPage($id, $pageSql); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception("Unable to find page `$id`"); + } + } + + // }}} + public function findNavItem($id) + { + $sql = " + SELECT id,navigation_name,parent,short_url + FROM pages + WHERE id = :id"; + + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':id', + $id, + PDO::PARAM_INT + ); + $stmt->execute(); + return $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception("Unable to find page `$id`"); + } + } + // {{{ findAll() + + public function findAll() + { + try { + $sql = " + SELECT * + FROM pages + ORDER by parent, pos"; + + return $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + 'Error fetching all published pages' + ); + } + } + + // }}} + // {{{ findByKeyword() + + public function findByKeyword($keyword) + { + try { + $pageSql = " + SELECT id + FROM pages + WHERE keyword = :keyword"; + + $stmt = $this->dbh->prepare($pageSql); + $stmt->bindParam(':keyword', $keyword); + $stmt->execute(); + + // Bind by column number + $stmt->bindColumn(1, $id); + + $stmt->fetch(PDO::FETCH_ASSOC); + + return $this->findNavItem($id); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to find keyword `$keyword`" + ); + } + } + + // }}} + // {{{ findTopParent() + + public function findTopParent($pageId) + { + if (!filter_var($pageId, FILTER_VALIDATE_INT)) { + throw new runtimeException("Invalid pageId `$pageId` to fetch"); + } + + try { + $sql = " + SELECT parent,id + FROM pages + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $pageId, PDO::PARAM_INT); + $stmt->execute(); + + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (!$stmt->rowCount()) { + return false; + } + + if ($row['parent'] == '0') { + return $row['id']; + } else { + return $this->findTopParent($row['parent']); + } + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to find parent for page `$pageId`" + ); + } + } + + // }}} + + // {{{ insert() + + public function insert(array $data) + { + if ($this->hasHeadlines()) { + $headlineColumns = 'headline, headline_intro,'; + $headlineParams = ':headline, :headline_intro,'; + } + + if ($this->hasMemberDb()) { + $memberColumns = 'include_member_map, search_form, '; + $memberParams = ':include_member_map, :search_form, '; + } + + $pageSql = " + INSERT INTO pages ( + $headlineColumns $memberColumns keyword, meta_title, + meta_description, navigation_name, parent, paragraph_links, + short_url, template, include_members, include_coupons) + VALUES ( + $headlineParams $memberParams :keyword, :meta_title, + :meta_description, :navigation_name, :parent, + :paragraph_links, :short_url, :template, :include_members, :include_coupons)"; + + $paragraphSql = " + INSERT INTO paragraphs ( + active, title, description, image, caption, page) + VALUES ( + true, :title, :description, :image, :caption, :page)"; + + try { + $this->dbh->beginTransaction(); + + $pageStmt = $this->dbh->prepare($pageSql); + $this->setPageVars($pageStmt, $data); + $pageStmt->execute(); + + $row = $this->dbh + ->query('select id from pages order by id desc limit 1') + ->fetch(PDO::FETCH_ASSOC); + + if (defined('MEMBERS_DB') && MEMBERS_DB) { + $this->_updateMemberCategories( + $data['member_categories'], + $row['id'] + ); + $this->_updateMemberRegions( + $data['member_regions'], + $row['id'] + ); + } + + if (defined('COUPONS') && COUPONS) { + $this->_updateCouponCategories( + $data['coupon_categories'], + $row['id'] + ); + } + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->bindParam(':page', $row['id']); + $paragraphStmt->execute(); + + // for some reason when Jodie is adding new pages the page position + // get messed up maybe more than one person it adding or updating + // pages I don't know either way when adding in new pages + // we'll have to go through all pages that have the same + // parent and redo the page positions so they don't get off order + $sql = " + SELECT id,pos + FROM pages + WHERE parent = :parent + ORDER BY pos"; + $stmt = $this->dbh->prepare($sql); + $sql = " + UPDATE pages + SET pos = :pos + WHERE id = :id"; + $updatePositionOfPage = $this->dbh->prepare($sql); + $stmt->bindParam(':parent', $data['parent'], PDO::PARAM_INT); + $stmt->execute(); + $pos = 1; + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $updatePositionOfPage->bindParam( + ':id', + $row['id'], + PDO::PARAM_INT + ); + $updatePositionOfPage->bindParam( + ':pos', + $pos, + PDO::PARAM_INT + ); + $updatePositionOfPage->execute(); + ++$pos; + } + + $this->dbh->commit(); + + return $row['id']; + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to insert page [$content]" + ); + } + } + + // }}} + + // {{{ update() + + public function update(array $data, $id) + { + if ($this->hasHeadlines()) { + $headlineColumns = ' + headline = :headline, + headline_intro = :headline_intro, '; + } + + if ($this->hasMemberDb()) { + $memberColumns = ' + include_member_map = :include_member_map, + search_form = :search_form, '; + } + + try { + $this->dbh->beginTransaction(); + // need to know if we're moving this to another parent + $sql = " + SELECT parent, pos + FROM pages + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ":id", + $id, + PDO::PARAM_INT + ); + $stmt->execute(); + + // the old parent of the page + $oldData = $stmt->fetch(PDO::FETCH_ASSOC); + $oldParent = $oldData['parent']; + $oldPos = $oldData['pos']; + if ($data['parent'] != $oldParent) { + // adjust the old level to normal + $sql = " + UPDATE pages + SET pos = pos - 1 + WHERE pos > :pos + AND parent = :parent + "; + $preStmt = $this->dbh->prepare($sql); + $preStmt->bindParam( + ":parent", + $oldParent, + PDO::PARAM_INT + ); + $preStmt->bindParam( + ":pos", + $oldPos, + PDO::PARAM_INT + ); + $preStmt->execute(); + // if it is then get next position number for new parent + $sql = " + SELECT max(pos) + 1 + FROM pages + WHERE parent = :parent"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ":parent", + $data['parent'], + PDO::PARAM_INT + ); + $stmt->execute(); + $pos = $stmt->fetchColumn(); + } + + $pageSql = " + UPDATE pages + SET $headlineColumns + $memberColumns + keyword = :keyword, + meta_title = :meta_title, + meta_description = :meta_description, + navigation_name = :navigation_name, + parent = :parent, + paragraph_links = :paragraph_links, + short_url = :short_url, + template = :template , + include_members = :include_members, + include_coupons = :include_coupons"; + if ($pos) { + $pageSql .= ", pos = $pos "; + } + + $pageSql .= " + WHERE id = :id"; + + $paragraphSql = " + UPDATE paragraphs + SET title = :title, + description = :description, + image = :image, + caption = :caption + WHERE page = :page + AND pos = 1"; + + $pageStmt = $this->dbh->prepare($pageSql); + $this->setPageVars($pageStmt, $data); + $pageStmt->bindParam(':id', $id, PDO::PARAM_INT); + $pageStmt->execute(); + + if (defined('MEMBERS_DB') && MEMBERS_DB) { + $this->_updateMemberCategories($data['member_categories'], $id); + $this->_updateMemberRegions($data['member_regions'], $id); + } + if (defined('COUPONS') && COUPONS) { + $this->_updateCouponCategories($data['coupon_categories'], $id); + } + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->bindParam(':page', $id); + $paragraphStmt->execute(); + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to update page [$content]" + ); + } + } + + // }}} + + // {{{ _updateMemberCategories() + + private function _updateMemberCategories(array $data = null, $id) + { + $deleteCatsSql = " + DELETE FROM member_categories2toolbox_pages + WHERE page = :id"; + $delStmt = $this->dbh->prepare($deleteCatsSql); + $delStmt->bindParam(':id', $id, PDO::PARAM_INT); + $delStmt->execute(); + + if (is_array($data)) { + $insertCatsSql = " + INSERT INTO member_categories2toolbox_pages (page, category) + VALUES (:page, :category)"; + $insStmt = $this->dbh->prepare($insertCatsSql); + $insStmt->bindParam(':page', $id, PDO::PARAM_INT); + foreach ($data as $category) { + $insStmt->bindParam(':category', $category, PDO::PARAM_INT); + $insStmt->execute(); + } + } + } + + // }}} + // {{{ getMemberCategoriesForPage() + + protected function getMemberCategoriesForPage($id) + { + try { + $sql = " + SELECT * + FROM member_categories2toolbox_pages + WHERE page = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $categories = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $categories[] = $row['category']; + } + + return $categories; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch member categories for page `$id`" + ); + } + } + + // }}} + + // {{{ _updateMemberRegions() + + private function _updateMemberRegions(array $data = null, $id) + { + $deleteRegionsSql = " + DELETE FROM member_regions2toolbox_pages + WHERE page = :id"; + $delStmt = $this->dbh->prepare($deleteRegionsSql); + $delStmt->bindParam(':id', $id, PDO::PARAM_INT); + $delStmt->execute(); + + if (is_array($data)) { + $insertRegionsSql = " + INSERT INTO member_regions2toolbox_pages (page, region) + VALUES (:page, :region)"; + $insStmt = $this->dbh->prepare($insertRegionsSql); + $insStmt->bindParam(':page', $id, PDO::PARAM_INT); + foreach ($data as $region) { + $insStmt->bindParam(':region', $region, PDO::PARAM_INT); + $insStmt->execute(); + } + } + } + + // }}} + // {{{ getMemberRegionsForPage() + + protected function getMemberRegionsForPage($id) + { + try { + $sql = " + SELECT * + FROM member_regions2toolbox_pages + WHERE page = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $regions = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $regions[] = $row['region']; + } + + return $regions; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch member regions for page `$id`" + ); + } + } + + // }}} + + // {{{ _updateCouponCategories() + + private function _updateCouponCategories(array $data = null, $id) + { + $deleteCatsSql = " + DELETE FROM coupon_categories2toolbox_pages + WHERE page = :id"; + $delStmt = $this->dbh->prepare($deleteCatsSql); + $delStmt->bindParam(':id', $id, PDO::PARAM_INT); + $delStmt->execute(); + + if (is_array($data)) { + $insertCatsSql = " + INSERT INTO coupon_categories2toolbox_pages (page, category) + VALUES (:page, :category)"; + $insStmt = $this->dbh->prepare($insertCatsSql); + $insStmt->bindParam(':page', $id, PDO::PARAM_INT); + foreach ($data as $category) { + $insStmt->bindParam(':category', $category, PDO::PARAM_INT); + $insStmt->execute(); + } + } + } + + // }}} + // {{{ getCouponCategoriesForPage() + + protected function getCouponCategoriesForPage($id) + { + try { + $sql = " + SELECT * + FROM coupon_categories2toolbox_pages + WHERE page = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $categories = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $categories[] = $row['category']; + } + + return $categories; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch coupon categories for page `$id`" + ); + } + } + + // }}} + + // {{{ getPhotoGalleriesForPage() + + protected function getPhotoGalleriesForPage($id) + { + try { + $sql = " + SELECT pc.* + FROM photo_category pc + JOIN photo_category_bus pcb + ON (pc.id = pcb.photocat_id) + WHERE pcb.buscat_id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id); + $stmt->execute(); + + $photoGalleries = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $photoGalleries[$row['id']] = $row['category']; + } + + return $photoGalleries; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to fetch member categories for page `$id`" + ); + } + } + + // }}} +} diff --git a/Toolkit/Toolbox/PageGatewayPublishFactory.php b/Toolkit/Toolbox/PageGatewayPublishFactory.php new file mode 100644 index 0000000..7876931 --- /dev/null +++ b/Toolkit/Toolbox/PageGatewayPublishFactory.php @@ -0,0 +1,9 @@ +dbh); + } +} diff --git a/Toolkit/Toolbox/PagesTree.php b/Toolkit/Toolbox/PagesTree.php new file mode 100644 index 0000000..4492378 --- /dev/null +++ b/Toolkit/Toolbox/PagesTree.php @@ -0,0 +1,289 @@ +\n"; + protected $leafStart = "\n\t
    • \n"; + + protected $toolbox; + + // }}} + // {{{ getActiveBall() + + protected function getActiveBall(array $branch) + { + $key = array_key_exists('published_page', $branch) + ? 'published_page' + : 'id'; + $homePage = ($branch[$key] == HOME_ID); + $memberDbHomePage = (defined('MEMBERS_DB') + && MEMBERS_DB + && $branch[$key] == MEMBERS_ONLY_HOME_PAGE); + + if ($homePage || $memberDbHomePage) { + return 'Active Ball'; + } + + $activeFormat = ''; + $activeFormat .= $this->getActiveBallImage($branch); + $activeFormat .= ''; + + return sprintf( + $activeFormat, + $branch['id'], + BASE_URL . "admin/toolbox.php?id={$branch['id']}", + $branch['active_alt'] + ); + } + + // }}} + // {{{ getActiveMobileBall() + + protected function getActiveMobileBall(array $branch) + { + $key = array_key_exists('published_page', $branch) + ? 'published_page' + : 'id'; + $nonMobilePages + = (defined('NON_MOBILE_PAGES')) + ? unserialize(NON_MOBILE_PAGES) + : array(); + $nonMobilePages[] = HOME_ID; + if (defined('MEMBERS_DB') && MEMBERS_DB) { + $nonMobilePages[] = MEMBERS_ONLY_HOME_PAGE; + $nonMobilePages[] = MEMBERS_CATEGORY; + } + + if (in_array($branch[$key], $nonMobilePages)) { + return 'Active Ball'; + } + + $activeFormat = ''; + $activeFormat .= $this->getActiveMobileBallImage($branch); + $activeFormat .= ''; + + return sprintf( + $activeFormat, + $branch['id'], + BASE_URL . "admin/toolbox.php?id={$branch['id']}", + $branch['active_alt'] + ); + } + + // }}} + // {{{ _getMoveArrows() + + private function _getMoveArrows($branch) + { + $homePage = ($branch['id'] == HOME_ID); + $memberDbHomePage = (defined('MEMBERS_DB') + && MEMBERS_DB + && $branch['id'] == MEMBERS_ONLY_HOME_PAGE); + + if ($homePage || $memberDbHomePage) { + $format = '%s'; + + $up = sprintf( + $format, + GLM_APP_BASE_URL . "assets/icons/arrow_up.png", + 'Move Up Arrow' + ); + + $down = sprintf( + $format, + GLM_APP_BASE_URL . "assets/icons/arrow_down.png", + 'Move Down Arrow' + ); + } else { + $format = 'Move %s Arrow'; + + $up = sprintf( + $format, + GLM_APP_BASE_URL . "assets/icons/arrow_up.png", + 'Up', + 'Up' + ); + + $down = sprintf( + $format, + GLM_APP_BASE_URL . "assets/icons/arrow_down.png", + 'Down', + 'Down' + ); + } + + + return $up . $down; + } + + // }}} + + private function _getPositionSelect($branch)/*{{{*/ + { + $homePage = ($branch['id'] == HOME_ID); + $memberDbHomePage = (defined('MEMBERS_DB') + && MEMBERS_DB + && $branch['id'] == MEMBERS_ONLY_HOME_PAGE); + if ($homePage || $memberDbHomePage) { + return ''; + } else { + $addClass + = ($branch['parent'] == 0 || $branch['parent'] == MEMBERS_CATEGORY) + ? 'pos-select parent-level-sel' + : 'pos-select'; + $showOn + = ($_GET['showpos']) + ? 'display:' + : 'display:none;'; + return ''; + } + }/*}}}*/ + + // {{{ createTree() + + protected function createTree(array $tree, $leaf, $level = 0) + { + $html = !$level ? $this->rootNodeStart : $this->subTreeStart; + + if ($level == 0) { + $lockMainNavPages = $this->config + ->getItem('section', 'conf') + ->getItem('directive', 'lockMainNavPages') + ->getContent(); + } else { + $lockMainNavPages = false; + } + + if (is_array($leaf) && !empty($leaf)) { + while (list($parent, $branch) = each($leaf)) { + if ($branch['id'] == HOME_ID) { + $html .= sprintf($this->leafStart, $branch['id'], 'rel="root"'); + } else { + $html .= sprintf($this->leafStart, $branch['id'], null); + } + if ( defined('MEMBERS_CATEGORY') + && MEMBERS_CATEGORY + && $branch['parent'] == MEMBERS_CATEGORY + ) { + $memberOnlyBase = BASE_URL . "members-only-area/"; + switch ($branch['id']) { + case MEMBERS_PROFILE_FORM_PAGE : + $previewUrl = $memberOnlyBase + . "?rt=EditProfile&tab=info"; + break; + case MEMBERS_COUPONS_PAGE : + $previewUrl = $memberOnlyBase + . "?rt=Coupons&page_id={$branch['id']}"; + break; + case MEMBERS_EVENTS_PAGE : + $previewUrl = $memberOnlyBase + . "?rt=Events&page_id={$branch['id']}"; + break; + case MEMBERS_LEADS_PAGE : + $previewUrl = $memberOnlyBase + . "?rt=Leads&page_id={$branch['id']}"; + break; + case MEMBERS_REPORTS_PAGE : + $previewUrl = $memberOnlyBase + . "?rt=Reports&page_id={$branch['id']}"; + break; + case MEMBERS_ADD_JOB_PAGE : + $previewUrl = $memberOnlyBase + . "?rt=Jobs&ac=addJob&page_id={$branch['id']}"; + break; + case MEMBERS_SHOW_JOBS_PAGE : + $previewUrl = $memberOnlyBase + . "?rt=Jobs&page_id={$branch['id']}"; + break; + default: + $previewUrl = $memberOnlyBase + . "?page_id={$branch['id']}"; + break; + } + + } else { + $previewUrl = BASE_URL . "index.php?catid={$branch['id']}&preview=1"; + } + + $html .= '
      '; + + $html .= 'Top +Section '; + $html .= 'Paragraphs '; + $html .= '[Preview] '; + if (!$lockMainNavPages) { + $html .= $this->getActiveBall($branch); + if (defined("MOBILE_SITE") && MOBILE_SITE) { + $html .= $this->getActiveMobileBall($branch); + } + $html .= $this->_getPositionSelect($branch); + } + + $html .= '
      '; + $html .= "{$branch['navigation_name']}"; + + if ($tree[$parent]) { + $html .= $this->createTree($tree, $tree[$parent], $level + 1); + } else { + $html .= $this->leafEnd; + } + } + } + + $html .= $this->treeEnd; + if ($level) { + $html .= $this->leafEnd; + } + return $html; + } + + // }}} + + // {{{ fetchContent() + + protected function fetchContent(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $pages = $gateway->findAll(); + if (is_array($pages)) { + $threads = array(); + foreach ($pages as $page) { + if (!empty($page['keyword'])) { + $page['navigation_name'] .= ' {' . $page['keyword'] . '}'; + } + $page['active_alt'] = $page['active'] ? 'On' : 'Off'; + $page['children'] = array(); + $threads[] = $page; + } + + $children = array(); + while (list($key, $value) = each ($threads)) { + $children[$value['parent']][$value['id']] = $value; + } + + $this->tree = $children; + } else { + $this->tree = array(); + } + } + + // }}} + + // {{{ toHtml() + + public function toHtml(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $GLOBALS['bottomScripts'][] = BASE_URL . 'Toolkit/Toolbox/libjs/pagesTree.js'; + $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js'; + $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/lib/jquery.cookie.js'; + $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/plugins/jquery.tree.cookie.js'; + + $this->fetchContent($gateway); + $html = parent::toHtml(); + + return "
      $html
      "; + } + + // }}} +} diff --git a/Toolkit/Toolbox/ParagraphBreadCrumbs.php b/Toolkit/Toolbox/ParagraphBreadCrumbs.php new file mode 100644 index 0000000..043c760 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphBreadCrumbs.php @@ -0,0 +1,46 @@ +{$page['navigation_name']}"; + } + + // }}} + // {{{ getPath() + + /** + * @return the $path + */ + public function getPath() + { + $id = $this->id; + $stack = array(); + do { + $page = $this->getPage($id); + + $stack[] = $this->getPageUri($page); + $id = $page['parent']; + } while ($id != 0); + + $reverse = array_reverse($stack); + + if (filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $uri = BASE_URL . "admin/toolbox.php?rt=Paragraphs&pageid={$this->id}"; + $reverse[] = "Paragraphs"; + } + + $this->path = implode(' > ', $reverse); + + return $this->path; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphDraftBreadCrumbs.php b/Toolkit/Toolbox/ParagraphDraftBreadCrumbs.php new file mode 100644 index 0000000..8d50e46 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphDraftBreadCrumbs.php @@ -0,0 +1,80 @@ +{$page['navigation_name']}"; + } + + // }}} + // {{{ getDraft() + + protected function getDraft($id) + { + try { + $sql = " + SELECT * + FROM pages_draft + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + return $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Could not fetch parent for page `$id`" + ); + } + } + + // }}} + // {{{ getPath() + + /** + * @return the $path + */ + public function getPath() + { + $draft = $this->getDraft($this->id); + + if (filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) { + $uri = BASE_URL . "admin/toolbox.php?rt=ParagraphsDraft&pageid={$this->id}"; + $stack = array("Paragraphs"); + } + + if (is_array($stack)) { + $stack[] = $this->getPageUri($draft); + } else { + $stack = array($draft['navigation_name']); + } + + $publishedPage = $this->getPage($draft['published_page']); + $id = $publishedPage['parent']; + while ($id != 0) { + $page = $this->getPage($id); + + $stack[] = $this->getPageUri($page); + $id = $page['parent']; + } + + $reverse = array_reverse($stack); + + $this->path = implode(' > ', $reverse); + + return $this->path; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphGatewayAbstract.php b/Toolkit/Toolbox/ParagraphGatewayAbstract.php new file mode 100644 index 0000000..58cb303 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphGatewayAbstract.php @@ -0,0 +1,49 @@ +bindParam(':active', $data['active'], PDO::PARAM_BOOL); + $stmt->bindParam(':title', $data['title']); + $stmt->bindParam(':description', $data['description']); + $stmt->bindParam(':image', $data['image']); + $stmt->bindParam(':caption', $data['caption']); + $stmt->bindParam(':page', $data['page']); + $stmt->bindParam(':back_to_top', $data['back_to_top'], PDO::PARAM_BOOL); + } + + // }}} + // {{{ setFileVars() + + protected function setFileVars(PDOStatement &$stmt, $data, $key) + { + $stmt->bindParam(':filename', $data['filename'][$key]); + $stmt->bindParam(':bytes', $data['bytes'][$key]); + $stmt->bindParam(':urltext', $data['urltext'][$key]); + if ($data['type'][$key] != DIRECTORY_SEPARATOR) { + $stmt->bindParam(':type', $data['type'][$key]); + } else { + $pieces = explode('.', $data['filename'][$key]); + $extension = end($pieces); + $stmt->bindParam(':type', $extension); + } + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphGatewayDraft.php b/Toolkit/Toolbox/ParagraphGatewayDraft.php new file mode 100644 index 0000000..dd07c58 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphGatewayDraft.php @@ -0,0 +1,225 @@ +dbh->prepare($pageSql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to delete paragraph draft `$id`" + ); + } + } + + // }}} + + // {{{ find() + + public function find($id) + { + $paragraphSql = " + SELECT * + FROM paragraphs_draft + WHERE id = :id "; + + $fileSql = " + SELECT * + FROM files_draft + WHERE paragraph = :paragraph + ORDER BY pos"; + + try { + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $paragraphStmt->bindParam(':id', $id, PDO::PARAM_INT); + $paragraphStmt->execute(); + + $paragraph = $paragraphStmt->fetch(PDO::FETCH_ASSOC); + + if (!empty($paragraph['image'])) { + $imgFormat = ""; + $paragraph['current_image_original'] + = sprintf($imgFormat, TOOLBOX_ORIGINAL); + $paragraph['current_image_resized'] + = sprintf($imgFormat, TOOLBOX_RESIZED); + $paragraph['current_image_midsized'] + = sprintf($imgFormat, TOOLBOX_MIDSIZED); + $paragraph['current_image_thumb'] + = sprintf($imgFormat, TOOLBOX_THUMB); + } else { + $paragraph['current_image_original'] = 'Image not yet uploaded'; + $paragraph['current_image_resized'] = 'Image not yet uploaded'; + $paragraph['current_image_midsized'] = 'Image not yet uploaded'; + $paragraph['current_image_thumb'] = 'Image not yet uploaded'; + } + + $fileStmt = $this->dbh->prepare($fileSql); + $fileStmt->bindParam(':paragraph', $id, PDO::PARAM_INT); + $fileStmt->execute(); + + $paragraph['files'] = $fileStmt->fetchAll(PDO::FETCH_ASSOC); + + return $paragraph; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to find paragraph draft `$id`" + ); + } + } + + // }}} + // {{{ findAll() + + public function findAll($page) + { + try { + $sql = " + SELECT * + FROM paragraphs_draft + WHERE page = :page + AND pos > 1 + ORDER BY pos"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':page', $page); + $stmt->execute(); + + $paragraphs = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $paragraphs[] = $this->find($row['id']); + } + + return $paragraphs; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Error fetching all paragraph drafts for page `$page`" + ); + } + } + + // }}} + + // {{{ insert() + + public function insert(array $data) + { + $paragraphSql = " + INSERT INTO paragraphs_draft (active, back_to_top, title, + description, image, caption, page) + VALUES (:active, :back_to_top, :title, :description, :image, + :caption, :page)"; + + $filesInsertSql = " + INSERT INTO files_draft (filename, bytes, type, urltext, paragraph) + VALUES (:filename, :bytes, :type, :urltext, :paragraph)"; + + try { + $this->dbh->beginTransaction(); + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->execute(); + + $row = $this->dbh + ->query('select id from paragraphs_draft order by id desc limit 1') + ->fetch(PDO::FETCH_ASSOC); + + if ( isset($data['uploaded_files']) + && is_array($data['uploaded_files']) + ) { + $fileInsertStmt = $this->dbh->prepare($filesInsertSql); + $fileInsertStmt->bindParam(':paragraph', $row['id']); + $length = count($data['uploaded_files']['type']); + for ($i = 0; $i < $length; ++$i) { + $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i); + $fileInsertStmt->execute(); + } + } + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to insert paragraph draft [$content]" + ); + } + } + + // }}} + + // {{{ update() + + public function update(array $data, $id) + { + $paragraphSql = " + UPDATE paragraphs_draft + SET back_to_top = :back_to_top, + active = :active, + title = :title, + description = :description, + image = :image, + caption = :caption, + page = :page + WHERE id = :id"; + + $filesDeleteSql = " + DELETE FROM files_draft + WHERE paragraph = :id"; + + $filesInsertSql = " + INSERT INTO files_draft (filename, bytes, type, urltext, paragraph) + VALUES (:filename, :bytes, :type, :urltext, :paragraph)"; + + try { + $this->dbh->beginTransaction(); + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->bindParam(':id', $id); + $paragraphStmt->execute(); + + $filesDeleteStmt = $this->dbh->prepare($filesDeleteSql); + $filesDeleteStmt->bindParam(':id', $id); + $filesDeleteStmt->execute(); + + if ( isset($data['uploaded_files']) + && is_array($data['uploaded_files']) + ) { + $fileInsertStmt = $this->dbh->prepare($filesInsertSql); + $fileInsertStmt->bindParam(':paragraph', $id); + $length = count($data['uploaded_files']['type']); + for ($i = 0; $i < $length; ++$i) { + $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i); + $fileInsertStmt->execute(); + } + } + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to update paragraph draft [$content]" + ); + } + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphGatewayDraftFactory.php b/Toolkit/Toolbox/ParagraphGatewayDraftFactory.php new file mode 100644 index 0000000..f02720e --- /dev/null +++ b/Toolkit/Toolbox/ParagraphGatewayDraftFactory.php @@ -0,0 +1,10 @@ +dbh); + } +} +?> diff --git a/Toolkit/Toolbox/ParagraphGatewayPublish.php b/Toolkit/Toolbox/ParagraphGatewayPublish.php new file mode 100644 index 0000000..1621ab2 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphGatewayPublish.php @@ -0,0 +1,293 @@ +dbh->prepare($pageSql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to delete paragraph `$id`" + ); + } + } + + // }}} + + // {{{ find() + + public function find($id) + { + $paragraphSql = " + SELECT * + FROM paragraphs + WHERE id = :id "; + + $fileSql = " + SELECT id,filename,bytes,type, + coalesce(urltext,filename,'empty') as urltext, + paragraph,pos + FROM files + WHERE paragraph = :paragraph + ORDER BY pos"; + + try { + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $paragraphStmt->bindParam(':id', $id, PDO::PARAM_INT); + $paragraphStmt->execute(); + + $paragraph = $paragraphStmt->fetch(PDO::FETCH_ASSOC); + + if (!empty($paragraph['image'])) { + $imgFormat = ""; + $paragraph['current_image_original'] + = sprintf($imgFormat, TOOLBOX_ORIGINAL); + $paragraph['current_image_resized'] + = sprintf($imgFormat, TOOLBOX_RESIZED); + $paragraph['current_image_midsized'] + = sprintf($imgFormat, TOOLBOX_MIDSIZED); + $paragraph['current_image_thumb'] + = sprintf($imgFormat, TOOLBOX_THUMB); + } else { + $paragraph['current_image_original'] = 'Image not yet uploaded'; + $paragraph['current_image_resized'] = 'Image not yet uploaded'; + $paragraph['current_image_midsized'] = 'Image not yet uploaded'; + $paragraph['current_image_thumb'] = 'Image not yet uploaded'; + } + + $fileStmt = $this->dbh->prepare($fileSql); + $fileStmt->bindParam(':paragraph', $id, PDO::PARAM_INT); + $fileStmt->execute(); + + $paragraph['files'] = $fileStmt->fetchAll(PDO::FETCH_ASSOC); + + return $paragraph; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Unable to find paragraph `$id`" + ); + } + } + + // }}} + // {{{ findAll() + + public function findAll($page) + { + try { + $sql = " + SELECT * + FROM paragraphs + WHERE page = :page + AND pos > 1 + ORDER BY pos"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':page', $page); + $stmt->execute(); + + $paragraphs = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $paragraphs[] = $this->find($row['id']); + } + + return $paragraphs; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Toolbox_Exception( + "Error fetching all paragraphs for page `$page`" + ); + } + } + + // }}} + + // {{{ insert() + + public function insert(array $data) + { + // add the part where it throw the file to the server + // and returns the data for it + if (is_array($_FILES['filename']) && $_FILES['filename']['error'] == 0) { + $fs = new Toolkit_FileServer_FileAdapter(); + try { + if ($res = $fs->upload('filename')) { + $data['uploaded_files']['filename'][] = $res['name']; + $data['uploaded_files']['urltext'][] + = ($data['fileurltext']) + ? $data['fileurltext'] + : $_FILES['filename']['name']; + $data['uploaded_files']['bytes'][] = $res['size']; + $data['uploaded_files']['type'][] = $res['type']; + } + + } catch (Toolkit_FileServer_Exception $e) { + Toolkit_Logger::logException('File Server', $e); + echo -1; // Don't return "false", it will mess up the JS plugin. + return; + } + } + $paragraphSql = " + INSERT INTO paragraphs (active, back_to_top, title, description, + image, caption, page) + VALUES (:active, :back_to_top, :title, :description, :image, + :caption, :page)"; + + $filesInsertSql = " + INSERT INTO files (filename, bytes, type, urltext, paragraph) + VALUES (:filename, :bytes, :type, :urltext, :paragraph)"; + + try { + $this->dbh->beginTransaction(); + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->execute(); + + $row = $this->dbh + ->query('select id from paragraphs order by id desc limit 1') + ->fetch(PDO::FETCH_ASSOC); + + if ( isset($data['uploaded_files']) + && is_array($data['uploaded_files']) + ) { + $fileInsertStmt = $this->dbh->prepare($filesInsertSql); + $fileInsertStmt->bindParam(':paragraph', $row['id']); + $length = count($data['uploaded_files']['type']); + for ($i = 0; $i < $length; ++$i) { + $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i); + $fileInsertStmt->execute(); + } + } + + $this->dbh->commit(); + return $row['id']; + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to insert paragraph [$content]" + ); + } + } + + // }}} + + // {{{ update() + + public function update(array $data, $id) + { + if (is_array($data['deleteFile'])) { + foreach ($data['deleteFile'] as $fileNameToDelete) { + $delKey = array_search( + $fileNameToDelete, + $data['uploaded_files']['filename'] + ); + unset( + $data['uploaded_files']['urltext'][$delKey], + $data['uploaded_files']['filename'][$delKey], + $data['uploaded_files']['bytes'][$delKey], + $data['uploaded_files']['type'][$delKey] + ); + } + } + + // add the part where it throw the file to the server + // and returns the data for it + if (is_array($_FILES['filename']) && $_FILES['filename']['error'] == 0) { + $fs = new Toolkit_FileServer_FileAdapter(); + try { + if ($res = $fs->upload('filename')) { + $data['uploaded_files']['filename'][] = $res['name']; + $data['uploaded_files']['urltext'][] + = ($data['fileurltext']) + ? $data['fileurltext'] + : $_FILES['filename']['name']; + $data['uploaded_files']['bytes'][] = $res['size']; + $data['uploaded_files']['type'][] = $res['type']; + } + + } catch (Toolkit_FileServer_Exception $e) { + Toolkit_Logger::logException('File Server', $e); + echo -1; // Don't return "false", it will mess up the JS plugin. + return; + } + } + //echo '
      '.print_r($data, true).'
      '; + //exit; + unset( + $data['deleteFile'], + $data['fileurltext'] + ); + + $paragraphSql = " + UPDATE paragraphs + SET back_to_top = :back_to_top, + active = :active, + title = :title, + description = :description, + image = :image, + caption = :caption, + page = :page + WHERE id = :id"; + + $filesDeleteSql = " + DELETE FROM files + WHERE paragraph = :id"; + + $filesInsertSql = " + INSERT INTO files (filename, bytes, type, urltext, paragraph) + VALUES (:filename, :bytes, :type, :urltext, :paragraph)"; + + try { + $this->dbh->beginTransaction(); + + $paragraphStmt = $this->dbh->prepare($paragraphSql); + $this->setParagraphVars($paragraphStmt, $data); + $paragraphStmt->bindParam(':id', $id); + $paragraphStmt->execute(); + + $filesDeleteStmt = $this->dbh->prepare($filesDeleteSql); + $filesDeleteStmt->bindParam(':id', $id); + $filesDeleteStmt->execute(); + + if ( isset($data['uploaded_files']) + && is_array($data['uploaded_files']) + ) { + $fileInsertStmt = $this->dbh->prepare($filesInsertSql); + $fileInsertStmt->bindParam(':paragraph', $id); + $length = count($data['uploaded_files']['type']); + $fileArrayKeys = array_keys($data['uploaded_files']['type']); + foreach ($fileArrayKeys as $i) { + $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i); + $fileInsertStmt->execute(); + } + } + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + Toolkit_Logger::logException('DB Error', $e); + $content = serialize($data); + throw new Toolkit_Toolbox_Exception( + "Unable to update paragraph [$content]" + ); + } + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphGatewayPublishFactory.php b/Toolkit/Toolbox/ParagraphGatewayPublishFactory.php new file mode 100644 index 0000000..3e7083c --- /dev/null +++ b/Toolkit/Toolbox/ParagraphGatewayPublishFactory.php @@ -0,0 +1,10 @@ +dbh); + } +} +?> diff --git a/Toolkit/Toolbox/ParagraphsController.php b/Toolkit/Toolbox/ParagraphsController.php new file mode 100644 index 0000000..05d59cd --- /dev/null +++ b/Toolkit/Toolbox/ParagraphsController.php @@ -0,0 +1,315 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Toolkit_Toolbox_ParagraphsController + * + * Description for Toolkit_Toolbox_ParagraphsController + * + * @category Toolkit + * @package Toolbox + * @author Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +class Toolkit_Toolbox_ParagraphsController + extends Toolkit_BaseControllerAbstract implements Toolkit_IController +{ + // {{{ _getForm() + + /** + * Description for _getForm() + * + * @return \Toolkit_Toolbox_Forms_EditParagraph + * @access private + */ + private function _getForm() + { + // Need three separate objects otherwise, new parses overwrite existing + // root variable data. + $tlbConf = new Config; + $memConf = new Config; + $cpnConf = new Config; + + $memRoot =& $memConf->parseConfig( + BASE . 'Toolkit/Members/config.ini', + 'IniFile' + ); + $cpnRoot =& $cpnConf->parseConfig( + BASE . 'Toolkit/Coupons/config.ini', + 'IniFile' + ); + $tbxRoot =& $tlbConf->parseConfig( + BASE . 'Toolkit/Toolbox/config.ini', + 'IniFile' + ); + + $form = new Toolkit_Toolbox_Forms_EditParagraph( + 'edit_paragraph', + 'post', + BASE_URL . 'admin/toolbox.php?rt=Paragraphs&ac=process' + ); + $form->configureForm( + $this->registry->dbh, + new Toolkit_Toolbox_ParagraphGatewayPublishFactory($this->registry->dbh), + new Toolkit_FileServer_ImageAdapter(), + new Toolkit_FileServer_FileAdapter(), + new Toolkit_Toolbox_FileExtension + ); + + return $form; + } + + // }}} + + // {{{ editAction() + + /** + * Description for editAction() + * + * @return string + * @access public + */ + public function editAction() + { + if (ctype_digit($_GET['pageid'])) { + $breadCrumbs = new Toolkit_Toolbox_ParagraphBreadCrumbs( + $this->registry->dbh, + $_GET['pageid'] + ); + $html = (string) $breadCrumbs; + } + + $form = $this->_getForm(); + $html .= $form->toHtml($this->registry->dbh); + + return $html; + } + + // }}} + + // {{{ indexAction() + + /** + * Description for indexAction() + * + * @return string + * @throws Toolkit_Toolbox_Exception + * @throws RuntimeException + * @access public + */ + public function indexAction() + { + if (ctype_digit($_GET['pageid'])) { + $breadCrumbs = new Toolkit_Toolbox_ParagraphBreadCrumbs( + $this->registry->dbh, + $_GET['pageid'] + ); + $html = (string) $breadCrumbs; + } + + try { + if (!ctype_digit($_GET['pageid'])) { + throw new RuntimeException( + "Category id `{$_GET['pageid']}` is not an integer" + ); + } + + $toolboxConfig = new Config; + $toolboxConfigRoot =& $toolboxConfig->parseConfig( + BASE . 'Toolkit/Toolbox/config.ini', + 'IniFile' + ); + $tree = new Toolkit_Toolbox_ParagraphsTree($toolboxConfigRoot); + $html .= $tree->toHtml( + new Toolkit_Toolbox_ParagraphGatewayPublish($this->registry->dbh) + ); + + return $html; + } catch (RuntimeException $e) { + Toolkit_Logger::logException('Runtime Error', $e); + throw new Toolkit_Toolbox_Exception( + 'Category id must be an integer' + ); + } + } + + // }}} + + // {{{ processAction() + + /** + * Description for processAction() + * + * @return string + * @access public + */ + public function processAction() + { + $form = $this->_getForm(); + + if ($form->isSubmitted()) { + if ($form->getSubmitValue('cancel')) { + // do nothing + $pageid = $form->getSubmitValue('page'); + header('Location: ' . BASE_URL . "admin/toolbox.php?rt=Paragraphs&pageid=$pageid"); + exit(); + } elseif ($form->getSubmitValue('previewParagraph')) { + } elseif ($form->getSubmitValue('saveParagraph')) { + // save paragraph + $gateway = new Toolkit_Toolbox_ParagraphGatewayPublish($this->registry->dbh); + + if ($form->validate()) { + $paragraphId = $form->getSubmitValue('id'); + if ($paragraphId) { + // before we update this paragraph need to remove the cache + try { + $sql = " + SELECT page + FROM paragraphs + WHERE id = :id"; + $paraStmt = $this->registry + ->dbh + ->prepare($sql); + $paraStmt->bindParam(':id', $paragraphId, PDO::PARAM_INT); + $paraStmt->execute(); + $oldPageId = $paraStmt->fetchColumn(); + if ($oldPageId) { + $cache = new Cache_Lite($GLOBALS['cacheOptions']); + $cache->remove("page-$oldPageId", 'Toolbox'); + $cache->remove("paragraphs-$oldPageId", 'Toolbox'); + $cache->remove("sectionLinks-$oldPageId", 'Toolbox'); + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + + $gateway->update($form->getSubmitValues(), $paragraphId); + } else { + $paragraphId = $gateway->insert($form->getSubmitValues()); + } + $pageid = $form->getSubmitValue('page'); + try { + $deleteFile = $form->getSubmitValue('deleteFile'); + if (is_array($deleteFile) && !empty($deleteFile)) { + $fs = new Toolkit_FileServer_FileAdapter(); + foreach ($deleteFile as $delFile) { + $fs->delete($delFile); + } + } + $image = $form->getSubmitValue('image'); + if ($form->getSubmitValue('remove_image') == '1' + && $image + ) { + $is = new Toolkit_FileServer_ImageAdapter(); + $is->delete($image); + } + } catch(Toolkit_FileServer_Exception $fileError) { + Toolkit_Common::handleError($fileError); + } + + $cache = new Cache_Lite($GLOBALS['cacheOptions']); + $cache->remove("page-$pageid", 'Toolbox'); + $cache->remove("paragraphs-$pageid", 'Toolbox'); + $cache->remove("sectionLinks-$pageid", 'Toolbox'); + + header( + 'Location: ' + . BASE_URL + . "admin/toolbox.php?rt=Paragraphs" + . "&ac=edit&id={$paragraphId}&pageid={$pageid}&g=1" + ); + exit(); + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml($this->registry->dbh); + } + } elseif ($form->getSubmitValue('deleteParagraph')) { + try { + $files = $form->getSubmitValue('uploaded_files'); + $deleteFile = $files['filename']; + if (is_array($deleteFile) && !empty($deleteFile)) { + $fs = new Toolkit_FileServer_FileAdapter(); + foreach ($deleteFile as $delFile) { + $fs->delete($delFile); + } + } + $image = $form->getSubmitValue('image'); + if ($image) { + $is = new Toolkit_FileServer_ImageAdapter(); + $is->delete($image); + } + } catch(Toolkit_FileServer_Exception $fileError) { + Toolkit_Common::handleError($fileError); + } + // delete paragraph + $gateway = new Toolkit_Toolbox_ParagraphGatewayPublish($this->registry->dbh); + $gateway->delete($form->getSubmitValue('id')); + + $pageid = $form->getSubmitValue('page'); + + $cache = new Cache_Lite($GLOBALS['cacheOptions']); + $cache->remove("page-$pageid", 'Toolbox'); + $cache->remove("paragraphs-$pageid", 'Toolbox'); + $cache->remove("sectionLinks-$pageid", 'Toolbox'); + + $paragraphTitle = $form->getSubmitValue('title'); + $return = "[$paragraphTitle] successfully deleted."; + try { + $dbh = Toolkit_Database::getInstance(); + $sql = " + UPDATE paragraphs + SET pos = :pos + WHERE id = :id"; + $updateParagraphPos = $dbh->prepare($sql); + $sql = " + SELECT id,page,pos + FROM paragraphs + WHERE page = :page + ORDER BY page,pos"; + $res = $dbh->prepare($sql); + $res->bindParam(':page', $pageid, PDO::PARAM_INT); + $res->execute(); + while ($row = $res->fetch(PDO::FETCH_ASSOC)) { + $paragraphData[$row['page']][] = $row['id']; + } + if (is_array($paragraphData)) { + $curPage = 0; + $pos = 1; + foreach ($paragraphData as $page => $paragraphs) { + if ($curPage != $page) { + $curPage = $page; + $pos = 1; + } + foreach ($paragraphs as $paragraphId) { + $updateParagraphPos->bindParam(":pos", $pos, PDO::PARAM_INT); + $updateParagraphPos->bindParam(":id", $paragraphId, PDO::PARAM_INT); + $updateParagraphPos->execute(); + ++$pos; + } + } + } + } catch(PDOException $e) { + die($e->getMessage()); + } + } + } else { + $return = $form->toHtml($this->registry->dbh); + } + + return $return; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphsDraftController.php b/Toolkit/Toolbox/ParagraphsDraftController.php new file mode 100644 index 0000000..f105073 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphsDraftController.php @@ -0,0 +1,154 @@ +parseConfig( + BASE . 'Toolkit/Members/config.ini', + 'IniFile' + ); + $cpnRoot =& $cpnConf->parseConfig( + BASE . 'Toolkit/Coupons/config.ini', + 'IniFile' + ); + $tbxRoot =& $tlbConf->parseConfig( + BASE . 'Toolkit/Toolbox/config.ini', + 'IniFile' + ); + + $form = new Toolkit_Toolbox_Forms_EditParagraph( + 'edit_paragraph', + 'post', + BASE_URL . 'admin/toolbox.php?rt=ParagraphsDraft&ac=process' + ); + $form->configureForm( + $this->registry->dbh, + new Toolkit_Toolbox_ParagraphGatewayDraftFactory($this->registry->dbh), + new Toolkit_FileServer_ImageAdapter(), + new Toolkit_FileServer_FileAdapter(), + new Toolkit_Toolbox_FileExtension + ); + + return $form; + } + + // }}} + + // {{{ editAction() + + public function editAction() + { + if (ctype_digit($_GET['pageid'])) { + $breadCrumbs = new Toolkit_Toolbox_ParagraphDraftBreadCrumbs( + $this->registry->dbh, + $_GET['pageid'] + ); + $html = (string) $breadCrumbs; + } + + $form = $this->_getForm(); + $html .= $form->toHtml($this->registry->dbh); + + return $html; + } + + // }}} + + // {{{ indexAction() + + public function indexAction() + { + if (ctype_digit($_GET['pageid'])) { + $breadCrumbs = new Toolkit_Toolbox_ParagraphDraftBreadCrumbs( + $this->registry->dbh, + $_GET['pageid'] + ); + $html = (string) $breadCrumbs; + } + + try { + if (!ctype_digit($_GET['pageid'])) { + throw new RuntimeException( + "Category id `{$_GET['pageid']}` is not an integer" + ); + } + + $toolboxConfig = new Config; + $toolboxConfigRoot =& $toolboxConfig->parseConfig( + BASE . 'Toolkit/Toolbox/config.ini', + 'IniFile' + ); + $tree = new Toolkit_Toolbox_ParagraphsDraftTree($toolboxConfigRoot); + $html .= $tree->toHtml( + new Toolkit_Toolbox_ParagraphGatewayDraft($this->registry->dbh) + ); + + return $html; + } catch (RuntimeException $e) { + Toolkit_Logger::logException('Runtime Error', $e); + throw new Toolkit_Toolbox_Exception( + 'Category id must be an integer' + ); + } + } + + // }}} + + // {{{ processAction() + + public function processAction() + { + $form = $this->_getForm(); + + if ($form->isSubmitted()) { + if ($form->getSubmitValue('cancel')) { + // do nothing + $pageid = $form->getSubmitValue('page'); + header('Location: ' . BASE_URL . "admin/toolbox.php?rt=ParagraphsDraft&pageid=$pageid"); + exit(); + } elseif ($form->getSubmitValue('previewParagraph')) { + } elseif ($form->getSubmitValue('saveParagraph')) { + // save paragraph + $gateway = new Toolkit_Toolbox_ParagraphGatewayDraft($this->registry->dbh); + if ($form->validate()) { + $paragraphId = $form->getSubmitValue('id'); + if ($paragraphId) { + $gateway->update($form->getSubmitValues(), $paragraphId); + } else { + $gateway->insert($form->getSubmitValues()); + } + $pageid = $form->getSubmitValue('page'); + header('Location: ' . BASE_URL . "admin/toolbox.php?rt=ParagraphsDraft&pageid=$pageid"); + exit(); + } else { + $return = $form->getErrorMessage(); + $return .= $form->toHtml(); + } + } elseif ($form->getSubmitValue('deleteParagraph')) { + // delete paragraph + $gateway = new Toolkit_Toolbox_ParagraphGatewayDraft($this->registry->dbh); + $gateway->delete($form->getSubmitValue('id')); + + $paragraphTitle = $form->getSubmitValue('title'); + $return = "[$paragraphTitle] successfully deleted."; + } + } else { + $return = $form->toHtml(); + } + + return $return; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphsDraftTree.php b/Toolkit/Toolbox/ParagraphsDraftTree.php new file mode 100644 index 0000000..b35e504 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphsDraftTree.php @@ -0,0 +1,86 @@ +'; + $activeFormat .= $this->getActiveBallImage($branch); + $activeFormat .= ''; + + return sprintf( + $activeFormat, + BASE_URL . "admin/toolbox.php?rt=ParagraphsDraft&id={$_GET['id']}", + $branch['active_alt'] + ); + } + + // }}} + + // {{{ createTree() + + protected function createTree(array $tree, $leaf, $level = 0) + { + if (empty($leaf)) { + return '

      No paragraph drafts created for this page yet

      '; // page has no paragraphs + } + + $html = $this->rootNodeStart; + + while (list($parent, $branch) = each($leaf)) { + $html .= sprintf($this->leafStart, $branch['id'], null); + + $html .= "{$branch['title']}"; + $html .= '
      '; + $html .= '[Edit] '; + $html .= $this->getActiveBall($branch); + $html .= '
      '; + $html .= $this->leafEnd; + } + + $html .= $this->treeEnd; + return $html; + } + + // }}} + + // {{{ fetchContent() + + protected function fetchContent(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $paragraphs = $gateway->findAll($_GET['pageid']); + if (is_array($paragraphs)) { + $threads = array(); + foreach ($paragraphs as $paragraph) { + $threads[] = $paragraph; + } + + $children = array(); + while (list($key, $value) = each ($threads)) { + $children[0][$value['id']] = $value; + } + + $this->tree = $children; + } else { + $this->tree = array(); + } + } + + // }}} + // {{{ toHtml() + + public function toHtml(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $GLOBALS['bottomScripts'][] = BASE_URL . 'Toolkit/Toolbox/libjs/paragraph-tree.js'; + $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js'; + + $this->fetchContent($gateway); + $html = parent::toHtml(); + + return "
      $html
      "; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/ParagraphsTree.php b/Toolkit/Toolbox/ParagraphsTree.php new file mode 100644 index 0000000..baa3d54 --- /dev/null +++ b/Toolkit/Toolbox/ParagraphsTree.php @@ -0,0 +1,120 @@ +\n"; + // {{{ getActiveBall() + + protected function getActiveBall(array $branch) + { + $activeFormat = ''; + $activeFormat .= $this->getActiveBallImage($branch); + $activeFormat .= ''; + + return sprintf( + $activeFormat, + $branch['id'], + BASE_URL . "admin/toolbox.php?rt=Paragraphs&id={$branch['id']}", + $branch['active_alt'] + ); + } + + // }}} + // {{{ _getMoveArrows() + + private function _getMoveArrows() + { + $format = 'Move %s Arrow'; + + $up = sprintf( + $format, + GLM_APP_BASE_URL . "assets/icons/arrow_up.png", + 'Up', + 'Up' + ); + + $down = sprintf( + $format, + GLM_APP_BASE_URL . "assets/icons/arrow_down.png", + 'Down', + 'Down' + ); + + return $up . $down; + } + + // }}} + + private function _getPositionSelect($branch)/*{{{*/ + { + return ''; + }/*}}}*/ + // {{{ createTree() + + protected function createTree(array $tree, $leaf, $level = 0) + { + if (empty($leaf)) { + return '

      No paragraphs created for this page yet

      '; // page has no paragraphs + } + + $html = $this->rootNodeStart; + + while (list($parent, $branch) = each($leaf)) { + $html .= sprintf($this->leafStart, $branch['id'], null); + + $html .= '
      '; + $html .= '[Edit] '; + $html .= $this->getActiveBall($branch); + if (count($leaf) > 1) { + $html .= $this->_getPositionSelect($branch); + } + $html .= "{$branch['title']}"; + $html .= '
      '; + + $html .= $this->leafEnd; + } + + $html .= $this->treeEnd; + return $html; + } + + // }}} + + // {{{ fetchContent() + + protected function fetchContent(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $paragraphs = $gateway->findAll($_GET['pageid']); + if (is_array($paragraphs)) { + $threads = array(); + foreach ($paragraphs as $paragraph) { + $threads[] = $paragraph; + } + + $children = array(); + while (list($key, $value) = each ($threads)) { + $children[0][$value['id']] = $value; + } + + $this->tree = $children; + } else { + $this->tree = array(); + } + } + + // }}} + // {{{ toHtml() + + public function toHtml(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $GLOBALS['bottomScripts'][] = BASE_URL . 'Toolkit/Toolbox/libjs/paragraph-tree.js'; + $GLOBALS['bottomScripts'][] = GLM_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js'; + + $this->fetchContent($gateway); + $html = parent::toHtml(); + + return "
      $html
      "; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/SearchController.php b/Toolkit/Toolbox/SearchController.php new file mode 100644 index 0000000..066cbc1 --- /dev/null +++ b/Toolkit/Toolbox/SearchController.php @@ -0,0 +1,50 @@ +configureForm(); + + $html = $searchForm->toHtml(); + + $toolbox = new GLM_TEMPLATE( NULL ); + $sql = " + SELECT id, parent, pos, active, + CASE WHEN keyword IS NOT NULL AND keyword <> '' + THEN category || ' {' || keyword || '}' + ELSE category + END AS category, + CASE WHEN active THEN 'Display' + ELSE 'Don\'t Display' + END AS active_alt + FROM bus_category + WHERE lower(category) LIKE :search"; + + $stmt = $this->registry->dbh->prepare($sql); + $stmt->bindParam(':search', strtolower("%{$_GET['q']}%"), PDO::PARAM_STR); + $stmt->execute(); + + $threads = $stmt->fetchAll(PDO::FETCH_ASSOC); + + $tree = new Toolkit_Toolbox_SearchTree(new GLM_TEMPLATE(null)); + $sortedLeafs = $tree->sortChildren($threads, true); + $html .= $tree->toHtml($sortedLeafs, $sortedLeafs[0]); + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/SearchTree.php b/Toolkit/Toolbox/SearchTree.php new file mode 100644 index 0000000..521fc23 --- /dev/null +++ b/Toolkit/Toolbox/SearchTree.php @@ -0,0 +1,35 @@ +%s'; + $img = $branch['active'] ? 'grnball.gif' : 'redball.gif'; + $q = urlencode(stripslashes($_GET['q'])); + return sprintf( + $activeFormat, + BASE_URL . "admin/toolbox.php?id={$branch['id']}&_qf__search_form=&rt=Search&q=$q", + $branch['active_alt'], + BASE_URL . "Toolkit/Toolbox/assets/$img", + $branch['active_alt'] + ); + } + + // }}} + // {{{ sortChildren() + + public function sortChildren(array $threads) + { + $children = array(); + while (list($key, $value) = each ($threads)) { + $children[0][$value['id']] = $value; + } + + return $children; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/TreeAbstract.php b/Toolkit/Toolbox/TreeAbstract.php new file mode 100644 index 0000000..51def6d --- /dev/null +++ b/Toolkit/Toolbox/TreeAbstract.php @@ -0,0 +1,230 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Toolkit_Toolbox_TreeAbstract + * + * Description for Toolkit_Toolbox_TreeAbstract + * + * @category Toolkit + * @package Toolbox + * @author Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +abstract class Toolkit_Toolbox_TreeAbstract +{ + // {{{ properties + + + /** + * Description for $rootNodeStart + * @var string + * @access protected + */ + protected $rootNodeStart = "
        \n"; + + /** + * Description for $subTreeStart + * @var string + * @access protected + */ + protected $subTreeStart = "\n
          \n"; + + /** + * Description for $treeEnd + * @var string + * @access protected + */ + protected $treeEnd = "\n
        \n"; + + /** + * Description for $leafStart + * @var string + * @access protected + */ + protected $leafStart = "\n\t
      • \n"; + + /** + * Description for $leafEnd + * @var string + * @access protected + */ + protected $leafEnd = "\n\t
      • \n"; + + /** + * Description for $config + * @var Config_Container + * @access protected + */ + protected $config; + + /** + * Description for $tree + * @var array + * @access protected + */ + protected $tree; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Config_Container $config Config container + * + * @return void + * @access public + */ + public function __construct(Config_Container $config) + { + $this->config = $config; + } + + // }}} + + // {{{ getActiveBallImage() + + /** + * Description for getActiveBallImage() + * + * @param array $branch Branch array + * + * @return string + * @access protected + */ + protected function getActiveBallImage(array $branch) + { + $imgFormat = '%s'; + + $show = sprintf( + $imgFormat, + ($branch['active']) ? '' : 'style="display: none;"', + BASE_URL . "Toolkit/Toolbox/assets/grnball.gif", + 'Active Ball' + ); + + $hide = sprintf( + $imgFormat, + ($branch['active']) ? 'style="display: none;"' : '', + BASE_URL . "Toolkit/Toolbox/assets/redball.gif", + "In-active Ball" + ); + + return $show . $hide; + } + + // }}} + // {{{ getActiveMobileBallImage() + + /** + * Description for getActiveMobileBallImage() + * + * @param array $branch Branch array + * + * @return string + * @access protected + */ + protected function getActiveMobileBallImage(array $branch) + { + $imgFormat = '%s'; + + $show = sprintf( + $imgFormat, + ($branch['mobile_active']) ? '' : 'style="display: none;"', + BASE_URL . "Toolkit/Toolbox/assets/mobilemgreen.jpg", + 'Active Ball' + ); + + $hide = sprintf( + $imgFormat, + ($branch['mobile_active']) ? 'style="display: none;"' : '', + BASE_URL . "Toolkit/Toolbox/assets/mobilemred.jpg", + "In-active Ball" + ); + + return $show . $hide; + } + + // }}} + // {{{ getActiveBall() + + /** + * Description for getActiveBall() + * + * @param array $branch Branch array + * + * @access protected + * @return void + */ + abstract protected function getActiveBall(array $branch); + + // }}} + + // {{{ createTree() + + /** + * Description for createTree + * + * @param array $tree Description for $tree ... + * @param unknown $leaf Description for $leaf ... + * @param int $level Description for $level ... + * + * @return void + * @access protected + */ + abstract protected function createTree(array $tree, $leaf, $level = 0); + + // }}} + // {{{ fetchContent() + + /** + * Description for fetchContent + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox Gateway + * + * @return void + * @access protected + */ + abstract protected function fetchContent( + Toolkit_Toolbox_GatewayAbstract $gateway + ); + + // }}} + + // {{{ toHtml() + + /** + * Description of toHtml() + * + * @return string + * @access public + */ + public function toHtml() + { + $GLOBALS['styleSheets'][] = BASE_URL . 'admin/main.css'; + $GLOBALS['styleSheets'][] = BASE_URL . 'Toolkit/Toolbox/styles.css'; + $GLOBALS['topScripts'][] + = GLM_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js'; + + if (is_array($this->tree)) { + $html = $this->createTree($this->tree, reset($this->tree)); + } + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/assets/.keepme b/Toolkit/Toolbox/assets/.keepme new file mode 100644 index 0000000..e69de29 diff --git a/Toolkit/Toolbox/assets/arrow.png b/Toolkit/Toolbox/assets/arrow.png new file mode 100755 index 0000000000000000000000000000000000000000..ee11ab40646e2bc42c35af3b4e13389c4c9c5e52 GIT binary patch literal 502 zcmVt&d^oYUM)|R2Htc=sj%Bl+}b_R%bNihiQJ)o<=3?U&Q20uSPhJb(o z10eT25Vu3aku-x~z{0|Up`oFH8R*IisDbvx7)6-)}OG{&LaBxTia<2k$AU=bL1_~7isY$Nrx@0)TlW{p>;vL@XnJEH+Mo{~J}?|Qbco^Dv16Bk+&Cb1C;>P3}S&X zDk>^efRrl`&+6#t_)Ce4I7LN8rvd5nKtt^*_L`rcpRTN|>;a%*>!7YA&mc`rO@^qb zC&;0fE=AUmpZg1waEXket~-#Rv$OmzOic*yLcwL029D1Q-Ab&Wx;9QN23= O0000pfi@Ln>}1{rUgjp4pT^n0YEgT(gglPl=`(M@9$N1S__s znnf2`6rMF+dLqeE(rP~8Q(MvAg*AH`1Z}T1%(~HVB~-!f+a+0rYj(xY&gcilOzBVK zV4gDHZA*8}JOWzopr0Kh$8f&c&j literal 0 HcmV?d00001 diff --git a/Toolkit/Toolbox/assets/collapse.png b/Toolkit/Toolbox/assets/collapse.png new file mode 100755 index 0000000000000000000000000000000000000000..d10e0519033cf07df1a80b71773ad9dcf89e5674 GIT binary patch literal 182 zcmeAS@N?(olHy`uVBq!ia0vp^0zfRp#0(_$L%00|Qk(%kA+G=b{|7RGWZnCIe;|vo zB*-tA!Qt7BG!Q4r+uensgH_f8q`bf*vY3H^TL^?1FWs&C0~BO0@$_|Nzs$rYC}=7l z{p=-BNX^s5F{ENna>4;_31??!35iW%mIekMYgse=RAGBzy0`dp@lA`>X%hf6w?havoNteP}GJzWFgkW4>0M*4)zCv4WUL1XecR#gTZJcjh5QEP80LYU2P=$ zF_y^8P58>XP>^()3m&R+W<#hE1DZ~-;9xM?NUKlO)uf4e z;$j%devBnD^~ce^j(c}(*gMA7O0RN&~uYGB{dzNb@;xCCp^(PF6}rMnOeST|r4lSw=>~TvNxu(8R<C(60W%9L8&E<`fPsmTiG`IF zF2~5k%p%CZCZxzJqLjE$*w8322xI`zt3b~p0cKVfkO3Nk42;Z-EZhh=MxeFKEJB8X ztimFqib{@7i3<;Y_ z@dZ1cD@HvKJ?3S3IOpQI6Ng_k7`nR!=`49R=ls!ir`|d7WgJ)fu+8J*v(*Vxd&4+O z@6PtU^5svJd)<$<8-hBFdzRh(vVh6Y`1hfzZrz}OV!J6^(PF6}rMnOeST|r4lSw=>~TvNxu(8R<UCKhH+xD+E3 zGYcz&ppYWFun3!yp^;-?;>3kOm6D7MOw1@ou&^>Qv#|rERDkv{urjkSBN@WL%pxen zs%R)2n7FWU;>Q2CK<)uLhgp!po($*dEi4}|b zJhNk53#uD*mC|CjymG$#NtSzi|2gg#>bs9sWL;&Lq`T|!2mR-BA6n-p>t0*8d7^D_ lX{dh4ue*LeH`Ca>%x()udTrklY_==qP7!kg`<43tHvw2)duadw literal 0 HcmV?d00001 diff --git a/Toolkit/Toolbox/assets/redball.gif b/Toolkit/Toolbox/assets/redball.gif new file mode 100755 index 0000000000000000000000000000000000000000..700513384bc89f9df78d061bdf3d52e52f7063ae GIT binary patch literal 881 zcmc(ev1*lJ42IuA!9(eAip4<=(t~z$5VD*qLPhAYAWn`779}^}Qo0u5OhUoIY=Vnp z@d`vi3eDu`74#0oDL(mb!fy*n-aL8p|I5RJ#op1THuXoUepwY&US(D4D6=vuz0xYx z$;gVR@CvI?*Ls#mxtCkHy4A8Q%Dl|VgiQSy?N2+&3vEt;uT&*>MLo@trtu|yFW zo?#hk3X&e_o^I)CC~7UzJk8PsBdw`OdCF2ug&HxSp#+N@gV9DBEt=H}b! zSR(gu3sqX3XsMm+G%?TI z)kd-(V~Nb%gs-d%1xc5=@DZmm04~Zgnr*QXKft6LJ78jAHiQ~6py>n)4hEx*wE9F{ zO`4b|E{2ip$5J_@03-dBiQ~Mpf&PLLjesa95{N;gF%TqH3YE&y`kfH7hoSidC>kn2qpNHH zlm+X_AXpU;#bQH1P&wy!nnI}VSC%ps0|S1A6b=b97Bz;ACkl{}l9QB`kP~zU1%maG(AbOQ@XEDYtr0G$A~XPW~I?iB0RP4M)o zR~ z3*LKq%G97V6}HZ*K77poXGCddAyh(8wIgo=v+$CVrg?5+!A- zR4Q_3j_$Gv;8RFu2oB8DEmngqUUw;j@A% zHh9ZPA0bTwk6-QChpgyKQpmrpzkmG_pkmJdfEl>MLNL9!Lz6!%z|jT(NldnYF66W& zKs+n#GRQpzFhCDHGtpJf1&B3K#~Y?_RL4=9w2-1F%M~}s7R#kpQbN5!^c8;=j98lq zS6$E%Vb3UYSSTSW=8RH=n3tp`#YOqTkUV0LAZ2)Ih?z_9a8{0I!Qlc=FB`&h0A+*t zsKIF5gkl;wsMYbpYE!nxm?oZVA&MyZbd7Y_TZ_;vfjn1AsmF z=wntt|D;3fK#$VlSwiKcNQ6USRbgrWs25cF1FZq9`Vo~NiF8s)&Y%R+YnKM78BH?L zG?Pt(a3|hQj!_GgP)t2@)RdpjOB6cpCPM*MRRyVU2KjdPl`oQ(^Uh{o@q?B`;pWrU z0&k^R?_71!fmc=m`{5VE(3&*Tam*O`5t5WH#^kfAN|ppDSzh)@W@K4b92_VEMl5M= zq5@|@sx8HhVm0q&=+H#l)@W{^>~_j2za=Xi5v3Go6-UY`x8hNsI+rQSn_g#&r@!2i z9TD95M#Mu!h?nLD>2+JGsnmpg)ksRhmqy6t(C7Aj704=8m9p+9SW7+xzJY<;?III( z46@*k01!5j#DuC4Apjc~rnzDNCmy~OA{`i%Xe^3(u81cK3&B{2jHtN8^Nl%iw#lB( z6`g^Wh}hRCBnbV>>@8?W_ZQ|XVNs@25jE> zCf0K5$r{isaIPrs({YFq(>^x<%UCYO17ab5~o74llfBovi(( zV{Ic9dO~)pkoiw&8tF#irXmiH#Ogob>X@zKfh%3{Dho$AVmnyLY75{ zW|8oJ7LXPS0=5{c9mYte*w)?Nlaf^g?0Mvx$z`B+6Lsl?gF#cvyG#+U(;%f@K1*5> zw-S|oQKc5Rli?JfQi~asfu&$$=~BYZqLpEF8)M7Hr`$hADhN|O}-fU}EK z5K(H!salP|w}I#ILKg$H%-2+48L_>DY~2yXcZd)kov=+BZYvc7;|2|I(Ct0GluzE$ NP#J_@03-dBiQ~Mpf&PLLjesa95{N;gF%TqH3YE&y`kfH7hoSidC>kn2qpNHH zlm+X_AXpU;#bQH1P&wy!nnI}VSC%ps0|S1A6b=b97Bz+)3XhPHl9QB=jTix$nwy-R zo|zJK1_grx1qB2I2B}2^1E>R|0|%I&wzr@F1PiIX3cB|@%pWQQTXea4Gms#z3*-t}ROU@u0chv{MmZxD(wvKEFY0Imu<_y<1g?0w z5&+W`Oqhe_oyoZ?$%K}-ynQtGag{1)s)`!bH7cd5pFlq~qmXf>E?QMLM3t&*(5hh* zQ|XHd>(!t%7PfklKtzCn1@!9m(glElyfy^x5y%Kt?IuId()#^-GUS1x)Iy>HIcu5^ zRfHrACM+yTD!ss1pfZMY0m6oFs<51#>(o)ENsx|8RWz2;GvO}Do=w|>sDGvq8g2E; zl`M2;k^;jC0M%h=2oAv1jc~)RV0nS{8YZ16_2;m7A?W9uh{Pf}d2XO44P`a**Rp9l z9If%U!zY2m&o=D?Uv(!b_^7ZSKYnNv#PT2i2l23AOl8ysv;rJ$0FVSt^ZbHNJZ#Xj zLS}@R!oWTAz+_iC7cAC99dEqyQ5{K<(t?SnELWUYETBkY8VvO|Q7lho0Ag(>V08gV z*&sGjG>aYPUO14Q1dWlS6zAj%K=!9WWzu10(`GTw^I1Bf1=q_w!VGf80tZMp$c`GA z_Khm3p|e^YFSrIJY>%1q5ss_qa!OMq^62NEfCkEAC4?3V$)BX7{o zU~I|ci*%`6x63hNU6ANI<5(ljlIJbShI*6w)e$&8_`sJr!1X8PXr#d-4?Tk*a1Q|a z?6ZqMgD6!&0gX zg>b=f=Dl^@MTcJZx$CeWfiKiG*0V4|$t`xV|N6INDdAkd#N>yH zbBcGqo(_q8ay$F^=%=s#`V|=JJ|&1sJC-a%>-K0^uFaCFT9rcgOE8+UPNxJDF7((< zZKlG;lJ>WiRZ*o?0TaqO(jmB+IV>KS%hj%Wm4;uL1t0>Uz`hQWDTNdvI1XVJAzBA5 zjeQIp)RLcLpr)9SyaFZM8r3SkJ_@03-dBiQ~Mpf&PLLjesa95{N;gF%TqH3YE&y`kfH7hoSidC>kn2qpNHH zlm+X_AXpU;#bQH1P&wy!nnI}VSC%ps0|S1A6b=b97Bz;ACkl{}l9QB`kP~zU1%maG(AbOQ@XEDYtr0G$A~XPW~I?iB0RP4M)o zR~ z3*LKq%G97V6}HZ*K77poXGCddAyh(8wIgo=v+$CVrg?5+!A- zR4Q_3j_$Gv;8RFu2oB8DEmngqUUw;j@A% zHh9ZPA0bTwk6-QChpgyKQpmrpzkmG_pkmJdfEl>MLNL9!Lz6!%z|jT(NldnYF66W& zKs+n#GRQpzFhCDHGtpJf1&B3K#~Y?_RL4=9w2-1F%M~}s7R#kpQbN5!^c8;=j98lq zS6$E%Vb3UYSSTSW=8RH=n3tp`#YOqTkUV0LAZ2)Ih?z_9a8{0I!Qlc=FB`&h0A+*t zsKIF5gkl;wsMYbpYE!nxm?oZVA&MyZf}>49y4xwI{Kl+s=@McbN6IO;qRwhw@Ek9?@N%6kpZ;=7c0_RJ z8xao`Azqprq-QFssZt{{I3pRZy!`Ro1$nU@iIJ_XY-Tw~I{FG01{D z0zhakJQNZk02>&lxnULyU8LH9Ewb#Ud%ma*V6xn9cbA}?cRc*X)}(lp)%Y~qXxoU8N9 z+RrRDJZ(l~!5>j#8Zm zRi{$bsr2VDjdVkBv^&SF2E-qYea8(5G;N$s95_W$aD@;gy1a1S%iQV2pdQ( zLuhOJ_@03-dBiQ~Mpf&PLLjesa95{N;gF%TqH3YE&y`kfH7hoSidC>kn2qpNHH zlm+X_AXpU;#bQH1P&wy!nnI}VSC%ps0|S1A6b=b97Bz+)3XhPHl9QB=jTix$nwy-R zo|zJK1_grx1qB2I2B}2^1E>R|0|%I&wzr@F1PiIX3cB|@%pWQQTXea4Gms#z3*-t}ROU@u0chv{MmZxD(wvKEFY0Imu<_y<1g?0w z5&+W`Oqhe_oyoZ?$%K}-ynQtGag{1)s)`!bH7cd5pFlq~qmXf>E?QMLM3t&*(5hh* zQ|XHd>(!t%7PfklKtzCn1@!9m(glElyfy^x5y%Kt?IuId()#^-GUS1x)Iy>HIcu5^ zRfHrACM+yTD!ss1pfZMY0m6oFs<51#>(o)ENsx|8RWz2;GvO}Do=w|>sDGvq8g2E; zl`M2;k^;jC0M%h=2oAv1jc~)RV0nS{8YZ16_2;m7A?W9uh{Pf}d2XO44P`a**Rp9l z9If%U!zY2m&o=D?Uv(!b_^7ZSKYnNv#PT2i2l23AOl8ysv;rJ$0FVSt^ZbHNJZ#Xj zLS}@R!oWTAz+_iC7cAC99dEqyQ5{K<(t?SnELWUYETBkY8VvO|Q7lho0Ag(>V08gV z*&sGjG>aYPUO14Q1dWlS6zAj%K=!9WWzu10(`GTw^I1Bf1=q_w!VGf80tZMp$c`GA z_Khm3p|e^YFSrIJY>%1q5ss_qa!OMq^62NEfCegPBb5|tC?pfyR*Gq=umTG#zg<9D zF8o0EOEA~%a*SAlkv0K((kyx2l5D6a>7?aIIgSrL@MR8g{Yg3LJMhRu&maig13*6e z?BdTL3Q{oZ1P7%;M`#SCV>KiG*0V4|$t`xV|N6INDkl;9kS%hF6w7?a@ z*-?vOj)9tDM)C@ja4S@+_!bNOB7rQ)gmLC#T29o(lUwy=flVQbyi}tUd*y6?M-1V< zKGiQDO(kFq8<_vXl8%Fkp(|kmTp;8gCKri)s0kHI#eH_D7Qn;?ggorn?L?&*RTybx zy^CTTjh7ddC66=9BS!P|*hUeahE3VC8JxC|Gau|seUSW9{D|hL`u#>(!V#j=juW-z z%&$39+Fx`qr8Vnx4MkwuPFGejHX{6EU1y_D0Y{Y{x7jXkZ;Mae(m)>oMY0bO0028l C8Ms>j literal 0 HcmV?d00001 diff --git a/Toolkit/Toolbox/assets/template5.gif b/Toolkit/Toolbox/assets/template5.gif new file mode 100755 index 0000000000000000000000000000000000000000..6c36b50e00df6359ebdf9d33228b2194e179c508 GIT binary patch literal 1501 zcmV<31tR)KNk%w1VLJ_@03-dBiQ~Mpf&PLLjesa95{N;gF%TqH3YE&y`kfH7hoSidC>kn2qpNHH zlm+X_AXpU;#bQH1P&wy!nnI}VSC%ps0|S1A6b=b97Bz+)3XhPHl9QB=jTix$nwy-R zo|zJK1_grx1qB2I2B}2^1E>R|0|%I&wzr@F1PiIX3cB|@%pWQQTXea4Gms#z3*-t}ROU@u0chv{MmZxD(wvKEFY0Imu<_y<1g?0w z5&+W`Oqhe_oyoZ?$%K}-ynQtGag{1)s)`!bH7cd5pFlq~qmXf>E?QMLM3t&*(5hh* zQ|XHd>(!t%7PfklKtzCn1@!9m(glElyfy^x5y%Kt?IuId()#^-GUS1x)Iy>HIcu5^ zRfHrACM+yTD!ss1pfZMY0m6oFs<51#>(o)ENsx|8RWz2;GvO}Do=w|>sDGvq8g2E; zl`M2;k^;jC0M%h=2oAv1jc~)RV0nS{8YZ16_2;m7A?W9uh{Pf}d2XO44P`a**Rp9l z9If%U!zY2m&o=D?Uv(!b_^7ZSKYnNv#PT2i2l23AOl8ysv;rJ$0FVSt^ZbHNJZ#Xj zLS}@R!oWTAz+_iC7cAC99dEqyQ5{K<(t?SnELWUYETBkY8VvO|Q7lho0Ag(>V08gV z*&sGjG>aYPUO14Q1dWlS6zAj%K=!9WWzu10(`GTw^I1Bf1=q_w!VGf80tZMp$c`GA z_Khm3p|e^YFSrIJY>%1q5ss_qa!OMq^62NEfCegPBb5|tC?pfyR*Gq=umTG#zg<9D zF8o0EOEA~%a*SAlkv0K((kyx2l5D6a>7?aIIgSrL@MR8g{Yg3LJMhRu&maig13*6e z?BdTL3Q{oZ1P7%;M`#SCV>KiG*0V4|$t`xV|N6INDp=Ehp;Y$*p*{z@`vIUaC=wy>ga{e3@)tpX!&7 zrjh}Hc_ksN6U)KSm9S2VEf8`KlZ(VY)P#zq;$kMtSZqM(7rhxqNV!vmkw(@#B8HGH zD9ek=lE<0l5u^hQ;b^iWpvt3D~-_im?&lAL}|BeF`|L^tjD-aeG^Q>Xruj00@$5hyVaP D(hs^9 literal 0 HcmV?d00001 diff --git a/Toolkit/Toolbox/assets/template6.gif b/Toolkit/Toolbox/assets/template6.gif new file mode 100644 index 0000000000000000000000000000000000000000..28d140edcd7fc1e4546c4c5402d7d1b17d7f0c6e GIT binary patch literal 1501 zcmV<31tR)KNk%w1VLaG(AbPEDWECc1i51kLTXPXNH?iB0RP4M)o zR~ z3*LKq%G97V6}HZ*K77poXGCddAyh(8wIgo=v+$CVrg?5+!A- zR4Q_3j_$Jg;8RFu2o%iJEmngqUUw;j@A% zHh9ZPA0bTwk6-QChpgyKQpmrpzkmG_pkmJdfEl>MLNL9!Lz6!%z|qD7NlYeyF66WY zKs+n#GRQp%3_uS&GtpJf1&B3K#~Y?_RL4=9w2-1F%M~}s7R#kpQbN5!^c8;=j98lq zS6$E%Vb3UYSSTSW=8RH=n3tp`#YOqTkUV0LAZ2)Ih?z_9a8{0I!Qlc=FB`(60A+*t zsKIF5gkl;wsMYbpYE!nxm?oZVA&MyZf}>49y4xwI{Kl+s=@McbN6IO;qRwhw@Ek9?@N%6kpZ;=7c0_RJ z8xao`Azqprq-QFssZt{{I3pRZy!`Ro1$nU@iIJ_XY-Tw~I{FG01{D z06=IiJQNZE02>&lxnULyU8LH9Ewb#Ud%ma*V6xn9cbA}?cRc!mIH(lp)%Y~qXxoU8N9 z+RrRea8(5G;N$sAGURRzZ@5kl-xDS%iQV2={V< zYW?6^i-FoVz9A_bV*@n$)Xe`=N33jjC>V~$;CjCu~u!&HN|Qm$O>bm+$F|j zy%Sf>j#rsqD35EJX&#vLc*N|LW_wgqP0xJrv-UYsQ1mmJqbeginTransaction(); +try { + $checkSql = + "SELECT id + FROM paragraphs + WHERE page = :page + AND pos = 1"; + $checkStmt = $dbh->prepare($checkSql); + $addSql = " + INSERT INTO paragraphs + (active,page,pos) + VALUES + (true,:page,1)"; + $addStmt = $dbh->prepare($addSql); + $sql = " + SELECT id + FROM pages + ORDER BY parent,pos"; + $stmt = $dbh->query($sql); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $checkStmt->bindParam( + ':page', + $row['id'], + PDO::PARAM_INT + ); + $checkStmt->execute(); + if ($checkStmt->rowCount() == 0) { + // nothing set yet need to add one + $addStmt->bindParam( + ':page', + $row['id'], + PDO::PARAM_INT + ); + $addStmt->execute(); + echo '

        + Adding paragraph! PageId:'.$row['id'].'

        '; + } else { + echo '

        + Good Page PageId:'.$row['id'].'

        '; + } + } + $dbh->commit(); +} catch(PDOException $e) { + die($e->getMessage()); +} diff --git a/Toolkit/Toolbox/fixPagePos.php b/Toolkit/Toolbox/fixPagePos.php new file mode 100644 index 0000000..c414a6d --- /dev/null +++ b/Toolkit/Toolbox/fixPagePos.php @@ -0,0 +1,70 @@ +beginTransaction(); +$pageData = array(); +try { + $sql = " + UPDATE pages + SET pos = :pos + WHERE id = :id"; + $updatePagePos = $dbh->prepare($sql); + $sql = " + SELECT id,parent,pos + FROM pages + ORDER BY parent,pos"; + $res = $dbh->query($sql); + while ($row = $res->fetch(PDO::FETCH_ASSOC)) { + $pageData[$row['parent']][] = $row['id']; + } + echo '

        fixing page positions

        '; + if (is_array($pageData)) { + $curParent = 0; + $pos = 1; + foreach ($pageData as $parent => $pages) { + if ($curParent != $parent) { + $curParent = $parent; + $pos = 1; + } + foreach ($pages as $pageId) { + $updatePagePos->bindParam(":pos", $pos, PDO::PARAM_INT); + $updatePagePos->bindParam(":id", $pageId, PDO::PARAM_INT); + $updatePagePos->execute(); + ++$pos; + } + } + } + $sql = " + UPDATE paragraphs + SET pos = :pos + WHERE id = :id"; + $updateParagraphPos = $dbh->prepare($sql); + $sql = " + SELECT id,page,pos + FROM paragraphs + ORDER BY page,pos"; + $res = $dbh->query($sql); + while ($row = $res->fetch(PDO::FETCH_ASSOC)) { + $paragraphData[$row['page']][] = $row['id']; + } + echo '

        fixing paragraphs positions

        '; + if (is_array($paragraphData)) { + $curPage = 0; + $pos = 1; + foreach ($paragraphData as $page => $paragraphs) { + if ($curPage != $page) { + $curPage = $page; + $pos = 1; + } + foreach ($paragraphs as $paragraphId) { + $updateParagraphPos->bindParam(":pos", $pos, PDO::PARAM_INT); + $updateParagraphPos->bindParam(":id", $paragraphId, PDO::PARAM_INT); + $updateParagraphPos->execute(); + ++$pos; + } + } + } +} catch(PDOException $e) { + die($e->getMessage()); +} +$dbh->commit(); diff --git a/Toolkit/Toolbox/libjs/edit-page.js b/Toolkit/Toolbox/libjs/edit-page.js new file mode 100644 index 0000000..f4f4045 --- /dev/null +++ b/Toolkit/Toolbox/libjs/edit-page.js @@ -0,0 +1,239 @@ +var EditPage = +{ + openSection: '#pageContent', + sectionHeaders: null, + sectionAttributes: null, + + init: function()// {{{ + { + $('input[name=deletePage]:submit').click(EditPage.confirmPageDelete); + $('#MemberCategories').change(function() { + $('input[name=include_members]').attr('checked', 'checked'); + }); + $('#MemberRegions').change(function() { + $('input[name=include_members]').attr('checked', 'checked'); + }); + $('#CouponCategories').change(function() { + $('input[name=include_coupons]').attr('checked', 'checked'); + }); + EditPage.pageAttributes(); + EditPage.memberAttributes(); + EditPage.couponAttributes(); + EditPage.headlineAttributes(); + + EditPage.sectionHeaders = $('tbody tr.hdr td'); + EditPage.sectionAttributes = $('span.attributes'); + + + // If there was an error with validation, then + // find the first error and open that section. + var $firstFormValidationError = $('div.req:first'); + if ($firstFormValidationError.length > 0) { + // Hide all sections first + $("tbody.section > tr:not(.hdr)").toggle(); + + // Then open the target section + $firstFormValidationError + .parents("tbody.section") + .children("tr:not(.hdr)") + .toggle(); + $firstFormValidationError + .parents("tbody.section") + .children('tr.hdr') + .children() + .toggleClass('open'); + } else { + // Initially hide all sections EXCEPT the first section + // which has an id #pageContent + $("tbody.section > tr:not(.hdr)") + .not("tbody#pageContent > tr") + .toggle(); + } + + $("tbody.section tr.hdr").click(function() { + var $currId = $(this).parents('tbody').attr('id'); + if ($currId == EditPage.openSection) { + return false; + } + + // Set this section to the current section open + EditPage.openSection = $currId + + // Remove the class open from all the section headers. + // This will reset the arrow in the header back to closed (>) + EditPage.sectionHeaders.each(function() { + $(this).removeClass('open'); + }); + + // default shows all the section "quick at a glance" attributes + EditPage.sectionAttributes.show(); + // hide current sections "quick at a glance" attributes + $(this).find('.attributes').hide(); + + // hide all the sections + $('tbody.section > tr:not(.hdr)').hide(); + // unhide the section that was clicked + $(this).siblings().toggle(); + // make this section open, w/ a down arrow (v) + $(this).children().toggleClass('open'); + }); + + $("select[multiple]").asmSelect({ + animate: true + }); + + 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 : 'Default', +// width : 570, +// height : 400, + filebrowserImageBrowseUrl : '../Toolkit/CKImages/browser.php?folder=1', + filebrowserImageUploadUrl : '../Toolkit/CKImages/controller.php?command=Upload', + filebrowserImageWindowWidth : '760', + filebrowserImageWindowHeight : '500' + }); +// config.scayt_autoStartup = true; +// config.scayt_uiTabs = '0,0,0'; + } + } + },// }}} + + confirmPageDelete: function(event)// {{{ + { + if (!confirm("Are you sure you wish to delete this page and its paragraphs?\n\n" + + "All sub pages along with existing page drafts will also be deleted!")) { + event.preventDefault(); + } + },// }}} + createCategoryShortcutView: function(element, section, container)// {{{ + { + var target = section.find('select[name="'+element+'[]"]'); + if (target.length) { + container.append(''); + var $holder = container.find('.'+element), + $numSelected = target.find(':selected').length; + if ($numSelected) { + EditPage.updateText($holder, '['+$numSelected+']Categories'); + } + target.change(function() { + var $numSelected = target.find(':selected').length; + EditPage.updateText($holder, '['+$numSelected+']Categories'); + }); + } + },// }}} + createRegionShortcutView: function(element, section, container)// {{{ + { + var target = section.find('select[name="'+element+'[]"]'); + if (target.length) { + container.append(''); + var $holder = container.find('.'+element), + $numSelected = target.find(':selected').length; + if ($numSelected) { + EditPage.updateText($holder, '['+$numSelected+']Regions'); + } + target.change(function() { + var $numSelected = target.find(':selected').length; + EditPage.updateText($holder, '['+$numSelected+']Regions'); + }); + } + },// }}} + createCheckboxShortcutView: function(element, section, container, text)// {{{ + { + var target = section.find('input[name='+element+']:checkbox'); + if (target.length) { + container.append(''); + var $holder = container.find('.'+element), + $checked = target.is(':checked') + ? '[X]' + : '[ ]'; + EditPage.updateText($holder, $checked + text); + + target.change(function() { + var $checked = target.is(':checked') + ? '[X]' + : '[ ]'; + EditPage.updateText($holder, $checked + text); + }); + } + },// }}} + createTextShortcutView: function(element, section, container)// {{{ + { + var target = section.find('input[name='+element+']'); + if (target.length) { + container.append(''); + var $holder = container.find('.'+element); + if (target.val() != '') { + EditPage.updateText($holder, '{' + target.val() + '}'); + } + target.change(function() { + if ($(this).val() != '') { + EditPage.updateText($holder, '{' + $(this).val() + '}'); + } else { + EditPage.updateText($holder, ''); + } + }); + } + },// }}} + + couponAttributes: function()// {{{ + { + var $section = $('#coupons'); + $section.find('tr.hdr td') + .append(''); + + $attributes = $section.find('tr.hdr .attributes'); + + EditPage.createCheckboxShortcutView('include_coupons', $section, $attributes, 'Display Coupons'); + EditPage.createCategoryShortcutView('coupon_categories', $section, $attributes); + },// }}} + + headlineAttributes: function()// {{{ + { + var $section = $('#headlines'); + $section.find('tr.hdr td') + .append(''); + + $attributes = $section.find('tr.hdr .attributes'); + + EditPage.createCheckboxShortcutView('headline', $section, $attributes, 'Headline'); + },// }}} + + pageAttributes: function()// {{{ + { + var $section = $('#attributes'); + $section.find('tr.hdr td') + .append(''); + + $attributes = $section.find('tr.hdr .attributes'); + + EditPage.createTextShortcutView('keyword', $section, $attributes); + EditPage.createTextShortcutView('short_url', $section, $attributes); + EditPage.createCheckboxShortcutView('paragraph_links', $section, $attributes, 'Links'); + },// }}} + + memberAttributes: function()// {{{ + { + var $section = $('#members'); + $section.find('tr.hdr td') + .append(''); + + $attributes = $section.find('tr.hdr .attributes'); + + EditPage.createCheckboxShortcutView('include_members', $section, $attributes, 'Display Members'); + EditPage.createCategoryShortcutView('member_categories', $section, $attributes); + EditPage.createRegionShortcutView('member_regions', $section, $attributes); + EditPage.createCheckboxShortcutView('include_member_map', $section, $attributes, 'Map'); + EditPage.createCheckboxShortcutView('search_form', $section, $attributes, 'Search'); + },// }}} + + updateText: function(holder, content)// {{{ + { + holder.html(content); + }// }}} +}; + +$(document).ready(EditPage.init); diff --git a/Toolkit/Toolbox/libjs/edit-paragraph.js b/Toolkit/Toolbox/libjs/edit-paragraph.js new file mode 100644 index 0000000..68bfcf8 --- /dev/null +++ b/Toolkit/Toolbox/libjs/edit-paragraph.js @@ -0,0 +1,149 @@ +var EditParagraph = +{ + init: function()// {{{ + { + $('.files').sortable({ + placeholder: 'ui-state-highlight' + }); + + $('input[name="deleteParagraph"]').click(EditParagraph.confirmParagraphDelete); + + // Bind click events to the remove buttons for uploaded files + // everytime a button is clicked, an entire li element is removed + // so we can get rid of all the info stored in hidden fields + // about the file (bytes, filename, etc...). + $('.remove').live('click', function(event) { + event.preventDefault(); + $(this).parent('li').remove(); + }); + + $('#filename').after(''); + $('#filename').after(''); + var $uploadNotification = $('#upload_notification'); + + $("tbody.section tr:not(.hdr)").toggle(); + var $hdr = $('tbody.section tr.hdr'); + + $hdr.click(function() { + $(this).siblings() + .toggle(); + $(this).children() + .toggleClass('open'); + }); + + $("div.req").each(function() { + $(this).parents("tbody.section") + .children("tr:not(.hdr)") + .toggle(); + $(this).parents("tbody.section") + .children("tr.hdr") + .children() + .toggleClass('open'); + }); + + 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 : 'Default', +// width : 570, +// height : 400, + filebrowserImageBrowseUrl : '../Toolkit/CKImages/browser.php?folder=1', + filebrowserImageUploadUrl : '../Toolkit/CKImages/controller.php?command=Upload', + filebrowserImageWindowWidth : '760', + filebrowserImageWindowHeight : '500' + }); + } + } + },// }}} + + cleanName: function(filename)// {{{ + { + var $alphaNumeric = filename.replace(/[^A-Za-z0-9]/g, ''); + + return $alphaNumeric; + },// }}} + confirmParagraphDelete: function(event)// {{{ + { + if (!confirm("Are you sure you wish to delete this paragraph and its files?")) { + event.preventDefault(); + } + },// }}} + + getExtensionImage: function(ext)// {{{ + { + var img; + switch (ext) { + case 'mp3' : + img = 'mp3.gif'; + break; + + case 'avi' : + img = 'avi.gif'; + break; + + case 'html' : + img = 'html.gif'; + break; + + case 'mov' : + img = 'mov.gif' + break; + + case 'wmv' : + img = 'wmv.gif'; + break; + + case 'ppt' : + img = 'ppt.gif'; + break; + + case 'zip' : + img = 'zip.png'; + break; + + case 'rar' : + case 'tar' : + img = 'rar.gif'; + break; + + case 'txt' : + img = 'txt.png'; + break; + + case 'xlsx' : + case 'xls' : + img = 'xls.gif'; + break; + + case 'pdf' : + img = 'pdf.png'; + break; + + case 'doc' : + case 'docx' : + img = 'doc.gif'; + break; + + case 'png' : // image does not exist yet. + case 'jpeg' : + case 'jpg' : + img = 'jpg.gif'; + break; + + case 'gif' : + img = 'gif.gif'; + break; + + default : + img = 'download.gif'; + break; + } + + return img; + }// }}} +}; + +$(document).ready(EditParagraph.init); diff --git a/Toolkit/Toolbox/libjs/pagesTree.js b/Toolkit/Toolbox/libjs/pagesTree.js new file mode 100644 index 0000000..473420d --- /dev/null +++ b/Toolkit/Toolbox/libjs/pagesTree.js @@ -0,0 +1,242 @@ +var PagesTree = +{ + init: function() + { + PagesTree.updateMoveArrowVisibility(); + $('.admin_nav') + .append('
      • Expand All
      • ') + .append('
      • Collapse All
      • ') + .append('
      • Show Positions
      • ') + .append('
      • Hide Positions
      • ') + ; + + var $myTree = $('#tree'); + + if ($myTree.children('ul').size() > 0) { + $myTree.tree({ + callback : { + onsearch : function (NODES, TREE_OBJ) { + TREE_OBJ.container.find('strong.search').removeClass('search'); + NODES.addClass('search'); + + if (NODES.length == 0) { + alert('No matches found - Please refine your search.'); + } + } + }, + plugins : { + cookie : { + prefix : "jstree_toolbox_", + types : { + selected : false + } + } + } + }); + $('#show_pos').click(function(event) { + event.preventDefault(); + $('select').show(); + }); + $('#hide_pos').click(function(event) { + event.preventDefault(); + $('select').hide(); + }); + $('#expand_all').click(function(event) { + event.preventDefault(); + $.tree.focused().open_all(); + }); + $('#collapse_all').click(function(event) { + event.preventDefault(); + $.tree.focused().close_all(); + }); + + $("#search_form").submit(function(event) { + var $search = $("#q").val().toUpperCase(); + event.preventDefault(); + jQuery.expr[':'].Contains = function(a, i, m) { + return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0; + }; + $.tree.focused().search($search, "contains('"+$search+"'),strong:Contains"); + }); + + $('a.pagePreview').click(function(event) { + var newWindow = window.open($(this).attr('href')); + newWindow.focus(); + return false; + }); + + $('img.moveDown').click(function() { + var $li = $(this).closest('li'), + $sibling = $li.next(); + if ($sibling.length == 1) { + var $id = $li.attr('id'); + $li.detach(); + $li.insertAfter($sibling); + PagesTree.updateMoveArrowVisibility(); + $.ajax({ + url : '../toolbox-page-move/'+$id+'/down/', + cache: false, + async: false, + success: function(html) { + if (html == 0) { + PagesTree.moveBack($li, $sibling); + } else if ($sibling.hasClass('last')) { + $sibling.removeClass('last'); + $li.addClass('last'); + } + }, + error: function() { + PagesTree.moveBack($li, $sibling); + } + }); + } + }); + + $('img.moveUp').click(function() { + var $li = $(this).closest('li'), + $sibling = $li.prev(); + if ($sibling.length == 1) { + var $id = $li.attr('id'); + $li.detach(); + $li.insertBefore($sibling); + PagesTree.updateMoveArrowVisibility(); + $.ajax({ + url : '../toolbox-page-move/'+$id+'/up/', + cache: false, + async: false, + success: function(html) { + if (html == 0) { + PagesTree.moveBack($li, $sibling); + } else if ($li.hasClass('last')) { + $li.removeClass('last'); + $sibling.addClass('last'); + } + }, + error: function() { + PagesTree.moveBack($li, $sibling); + } + }); + } + }); + + $('.active-ball').click(function(event) { + event.preventDefault(); + var id = $(this).attr('rel'), + _this = $(this); + $.get('../toolbox-change-state/'+id+'/?t=' + event.timeStamp, function(data) { + if (data) { + _this.children().toggle(); + var newTitle = _this.attr('title') == 'Display' + ? "Don't Display" + : 'Display'; + _this.attr('title', newTitle); + } + }); + }); + $('.mobile-active-ball').click(function(event) { + event.preventDefault(); + var id = $(this).attr('rel'), + _this = $(this); + $.get('../toolbox-change-state-mobile/'+id+'/?t=' + event.timeStamp, function(data) { + if (data) { + _this.children().toggle(); + var newTitle = _this.attr('title') == 'Display' + ? "Don't Display" + : 'Display'; + _this.attr('title', newTitle); + } + }); + }); + } + $('.closed').hover(function(){ + $(this).css('background', 'lightgrey'); + //$(this).children('.right-element').show(); + },function(){ + $(this).css('background', 'none'); + //$(this).children('.right-element').hide(); + }); + $('.leaf').hover(function(){ + $(this).css('background', 'lightgrey'); + //$(this).children('.right-element').show(); + },function(){ + $(this).css('background', 'none'); + //$(this).children('.right-element').hide(); + }); + $('li.open').each(function(){ + var count = $(this).children('ul').children('li').size(); + PagesTree.loadSelectOptions( + $(this).children('ul').children('li').children('div.right-element'), + count + ); + }); + $('li.closed').each(function(){ + var count = $(this).children('ul').children('li').size(); + PagesTree.loadSelectOptions( + $(this).children('ul').children('li').children('div.right-element'), + count + ); + }); + $('select.pos-select').each(function(){ + $(this).change(function(){ + var id = $(this).attr('name'); + var oldpos = $(this).attr('rel'); + var newpos = $(this).attr('value'); + window.location.href = '../toolbox-page-move-sel/' + id + '/' + oldpos + '/' + newpos + '/'; + }); + }); + $('ul.ltr').each(function(){ + var count = $(this).children('li').size(); + PagesTree.loadSelectOptions( + $(this).children('li').children('div.right-element'), + count + ); + }); + }, + + loadSelectOptions: function(ul, count) + { + ul.each(function(){ + var selCount = $(this).children('select').attr('rel'); + if ($(this).children('select').hasClass('parent-level-sel')) { + var begin = 2; + } else { + var begin = 1; + } + for (i = begin; i <= count; ++i) { + var html = '