From: Steve Sutton
Date: Tue, 22 Apr 2014 19:38:17 +0000 (+0000)
Subject: new location
X-Git-Tag: v1.0~52
X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/?a=commitdiff_plain;h=be8f67df42991d4775b53ea2df9106c6d9057f5e;p=web%2FCedarvilleMarine.git
new location
---
diff --git a/.htaccess b/.htaccess
new file mode 100644
index 0000000..f8e3d2c
--- /dev/null
+++ b/.htaccess
@@ -0,0 +1,147 @@
+
+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.cedarvillemarine.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]
+
+# Combine resource files into one
+# but only for PRODUCTION MODE
+#RewriteCond %{ENV:GLM_HOST_ID} PRODUCTION
+#RewriteCond %{HTTPS} !=on
+#RewriteRule ^javascript/(.*\.js) combine.php?type=javascript&files=$1
+#RewriteCond %{ENV:GLM_HOST_ID} =PRODUCTION
+#RewriteCond %{HTTPS} !=on
+#RewriteRule ^css/(.*\.css) combine.php?type=css&files=$1
+
+############
+## Events ##
+############
+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]
+
+RewriteRule bannerClick.php Toolkit/Banners/banner_click_through.php [QSA,L]
+
+##############
+## 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]
+RewriteRule ^member-([0-9]*)/.*-([0-9]*).html$ 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..176c7f3
--- /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..6ca0be2
--- /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..f97d172
--- /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:' . MEDIA_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:' . MEDIA_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:' . MEDIA_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:' . MEDIA_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 = MEDIA_BASE_URL;
+ $page->glmAppBaseUrl = MEDIA_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',
+ MEDIA_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:' . MEDIA_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..756e7cb
--- /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 = preg_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 . preg_replace("%/$%", "", $path);
+ //var_dump($dirName);echo ' ';
+ $d = dir($dirName);
+ while (false !== ($entry = $d->read())) {
+ if (!preg_match("%^\.|^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..2e24e47
--- /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 0000000..93fc375
Binary files /dev/null and b/Toolkit/CKImages/assets/night-fate-stock2.jpg differ
diff --git a/Toolkit/CKImages/browser.php b/Toolkit/CKImages/browser.php
new file mode 100644
index 0000000..f266df2
--- /dev/null
+++ b/Toolkit/CKImages/browser.php
@@ -0,0 +1,49 @@
+
+ * @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';
+
+// make sure the image directories exists for editor
+$imgDirs = array(
+ BASE . 'Toolkit/CKImages/editedImages',
+ BASE . 'Toolkit/PHPImageEditor/editimagesoriginal',
+ BASE . 'Toolkit/PHPImageEditor/editimagespng',
+ BASE . 'Toolkit/PHPImageEditor/editimagesworkwith',
+);
+$oldMask = umask(0);
+foreach ($imgDirs as $dir) {
+ if (!is_dir($dir)) {
+ mkdir($dir, 0770, true);
+ }
+}
+umask($oldMask);
+
+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..0c41ae8
--- /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: ' . MEDIA_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..86cab7a
--- /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(//app.gaslightmedia.com/assets/icons/add.png);
+}
+#toolbar #folderNew {
+ background-image: url(//app.gaslightmedia.com/assets/icons/folder_add.png);
+}
+#toolbar #folderDelete {
+ background-image: url(//app.gaslightmedia.com/assets/icons/folder_delete.png);
+}
+.tree ul {
+ margin: 0;
+ padding-top: 1px;
+}
+.tree li a {
+ background-image: url(//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(//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(//app.gaslightmedia.com/assets/icons/accept.png) no-repeat; }
+.CKImageEdit {background: url(//app.gaslightmedia.com/assets/icons/image_edit.png) no-repeat; }
+.CKImageView {background: url(//app.gaslightmedia.com/assets/icons/image.png) no-repeat;}
+.CKImageDelete {background: url(//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;
+}
diff --git a/Toolkit/CKImages/templates/thumbnails.html b/Toolkit/CKImages/templates/thumbnails.html
new file mode 100755
index 0000000..d8eaa64
--- /dev/null
+++ b/Toolkit/CKImages/templates/thumbnails.html
@@ -0,0 +1,70 @@
+
+
+
+Thumbnail Images
+
+
+
+
+
+
+
+
+ GLM Image Browser
+
+
+
+
+
{i[original_width]:h}x{i[original_height]:h}
+
+
+
{i[file_name]:h}
+
{i[create_date]:h}
+
+
+
+
+
+
+
+
+
+ {quickUploadForm:h}
+
+
+
+ {CKEditorFuncNum}
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Toolkit/Common.php b/Toolkit/Common.php
new file mode 100644
index 0000000..2ff5197
--- /dev/null
+++ b/Toolkit/Common.php
@@ -0,0 +1,1354 @@
+
+ * @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(MEDIA_BASE_URL);
+ $appUrlStrLen = strlen(MEDIA_APP_BASE_URL);
+
+ // Use versioning with local scripts for cachebusting
+ $localPath = MEDIA_BASE_URL . 'v/' . VERSION . '/javascript/';
+ $appPath = MEDIA_APP_BASE_URL . 'javascript/';
+
+ $localScripts = array();
+ $appScripts = array();
+ foreach ($uniqueScripts as $origScript) {
+ $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(MEDIA_BASE_URL);
+ $appUrlStrLen = strlen(MEDIA_APP_BASE_URL);
+ $ret = '';
+
+ $localPath = MEDIA_BASE_URL . 'v/' . VERSION . '/css/';
+ $appPath = MEDIA_APP_BASE_URL . 'css/';
+
+ $localStyleSheets = array();
+ $appStyleSheets = array();
+ foreach ($uniqueStyleSheets as $origStyleSheet) {
+ $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..ef49dbb
--- /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
';
+ }
+ return true;
+ }
+ return false;
+ }
+
+
+ // }}}
+}
+?>
diff --git a/Toolkit/Contacts/VisitorGuide.php b/Toolkit/Contacts/VisitorGuide.php
new file mode 100755
index 0000000..2755e94
--- /dev/null
+++ b/Toolkit/Contacts/VisitorGuide.php
@@ -0,0 +1,313 @@
+
+ * @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' => 'header',
+ 'name' => 'firstHdr_rmv',
+ 'display' => ''
+ );
+ $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' => 'email',
+ 'req' => true,
+ 'name' => 'email',
+ 'display' => 'Email'
+ );
+ $e[] = array(
+ 'type' => 'email',
+ 'req' => true,
+ 'name' => 'email_rmv',
+ 'display' => 'Verify Email'
+ );
+ $e[] = array(
+ 'type' => 'tel',
+ 'req' => false,
+ 'name' => 'phone',
+ 'display' => 'Phone'
+ );
+ $e[] = array(
+ 'type' => 'tel',
+ '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/application.ini b/Toolkit/Contacts/application.ini
new file mode 100644
index 0000000..a29edc0
--- /dev/null
+++ b/Toolkit/Contacts/application.ini
@@ -0,0 +1,22 @@
+; Production server configuration data
+[production]
+previousYearSince = 2010
+
+; flexyOptions
+flexyOptions.templateDir = BASE "Toolkit/Contacts/templates"
+flexyOptions.compileDir = BASE "Toolkit/Contacts/templates/compiled"
+flexyOptions.forceCompile = Off
+flexyOptions.url_rewrite = "baseurl/::" BASE_URL ",glmappbaseurl/::" MEDIA_APP_BASE_URL
+flexyOptions.allowPHP = On
+
+; development server configuration data inherits from production and
+; overrides values as necessary
+[development : production]
+
+; chuck's server configuration data inherits from development
+; and overrides values as necessary
+[chuck : development]
+
+; steve's server configuration data inherits from development
+; and overrides values as necessary
+[steve : development]
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..c77d0d2
--- /dev/null
+++ b/Toolkit/Contacts/config.ini
@@ -0,0 +1,14 @@
+; 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"
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..d145ab2
--- /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/contactForm.html b/Toolkit/Contacts/templates/contactForm.html
new file mode 100644
index 0000000..2f2f84a
--- /dev/null
+++ b/Toolkit/Contacts/templates/contactForm.html
@@ -0,0 +1,92 @@
+
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 @@
+
+
+
+ *
+
+ {label}
+
+
+
+ {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 @@
+
\ 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 @@
+
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.
+
+
+ Name
+ Phone
+
+
+ {foreach:memberDirectNoEmail,member}
+
+ {member[memberName]}
+ {member[memberPhone]}
+ Remove
+
+ {end:}
+
+Request Information by Email from:
+This list of businesses will receive the following information form directly to their email account.
+
+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}
+
+
+
+ {v[label]:h}
+
+
+ {if:v[nowrap]}
+
+ {v[element]:h}
+
+ {else:}
+
+ {v[element]:h}
+
+ {end:}
+
+ {end:}
+
+
+
+
+
+
+
+
+
+ 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..ced09b6
--- /dev/null
+++ b/Toolkit/DataGridBuilder.php
@@ -0,0 +1,288 @@
+
+ * @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;
+ }
+ if ($_GET['page_id']) {
+ $this->pagerOptions['path'] = MEDIA_BASE_URL . 'members-only-area/';
+ }
+ }
+
+ // }}}
+
+ // {{{ 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..f6e6521
--- /dev/null
+++ b/Toolkit/Database.php
@@ -0,0 +1,268 @@
+
+ * @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();
+ }
+
+ if (defined('SEASONS') && SEASONS) {
+ // define seasonator search path
+ $stmt->bindValue(':schema', 'seasons', 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..36e214a
--- /dev/null
+++ b/Toolkit/FileServer/AdapterAbstract.php
@@ -0,0 +1,416 @@
+
+ * @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 {
+ if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
+ $fileData = array(
+ 'request' => $request,
+ 'file_upload' => new CurlFile(
+ $_FILES[$name]['tmp_name'],
+ $_FILES[$name]['type'],
+ $_FILES[$name]['name']),
+ 'file_upload_name' => $_FILES[$name]['name']
+ );
+ } 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_POST => 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..d59601d
--- /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..6db761e
--- /dev/null
+++ b/Toolkit/FileServer/ImageAdapter.php
@@ -0,0 +1,259 @@
+
+ * @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();
+ if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
+ $fileData = array(
+ 'request' => $request,
+ 'file_upload' => new CurlFile(
+ $_FILES[$fname]['tmp_name'],
+ $_FILES[$fname]['type'],
+ $_FILES[$fname]['name']),
+ 'file_upload_name' => basename($fname)
+ );
+ } else {
+ $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..8ee6d1a
--- /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'] = MEDIA_BASE_URL;
+ *
+ *
+ *
+ *
+ *
+ *
+ * @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..ab3d79e
--- /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..4eb5592
--- /dev/null
+++ b/Toolkit/FormBuilder.php
@@ -0,0 +1,1264 @@
+
+ * @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) {
+ $baseURL = MEDIA_BASE_URL;
+ $GLOBALS['styleSheets'][] = $baseURL . '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
+ *
+ *
+ *
+ *
+ * *
+ *
+ * {label}
+ *
+ *
+ *
+ * {error}
+ *
+ * {element}
+ *
+ *
+ *
+ *
+ * # Form.tpl
+ *
+ *
+ *
+ *
+ * # 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(
+ '
+ {label}
+ {element}
+ ',
+ 'captcha_question'
+ );
+ $renderer->setElementTemplate(
+ '
+ '.$required.'{label}
+ '.$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'][]
+ = MEDIA_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.css';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/cluetip/lib/jquery.hoverIntent.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/cluetip/lib/jquery.bgiframe.min.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_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 @@
+
+
+
+ *
+
+ {label}
+
+
+
+ {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 @@
+
\ 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 @@
+
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..534e21b
--- /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..0c85d77
--- /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..fb777b8
--- /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..c56daca
--- /dev/null
+++ b/Toolkit/Image/Server.php
@@ -0,0 +1,385 @@
+
+ * @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 {
+ if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
+ $fileData = array(
+ 'request' => $request,
+ 'file_upload' => new CurlFile(
+ $_FILES[$name]['tmp_name'],
+ $_FILES[$name]['type'],
+ $_FILES[$name]['name']
+ ),
+ 'file_upload_name' => $_FILES[$name]['name']
+ );
+ } 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..12af0d6
--- /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('>', '\"', '
', '
', '"/>', '&', '<', '�', '�');
+ // $replace = array('>', '"', '', '', '" />', '&', '<', 'Ÿ', 'ÿ');
+ // $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..2dfc8a2
--- /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..5f93b72
--- /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 ($subject instanceof Toolkit_LeadManager_Contact) {
+ $values['address_line_1'] = $subject->getAddress();
+ $values['address_line_2'] = $subject->getAddress2();
+ } else if ($subject instanceof 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..d1d8493
--- /dev/null
+++ b/Toolkit/LeadManager/Contact.php
@@ -0,0 +1,315 @@
+
+ * @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;
+ private $_verify_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)
+ ->setVerifyPassword($verify_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;
+ }
+
+ /**
+ * Returns the Verify Password
+ *
+ * @return string
+ */
+ public function getVerifyPassword()
+ {
+ return $this->_verify_password;
+ }
+
+ /**
+ * Sets the verify_password
+ *
+ * @param string $verifyPassword
+ */
+ public function setVerifyPassword($verifyPassword)
+ {
+ $this->_verify_password = $verifyPassword;
+ }
+
+
+}
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..2063551
--- /dev/null
+++ b/Toolkit/LeadManager/Lead.php
@@ -0,0 +1,665 @@
+
+ * @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
+ = (is_array($interest))
+ ? explode(':', $interest)
+ : array();
+ if (is_array($intArray)) {
+ array_filter($intArray);
+ }
+ 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..4929af6
--- /dev/null
+++ b/Toolkit/LeadManager/StreamSend.php
@@ -0,0 +1,74 @@
+
+ * @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(),
+ 'state' => $subject->getState(),
+ 'zip' => $subject->getZip(),
+ 'phone' => $subject->getPhone()
+ );
+ if ($subject instanceof Toolkit_LeadManager_Contact) {
+ $values['address'] = $subject->getAddress();
+ $values['address2'] = $subject->getAddress2();
+ } else if ($subject instanceof Toolkit_LeadManager_Customer) {
+ $values['address'] = $subject->getAdd1();
+ $values['address2'] = $subject->getAdd2();
+ }
+
+ $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..17993c2
--- /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..524243a
--- /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..9288e31
--- /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..e29361d
--- /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..f28608e
--- /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..58d0efe
--- /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..3c38b6d
--- /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 0000000..3589e8b
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/crop_view.png differ
diff --git a/Toolkit/PHPImageEditor/images/edit.gif b/Toolkit/PHPImageEditor/images/edit.gif
new file mode 100644
index 0000000..1a5a0af
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/edit.gif differ
diff --git a/Toolkit/PHPImageEditor/images/empty.gif b/Toolkit/PHPImageEditor/images/empty.gif
new file mode 100644
index 0000000..35d42e8
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/empty.gif differ
diff --git a/Toolkit/PHPImageEditor/images/jcrop.gif b/Toolkit/PHPImageEditor/images/jcrop.gif
new file mode 100644
index 0000000..72ea7cc
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/jcrop.gif differ
diff --git a/Toolkit/PHPImageEditor/images/slider_pointer.gif b/Toolkit/PHPImageEditor/images/slider_pointer.gif
new file mode 100644
index 0000000..8e8fdcd
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/slider_pointer.gif differ
diff --git a/Toolkit/PHPImageEditor/images/slider_track.gif b/Toolkit/PHPImageEditor/images/slider_track.gif
new file mode 100644
index 0000000..e1dc8e0
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/slider_track.gif differ
diff --git a/Toolkit/PHPImageEditor/images/tab_body.png b/Toolkit/PHPImageEditor/images/tab_body.png
new file mode 100644
index 0000000..6e164fe
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/tab_body.png differ
diff --git a/Toolkit/PHPImageEditor/images/tab_not_selected.png b/Toolkit/PHPImageEditor/images/tab_not_selected.png
new file mode 100644
index 0000000..3051203
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/tab_not_selected.png differ
diff --git a/Toolkit/PHPImageEditor/images/tab_selected.png b/Toolkit/PHPImageEditor/images/tab_selected.png
new file mode 100644
index 0000000..d4fd93c
Binary files /dev/null and b/Toolkit/PHPImageEditor/images/tab_selected.png differ
diff --git a/Toolkit/PHPImageEditor/includes/constants.php b/Toolkit/PHPImageEditor/includes/constants.php
new file mode 100644
index 0000000..f296152
--- /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..b04cfe2
--- /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..90e6f79
--- /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()) { ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 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..965b6ba
--- /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+">"+T+">"});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(Fa text ';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=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(/
diff --git a/Toolkit/Photos/templates/Admin/editPhoto.html b/Toolkit/Photos/templates/Admin/editPhoto.html
new file mode 100644
index 0000000..d3bff2d
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/editPhoto.html
@@ -0,0 +1,264 @@
+
+
+
+
+
+ Edit Photo in {categoryName}
+
+
+
+
+ {if:photo}
+
+ {if:!mediaExclusive}
+
+ {end:}
+ {end:}
+
+
+
+
+
diff --git a/Toolkit/Photos/templates/Admin/editUser.html b/Toolkit/Photos/templates/Admin/editUser.html
new file mode 100644
index 0000000..128b30e
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/editUser.html
@@ -0,0 +1,233 @@
+
+
+
+
+ {if:user}
+
+ {end:}
+
+
+
+
diff --git a/Toolkit/Photos/templates/Admin/emailUser.tpl b/Toolkit/Photos/templates/Admin/emailUser.tpl
new file mode 100644
index 0000000..ac8da03
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/emailUser.tpl
@@ -0,0 +1,68 @@
+
+
+
+
+ {title:h}
+
+
+
+
+ {subject:h}
+
+
+
+
+
+ {if:approved}
+ Thank you for submitting your request for photos to the Traverse
+ City Convention & Visitors Bureau. Your request has been approved
+ and your login information is below. Please note that your access
+ to this site will be active for 2 weeks, beginning today. Should
+ you require additional time once your access period has expired, we
+ ask that you fill out a new request form.
+
+ Login: {user.getEmail()}
+ Password: {user.getMediaPass()}
+
+ Sincerely,
+
+ The Traverse City Tourism Marketing Team
+ {end:}
+ {if:denied}
+ We're sorry, but your request for media-quality photos did not meet
+ our criteria. However, we encourage you to choose from the wide range
+ of photos available on our general photo library. You do not require
+ a special login to view and download those photos.
+
+ Thanks for your interest in Traverse City!
+ The Traverse City Tourism Marketing Team
+ {end:}
+
+
+
+
+
+
+
+
+ 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/Photos/templates/Admin/index.html b/Toolkit/Photos/templates/Admin/index.html
new file mode 100644
index 0000000..4ce6dfe
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/index.html
@@ -0,0 +1,29 @@
+
+
+
+ {AppName}
+
+
+ {styles:h}
+
+ {topScripts:h}
+
+
+
+ {content:h}
+ {bottomScripts:h}
+
+
diff --git a/Toolkit/Photos/templates/Admin/listCategories.html b/Toolkit/Photos/templates/Admin/listCategories.html
new file mode 100644
index 0000000..d0e9508
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/listCategories.html
@@ -0,0 +1,93 @@
+
+
+
+
+
+
+ {if:category.getFirstPhoto()}
+
+
+
+ {end:}
+
+ {category.getTotalNumberOfPhotos():h}
+
+
+
+
+
+
diff --git a/Toolkit/Photos/templates/Admin/listPhotos.html b/Toolkit/Photos/templates/Admin/listPhotos.html
new file mode 100644
index 0000000..7711ee8
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/listPhotos.html
@@ -0,0 +1,63 @@
+
+
+
+ {if:photo.getImage()}
+
+
+
+ {end:}
+
+
+
diff --git a/Toolkit/Photos/templates/Admin/listUsers.html b/Toolkit/Photos/templates/Admin/listUsers.html
new file mode 100644
index 0000000..1d0d90c
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/listUsers.html
@@ -0,0 +1,26 @@
+
+
+
{statusText}
+
+
+ Function
+ Name
+ Expires
+ Approved
+
+
+
+ [Edit]
+
+ {user.getFname()} {user.getLname()}
+ {user.getExpire()}
+
+ {if:user.getApproved()}
+ Yes
+ {else:}
+ No
+ {end:}
+
+
+
+
diff --git a/Toolkit/Photos/templates/Admin/nav.html b/Toolkit/Photos/templates/Admin/nav.html
new file mode 100644
index 0000000..953174b
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/nav.html
@@ -0,0 +1,17 @@
+
diff --git a/Toolkit/Photos/templates/Admin/searchForm.html b/Toolkit/Photos/templates/Admin/searchForm.html
new file mode 100644
index 0000000..6b5ac51
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/searchForm.html
@@ -0,0 +1,76 @@
+
+
diff --git a/Toolkit/Photos/templates/Admin/userNav.html b/Toolkit/Photos/templates/Admin/userNav.html
new file mode 100644
index 0000000..721ba30
--- /dev/null
+++ b/Toolkit/Photos/templates/Admin/userNav.html
@@ -0,0 +1,14 @@
+
diff --git a/Toolkit/Photos/templates/photoCats.html b/Toolkit/Photos/templates/photoCats.html
new file mode 100755
index 0000000..a01d715
--- /dev/null
+++ b/Toolkit/Photos/templates/photoCats.html
@@ -0,0 +1,17 @@
+catPhotos) {
+ foreach ($t->catPhotos as $category) {
+ ?>
+
+
+
+
+ getCategory();?>
+
+
\ No newline at end of file
diff --git a/Toolkit/Photos/templates/photoGalleryWrapper.html b/Toolkit/Photos/templates/photoGalleryWrapper.html
new file mode 100644
index 0000000..e48bb57
--- /dev/null
+++ b/Toolkit/Photos/templates/photoGalleryWrapper.html
@@ -0,0 +1,336 @@
+
+
+
+
+{if:photoNameSearch}
+
+{end:}
\ No newline at end of file
diff --git a/Toolkit/Photos/templates/photos.html b/Toolkit/Photos/templates/photos.html
new file mode 100755
index 0000000..90e3171
--- /dev/null
+++ b/Toolkit/Photos/templates/photos.html
@@ -0,0 +1,31 @@
+photos) {
+ foreach ($t->photos as $photo) {
+ ?>
+
+
+
+ getTitle()) {?>
+
+ getTitle();
+ if(strlen($tempTitle) > 50) {
+ $tempTitle = substr($tempTitle, 0, 47);
+ $tempTitle .= "...";
+ }
+ echo $tempTitle;
+ //echo $photo->getTitle();
+ ?>
+
+
+
+ getDownload()) {?>
+
+ Download for
+ Web - Print
+
+
+
+
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..8857223
--- /dev/null
+++ b/Toolkit/RotatingImages/ActiveImagesDataGrid.php
@@ -0,0 +1,66 @@
+
+ * @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..a6ef3de
--- /dev/null
+++ b/Toolkit/RotatingImages/Database/tables/rotating_images.sql
@@ -0,0 +1,20 @@
+DROP TABLE IF EXISTS rotatingImages.rotating_images CASCADE;
+
+CREATE TABLE rotatingImages.rotating_images
+(id SERIAL,
+ image TEXT NOT NULL UNIQUE,
+ title TEXT,
+ descr TEXT,
+ 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..a98b7d7
--- /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'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/nivoslider/2.0/' . LIBJS_ENV . '/jquery.nivo.slider.js';
+ $GLOBALS['styleSheets'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/nivoslider/2.0/' . LIBJS_ENV . '/nivo-slider.css';
+ $GLOBALS['styleSheets'][] = MEDIA_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..e83266e
--- /dev/null
+++ b/Toolkit/RotatingImages/Decorator/Anchor.php
@@ -0,0 +1,100 @@
+
+ * @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()
+ );
+ }
+
+ // }}}
+ public function getTitle()
+ {
+ return $this->image->getTitle();
+ }
+
+ public function getDescr()
+ {
+ return $this->image->getDescr();
+ }
+
+ public function getId()
+ {
+ return $this->image->getId();
+ }
+}
+?>
diff --git a/Toolkit/RotatingImages/Decorator/DecoratorAbstract.php b/Toolkit/RotatingImages/Decorator/DecoratorAbstract.php
new file mode 100644
index 0000000..81509fc
--- /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..f7be31f
--- /dev/null
+++ b/Toolkit/RotatingImages/Decorator/IDecoratorsIterator.php
@@ -0,0 +1,49 @@
+
+ * @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..5f872ab
--- /dev/null
+++ b/Toolkit/RotatingImages/Decorator/Image.php
@@ -0,0 +1,92 @@
+
+ * @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 = ' ';
+ return sprintf(
+ $format,
+ $this->image->getWidth(),
+ $this->image->getHeight(),
+ ROTATING_IMAGE_RESIZED . $this->image->getImage(),
+ $this->image->getId()
+ );
+ }
+
+ // }}}
+
+ public function getTitle()
+ {
+ return $this->image->getTitle();
+ }
+
+ public function getDescr()
+ {
+ return $this->image->getDescr();
+ }
+
+ public function getId()
+ {
+ return $this->image->getId();
+ }
+
+}
diff --git a/Toolkit/RotatingImages/Decorator/Thumbnail.php b/Toolkit/RotatingImages/Decorator/Thumbnail.php
new file mode 100644
index 0000000..831f373
--- /dev/null
+++ b/Toolkit/RotatingImages/Decorator/Thumbnail.php
@@ -0,0 +1,71 @@
+
+ * @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..af07f71
--- /dev/null
+++ b/Toolkit/RotatingImages/Decorator/User.php
@@ -0,0 +1,125 @@
+
+ * @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
+{
+ /**
+ * Banner decorators
+ * @var array
+ * @access private
+ */
+ private $_decorators;
+
+ /**
+ * constructor
+ *
+ * @return void
+ * @access protected
+ */
+ public function __construct()
+ {
+ $this->_decorators = array();
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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 = MEDIA_APP_BASE_URL;
+ $baseUrl = MEDIA_BASE_URL;
+
+ $GLOBALS['styleSheets'][]
+ = $glmAppBaseUrl . 'libjs/plugins/nivoslider/3.2/prod/nivo-slider.css';
+ $GLOBALS['styleSheets'][]
+ = $glmAppBaseUrl . 'libjs/plugins/nivoslider/themes/default/default.css';
+ $GLOBALS['bottomScripts'][]
+ = $glmAppBaseUrl . 'libjs/plugins/nivoslider/3.2/prod/jquery.nivo.slider.js';
+ $GLOBALS['bottomScripts'][]
+ = $baseUrl . 'Toolkit/RotatingImages/libjs/user.php';
+
+ $options = $GLOBALS['flexyOptions'];
+ $options['templateDir'] = BASE . 'Toolkit/RotatingImages/templates';
+ $options['compileDir'] = BASE . 'Toolkit/RotatingImages/templates/compiled';
+ $tpl = new HTML_Template_Flexy($options);
+ $tpl->compile('rotatingImages.html');
+ $page = new stdClass();
+ $page->images = array();
+ $images = '';
+ foreach ($this->_decorators as $i) {
+ $images .= $i->toHtml();
+ $page->images[] = $i;
+ }
+
+ return !empty($images)
+ ? $tpl->bufferedOutputObject($page)
+ : '';
+ }
+
+}
diff --git a/Toolkit/RotatingImages/EditImageController.php b/Toolkit/RotatingImages/EditImageController.php
new file mode 100644
index 0000000..00a79d2
--- /dev/null
+++ b/Toolkit/RotatingImages/EditImageController.php
@@ -0,0 +1,96 @@
+
+ * @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->setConfig($this->registry->config);
+ $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: ' . MEDIA_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: ' . MEDIA_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..ba8da0b
--- /dev/null
+++ b/Toolkit/RotatingImages/Forms/EditImage.php
@@ -0,0 +1,397 @@
+
+ * @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
+
+ private $_config;
+
+ /**
+ * 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'
+ )
+ );
+
+ // }}}
+ public function setConfig(Config_Container $config)
+ {
+ $this->_config = $config;
+ }
+ // {{{ 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 = ' ';
+ $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(),
+ 'title' => $node->getTitle(),
+ 'descr' => $node->getDescr()
+ );
+ }
+ } 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();
+
+ $useTitles = $this->_config
+ ->getItem('section','conf')
+ ->getItem('directive', 'useTitles')
+ ->getContent();
+
+ // 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'
+ );
+ if ($useTitles) {
+ $e[] = array(
+ 'type' => 'text',
+ 'req' => false,
+ 'name' => 'title',
+ 'display' => 'Title',
+ 'opts' => array('class' => 'text')
+ );
+ $e[] = array(
+ 'type' => 'text',
+ 'req' => false,
+ 'name' => 'descr',
+ 'display' => 'Description',
+ 'opts' => array('class' => 'text')
+ );
+ }
+ $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..702c10f
--- /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(
+ ''
+ );
+ $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'][] = MEDIA_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..3692672
--- /dev/null
+++ b/Toolkit/RotatingImages/Gateway.php
@@ -0,0 +1,315 @@
+
+ * @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, title, descr)
+ VALUES
+ (:image, :active, :url, :external, :pos, :thumb_width, :thumb_height,
+ :width, :height, :title, :descr)";
+ $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);
+ }
+ if ($image->getTitle()) {
+ $stmt->bindParam(':title', $image->getTitle(), PDO::PARAM_STR);
+ } else {
+ $stmt->bindValue(':title', null, PDO::PARAM_NULL);
+ }
+
+ if ($image->getDescr()) {
+ $stmt->bindParam(':descr', $image->getDescr(), PDO::PARAM_STR);
+ } else {
+ $stmt->bindValue(':descr', 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,
+ title = :title,
+ descr = :descr
+ 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);
+ }
+
+ if ($image->getTitle()) {
+ $stmt->bindParam(':title', $image->getTitle(), PDO::PARAM_STR);
+ } else {
+ $stmt->bindValue(':title', null, PDO::PARAM_NULL);
+ }
+
+ if ($image->getDescr()) {
+ $stmt->bindParam(':descr', $image->getDescr(), PDO::PARAM_STR);
+ } else {
+ $stmt->bindValue(':descr', 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..be7685c
--- /dev/null
+++ b/Toolkit/RotatingImages/IImagesDataGrid.php
@@ -0,0 +1,40 @@
+
+ * @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..9255570
--- /dev/null
+++ b/Toolkit/RotatingImages/Image.php
@@ -0,0 +1,432 @@
+
+ * @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;
+
+ /**
+ * Title of the Image
+ * @var string
+ * @access protected
+ */
+ protected $title;
+
+ /**
+ * Description of Image
+ * @var type
+ * @access protected
+ */
+ protected $descr;
+
+ // }}}
+ // {{{ __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;
+ $this->title = $attributes['title'];
+ $this->descr = $attributes['descr'];
+ }
+
+ // }}}
+ // {{{ 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;
+ }
+
+ // }}}
+
+ public function getTitle()
+ {
+ return $this->title;
+ }
+
+ public function getDescr()
+ {
+ return $this->descr;
+ }
+
+ public function setTitle($title)
+ {
+ $this->title = $title;
+ return $this;
+ }
+
+ public function setDescr($descr)
+ {
+ $this->descr = $descr;
+ return $this;
+ }
+
+}
diff --git a/Toolkit/RotatingImages/ImagesDataGridAbstract.php b/Toolkit/RotatingImages/ImagesDataGridAbstract.php
new file mode 100644
index 0000000..bcfc50e
--- /dev/null
+++ b/Toolkit/RotatingImages/ImagesDataGridAbstract.php
@@ -0,0 +1,179 @@
+
+ * @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';
+ $img = sprintf(
+ $imgFormat, MEDIA_APP_BASE_URL . 'assets/icons/image_edit.png'
+ );
+
+ $linkFormat = '%s ';
+ return sprintf(
+ $linkFormat, MEDIA_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';
+ $img = sprintf(
+ $imgFormat, MEDIA_APP_BASE_URL . 'assets/icons/image_delete.png'
+ );
+
+ $linkFormat = '%s ';
+ return sprintf(
+ $linkFormat, MEDIA_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 = ' ';
+ 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'][] = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/themes/smoothness/jquery.ui.core.css';
+ $GLOBALS['styleSheets'][] = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8/development-bundle/themes/smoothness/jquery.ui.theme.css';
+
+ $GLOBALS['bottomScripts'][] = JQUERY_UI_CDN_JS;
+ $GLOBALS['bottomScripts'][] = MEDIA_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..a0231e4
--- /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..5fabdde
--- /dev/null
+++ b/Toolkit/RotatingImages/IndexController.php
@@ -0,0 +1,142 @@
+
+ * @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'][] = MEDIA_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..efd35a6
--- /dev/null
+++ b/Toolkit/RotatingImages/Navigation.php
@@ -0,0 +1,125 @@
+
+ * @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' => MEDIA_BASE_URL . 'admin/rotatingImages.php',
+ 'desc' => "Display all the Images",
+ ),
+ 'addImage' => array(
+ 'Title' => 'Add Image',
+ 'url' => MEDIA_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..3230eb2
--- /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..be6d71c
--- /dev/null
+++ b/Toolkit/RotatingImages/PreviewIframe.php
@@ -0,0 +1,89 @@
+
+ * @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..13ae7b5
--- /dev/null
+++ b/Toolkit/RotatingImages/PreviewJavascript.php
@@ -0,0 +1,88 @@
+
+ * @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..4a821fe
--- /dev/null
+++ b/Toolkit/RotatingImages/TransitionGateway.php
@@ -0,0 +1,101 @@
+
+ * @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..535d754
--- /dev/null
+++ b/Toolkit/RotatingImages/ajax.php
@@ -0,0 +1,49 @@
+
+ * @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..d5d582d
--- /dev/null
+++ b/Toolkit/RotatingImages/config.ini
@@ -0,0 +1,28 @@
+[conf]
+; Application Name
+applicationName = "Homepage Slideshow"
+useTitles = On
+hasPrevNextLinks = Off
+width = 505
+height = 303
+
+; 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..6eee5cb
--- /dev/null
+++ b/Toolkit/RotatingImages/libjs/user.php
@@ -0,0 +1,39 @@
+
+ * @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() {
+ $('#slider').nivoSlider({
+ effect: '',
+ animSpeed: 1000,
+ pauseTime:
+ });
+ if ($('#slider').children('a').size() <= 1 ) {
+ $('.nivo-prevNav').css('display', 'none');
+ $('.nivo-nextNav').css('display', 'none');
+ }
+
+ $('#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 @@
+
+
+
+ *
+
+ {label}
+
+
+
+ {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 @@
+
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 @@
+
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/RotatingImages/templates/rotatingImages.html b/Toolkit/RotatingImages/templates/rotatingImages.html
new file mode 100644
index 0000000..7a63826
--- /dev/null
+++ b/Toolkit/RotatingImages/templates/rotatingImages.html
@@ -0,0 +1,35 @@
+
+{if:images}
+
+
+
+ {foreach:images,image}
+ {image.toHtml():h}
+ {end:}
+
+
+
+ {if:image.getTitle()}{image.getTitle()} {end:}
+ {if:image.getDescr()}{image.getDescr()} {end:}
+
+{end:}
diff --git a/Toolkit/Router.php b/Toolkit/Router.php
new file mode 100644
index 0000000..eaca26d
--- /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..208b885
--- /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..7fb394f
--- /dev/null
+++ b/Toolkit/SiteMapXml.php
@@ -0,0 +1,186 @@
+
+ * @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
+ = ($catid == HOME_ID)
+ ? MEDIA_BASE_URL
+ : MEDIA_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 = MEDIA_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/SortForm.php b/Toolkit/SortForm.php
new file mode 100644
index 0000000..1c6e8da
--- /dev/null
+++ b/Toolkit/SortForm.php
@@ -0,0 +1,67 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @version CVS: $Id: SortForm.php,v 1.6 2010/01/18 02:09:05 jamie Exp $
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Creates a sortform to be used w/ datagrid DataGrids
+ *
+ * @category HTML
+ * @package Toolkit_SortForm
+ * @author Jamie Kahgee
+ * @copyright 2008 Gaslight Media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_SortForm extends Toolkit_FormBuilder
+{
+ // {{{ properties
+
+ /**
+ * The default rules to register for validating
+ *
+ * @var string
+ * @access protected
+ */
+ protected $registeredRules = array();
+
+ // }}}
+ // {{{ toHTML()
+
+ /**
+ * Render the form to a string
+ *
+ * Handle the rendering and validation of the form when displayed
+ * and submitted.
+ *
+ * @return string html form
+ * @access public
+ */
+ public function toHTML()
+ {
+ $this->setupRenderers();
+ if ($this->validate()) {
+ $output = parent::toHTML();
+ } else if ($this->isSubmitted()) {
+ $output = $this->errorMsg;
+ $output .= parent::toHTML();
+ } else {
+ $output = parent::toHTML();
+ }
+ return $output;
+ }
+
+ // }}}
+}
+?>
diff --git a/Toolkit/Table.php b/Toolkit/Table.php
new file mode 100644
index 0000000..2b6120a
--- /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..1b29dd8
--- /dev/null
+++ b/Toolkit/Template/BreadCrumbs.php
@@ -0,0 +1,217 @@
+
+ * @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);
+ }
+ $hasCommonEvents = (defined('COMMON_EVENTS') && COMMON_EVENTS);
+
+ if ($id != HOME_ID) {
+ if ( defined('EVENT_DB')
+ && EVENT_DB && !$hasCommonEvents
+ && $eventId = filter_var($_REQUEST['eventid'], FILTER_VALIDATE_INT)
+ ) {
+ try {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT header
+ FROM event
+ WHERE id = :eventid";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ':eventid',
+ $eventId,
+ PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $eventHeader = $stmt->fetchColumn();
+ if ($eventHeader) {
+ array_unshift($stack, $eventHeader);
+ }
+ } catch (PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+ }
+ if ( defined('EVENT_DB')
+ && EVENT_DB && !$hasCommonEvents
+ && $categoryId = filter_var($_REQUEST['category'], FILTER_VALIDATE_INT)
+ ) {
+ try {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT descr
+ FROM topic
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ':id',
+ $categoryId,
+ PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $topicHeader = $stmt->fetchColumn();
+ if ($topicHeader) {
+ array_unshift($stack, $topicHeader);
+ }
+ } catch (PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+ }
+ $page = $this->pageGateway->findNavItem($id);
+ $isSearch = filter_var($_REQUEST['search'], FILTER_VALIDATE_INT);
+ if ($isSearch && !$eventHeader && !$topicHeader && !$hasCommonEvents) {
+ array_unshift($stack, 'Events Search');
+ }
+ $isShortcut = filter_var($_REQUEST['t'], FILTER_SANITIZE_STRING);
+ if ($isShortcut && !$eventHeader && !$topicHeader && !$hasCommonEvents) {
+ if ($isShortcut == "today") {
+ array_unshift($stack, 'Today');
+ } else if ($isShortcut == "tomorrow") {
+ array_unshift($stack, 'Tomorrow');
+ } else if ($isShortcut == "next") {
+ array_unshift($stack, 'Next 7 Days');
+ }
+ }
+ if ($hasPhotoGalleriesOnThisPage) {
+ // Do Nothing
+ } else if (($eventHeader || $topicHeader || $isSearch || $isShortcut)
+ && !$hasCommonEvents
+ ) {
+ $seoUrl = Toolkit_Template_Page::getSeoUrl(
+ $this->pageGateway,
+ $id
+ );
+ $anchor = ''.$page['navigation_name'].' ';
+ array_unshift($stack, $anchor);
+ } 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)
+ ? '' . $breadCrumbs . '
'
+ : '';
+ }
+
+ // }}}
+}
+?>
diff --git a/Toolkit/Template/DraftBreadCrumbs.php b/Toolkit/Template/DraftBreadCrumbs.php
new file mode 100644
index 0000000..8bd85e4
--- /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 = ' ';
+ $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/AllInOneSideNav.php b/Toolkit/Template/Navigation/AllInOneSideNav.php
new file mode 100755
index 0000000..2f2df53
--- /dev/null
+++ b/Toolkit/Template/Navigation/AllInOneSideNav.php
@@ -0,0 +1,128 @@
+
+ * @copyright 2013 Gaslight Media
+ * @license Gaslight Media
+ * @version SVN: (0.1)
+ * @link <>
+ */
+
+/**
+ * Toolkit_Package_AllInOneSideNav
+ *
+ * Description of AllInOneSideNav
+ *
+ * @category Toolkit
+ * @package Package
+ * @author Steve Sutton
+ * @copyright 2013 Gaslight Media
+ * @license Gaslight Media
+ * @release Release: (0.1)
+ * @link <>
+ */
+class Toolkit_Template_Navigation_AllInOneSideNav
+{
+ private $_parents = array();
+ private $_navArray = array();
+ private $_gateway;
+ private $_pageId;
+
+ public function __construct(
+ Toolkit_Toolbox_GatewayAbstract $gateway
+ ) {
+ $this->_gateway = $gateway;
+ $id = filter_var($_REQUEST['catid'], FILTER_VALIDATE_INT);
+ $this->_pageId = $id;
+ if (!$id) {
+ $id = HOME_ID;
+ }
+ $this->_parents = $this->_getParentIds($id);
+ }
+
+ public function getNavigation()
+ {
+ return $this->setNavArray(0);
+ }
+
+ public function setNavArray($id)
+ {
+ try {
+ $navArray = array();
+ $dbh = Toolkit_Database::getInstance();
+ $pages = (defined('ALL_IN_ONE_INCLUDED')
+ && ALL_IN_ONE_INCLUDED)
+ ? unserialize(ALL_IN_ONE_INCLUDED)
+ : null;
+ $includedPages = (!empty($pages))
+ ? "AND (parent != 0 OR id IN (".implode(',', $pages)."))"
+ : '';
+ $memberPages = (defined('MEMBERS_DB') && MEMBERS_DB)
+ ? "AND id NOT IN (".MEMBERS_CATEGORY.")"
+ : '';
+ $sql = "
+ SELECT id,parent,navigation_name
+ FROM pages
+ WHERE parent = :id
+ AND active = true
+ $includedPages
+ $memberPages
+ ORDER BY parent,pos"; // AND id != ".MEMBERS_CATEGORY."
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+ $stmt->execute();
+ while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ if ($row['id'] == $this->_pageId) {
+ $class = 'current';
+ } else if (in_array($row['id'], $this->_parents)) {
+ $class = 'parent';
+ } else {
+ $class = '';
+ }
+ $navArray[] = array(
+ 'id' => $row['id'],
+ 'parent' => $row['parent'],
+ 'label' => $row['navigation_name'],
+ 'uri' => Toolkit_Template_Page::getSeoUrl(
+ $this->_gateway, $row['id']
+ ),
+ 'class' => $class,
+ 'pages' => $this->setNavArray($row['id'])
+ );
+ }
+ } catch (PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+ return $navArray;
+ }
+
+ private function _getParentIds($id)
+ {
+ 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();
+ $parent = $stmt->fetchColumn();
+ $this->_parents[] = $parent;
+ if ($parent == 0) {
+ return $this->_parents;
+ } else {
+ return $this->_getParentIds($parent);
+ }
+ } catch (PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+ }
+}
+
diff --git a/Toolkit/Template/Navigation/Factory.php b/Toolkit/Template/Navigation/Factory.php
new file mode 100644
index 0000000..52c76e5
--- /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_MainNavigationDynamic
+ */
+ public function createMainNav()
+ {
+ return new Toolkit_Template_Navigation_MainNavigationDynamic(
+ 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..87e0da6
--- /dev/null
+++ b/Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php
@@ -0,0 +1,97 @@
+
+ * @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;
+ private $_useTitleAsLink = false;
+
+ // }}}
+ // {{{ __construct()
+
+ /**
+ * Constructor
+ *
+ * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Page gateway to use
+ *
+ * @return void
+ * @access public
+ */
+ public function __construct(
+ Toolkit_Toolbox_PageGatewayAbstract $gateway,
+ $useTitleAsLink = false
+ ) {
+ $this->_gateway = $gateway;
+ $this->_useTitleAsLink = $useTitleAsLink;
+ }
+
+ // }}}
+
+ // {{{ 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);
+ if ($this->_useTitleAsLink) {
+ $link = Toolkit_Template_Page::getSeoUrl(
+ $this->_gateway, $topParentId
+ );
+ }
+ $title
+ = ($this->_useTitleAsLink)
+ ? "{$page['navigation_name']} "
+ : "{$page['navigation_name']}";
+ $this->_html = "{$title} " . $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..4f1870d
--- /dev/null
+++ b/Toolkit/Template/Page.php
@@ -0,0 +1,140 @@
+
+ * @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..f08ccc1
--- /dev/null
+++ b/Toolkit/Template/Page/BodyFactory.php
@@ -0,0 +1,212 @@
+
+ * @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']));
+ $glmSearch = ( defined('GLM_SEARCH')
+ && GLM_SEARCH
+ && isset($_REQUEST['GLMSearch'])
+ && $_REQUEST['GLMSearch'] == 'true');
+ $memberPage = ( defined('MEMBERS_DB')
+ && MEMBERS_DB
+ && $page['include_members']);
+
+ 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 ($glmSearch) {
+ return new Toolkit_Template_Page_GLMSearch();
+ } 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..3c142fc
--- /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 = '';
+
+ /**
+ * 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..44649b4
--- /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'][] = MEDIA_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/GLMSearch.php b/Toolkit/Template/Page/GLMSearch.php
new file mode 100644
index 0000000..32b7d55
--- /dev/null
+++ b/Toolkit/Template/Page/GLMSearch.php
@@ -0,0 +1,45 @@
+
+ * @copyright 2013 Gaslight Media
+ * @license Gaslight Media
+ * @version CVS: $Id: GLMSearch.php,v 1.5 2010/05/25 14:07:22 cscott Exp $
+ * @link <>
+ */
+
+/**
+ * Toolkit_Template_Page_GLMSearch
+ *
+ * Description of Toolkit_Template_Page_GLMSearch
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Chuck Scott
+ * @copyright 2013 Gaslight Media
+ * @license Gaslight Media
+ * @release Release: $id$
+ * @link <>
+ */
+class Toolkit_Template_Page_GLMSearch
+{
+ /**
+ * Description for getContent()
+ *
+ * @return string
+ * @access public
+ */
+ public function getContent()
+ {
+ require('/var/www/server/CommonApps/GLMSearch/V1/glmSearch.inc');
+ $glmSearch = new glmSearch(GLM_SEARCH_SITE, GLM_SEARCH_LOGIN, GLM_SEARCH_KEY);
+ $page = $glmSearch->doSearch();
+ return $page;
+ }
+}
+?>
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..3eff26d
--- /dev/null
+++ b/Toolkit/Template/Page/Member.php
@@ -0,0 +1,404 @@
+
+ * @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
+ $nonMembers = $this->_configContainer->getItem('section', 'conf')
+ ->getItem('directive', 'nonMembers')
+ ->getContent();
+ if ($nonMembers) {
+ $defaultSort = array(
+ 'nonmember' => 'ASC',
+ 'member_name' => 'ASC'
+ );
+ } else {
+ $defaultSort = array(
+ 'member_name' => 'ASC'
+ );
+ }
+ $searchList->setDefaultSort($defaultSort);
+ // 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();
+ }
+ $pageUrl
+ = ($_REQUEST['page_id'])
+ ? MEDIA_BASE_URL . "members-only-area/?page_id={$_REQUEST['page_id']}"
+ : MEDIA_BASE_URL . "index.php?catid={$_GET['catid']}";
+ $form = new Toolkit_Members_UserSearchForm(
+ 'SearchForm',
+ 'get',
+ $pageUrl,
+ 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',
+ MEDIA_BASE_URL . 'index.php'
+ );
+ $searchForm->configureForm(
+ Toolkit_Database::getInstance(),
+ $id
+ );
+
+ $widget->setSearchForm($searchForm);
+
+ $couponForm = new HTML_QuickForm(
+ 'coupon_form',
+ 'post',
+ MEDIA_BASE_URL . 'Toolkit/Coupons/print.php'
+ );
+ $renderer =& $couponForm->defaultRenderer();
+ $renderer->clearAllTemplates();
+ return $widget->toHtml($couponForm, $tEngine, 'coupons.html');
+ }
+
+ private function _isMemberActive($memberId)
+ {
+ try {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT active
+ FROM member
+ WHERE member_id = :member_id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':member_id', $memberId, PDO::PARAM_INT);
+ $stmt->execute();
+ return $stmt->fetchColumn();
+ } catch (PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+
+ }
+ // {{{ getContent()
+
+ /**
+ * Description of getContent()
+ *
+ * @return string
+ * @access public
+ */
+ public function getContent()
+ {
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/member-link.js';
+ $breadCrumbsBuilder = $this->breadCrumbsFactory->createBreadCrumbsHelper();
+ $page = $this->pageGateway->find($this->id);
+
+ $coupons = null;
+ if (defined('COUPONS') && COUPONS) {
+ $coupons = $this->_getPageCoupons($this->id);
+ }
+
+ if ($memberId = filter_input(INPUT_GET, 'member_id', FILTER_VALIDATE_INT)) {
+ // check and see if the member is inactive
+ // if they are then don't show bread crumb and give out 404 header
+ if (!$this->_isMemberActive($memberId)) {
+ header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
+ $badPage = new Toolkit_Template_Page_Bad();
+ return $badPage->getContent();
+ } else {
+ $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..b091e75
--- /dev/null
+++ b/Toolkit/Template/Page/SiteMap.php
@@ -0,0 +1,237 @@
+
+ * @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'][] = MEDIA_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)
+ {
+ if ( defined('MEMBERS_CATEGORY')
+ && defined('MEMBERS_DB')
+ && MEMBERS_DB
+ ) {
+ $sql = "
+ SELECT id, navigation_name, parent, include_members
+ FROM pages
+ WHERE parent = :parent
+ AND active = true
+ AND id != " . MEMBERS_CATEGORY . "
+ ORDER BY parent, pos";
+ } else {
+ $sql = "
+ SELECT id, navigation_name, parent
+ FROM pages
+ WHERE parent = :parent
+ AND active = true
+ ORDER BY parent, pos";
+ }
+
+ try {
+
+ $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 = array();
+ if ($row['include_members']) {
+ $subs = $this->_getMembersForPage($row['id']);
+ }
+ $subs2 = $this->getNavArray($row['id']);
+ if ($subs2) {
+ foreach ($subs2 as $subsub) {
+ $subs[] = $subsub;
+ }
+ }
+ 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'
+ );
+ }
+ }
+
+ private function _getMembersForPage($pageId)
+ {
+ $members = array();
+ $memberCats = array();
+ $memberRegs = array();
+ try {
+ // get member categories for the page
+ $sql = "
+ SELECT *
+ FROM toolbox.member_categories2toolbox_pages
+ WHERE page = :page";
+ $stmt = $this->_dbh->prepare($sql);
+ $stmt->bindParam(":page", $pageId, PDO::PARAM_INT);
+ $stmt->execute();
+ while ($memberCategory = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ $memberCats[] = $memberCategory['category'];
+ }
+ // get member regions for the page
+ $sql = "
+ SELECT *
+ FROM toolbox.member_regions2toolbox_pages
+ WHERE page = :page";
+ $stmt = $this->_dbh->prepare($sql);
+ $stmt->bindParam(":page", $pageId, PDO::PARAM_INT);
+ $stmt->execute();
+ while ($memberRegions = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ $memberRegs[] = $memberRegions['region'];
+ }
+ // if they're both empty then get list of all members
+ $where = array("active");
+ if (!empty($memberCats)) {
+ $where[] = "member_id IN (
+ SELECT member_id
+ FROM member_category
+ WHERE category_id IN (" . implode(',', $memberCats) . "))";
+ }
+ if (!empty($memberRegs)) {
+ $where[] = "(
+ region IN (" . implode(',', $memberRegs) . ")
+ OR
+ region IS NULL)";
+
+ }
+ $sql = "
+ SELECT member_id,member_name
+ FROM member";
+ if (!empty($where)) {
+ $sql .= " WHERE " . implode(' AND ', $where);
+ }
+ $sql .= " ORDER BY member_name";
+ $stmt = $this->_dbh->query($sql);
+ while ($member = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ $memberName = str_replace(' ', '-', $member['member_name']);
+ $pattern = '/[\/#&?\'"]|amp;/';
+ $name = preg_replace(
+ $pattern,
+ '',
+ strip_tags(strtolower(trim($memberName)))
+ );
+ $url = MEDIA_BASE_URL . "member-{$pageId}/"
+ . htmlspecialchars($name) . "-{$member['member_id']}.html";
+ $members[$member['member_id']] = array(
+ 'label' => $member['member_name'],
+ 'url' => $url
+ );
+ }
+ } catch (PDOException $e) {
+ Toolkit_Logger::logException('DB Error', $e);
+ throw new Toolkit_Template_Exception(
+ 'Unable to fetch members for sitemap page'
+ );
+ }
+ return $members;
+ }
+}
+?>
diff --git a/Toolkit/Template/Page/Toolbox.php b/Toolkit/Template/Page/Toolbox.php
new file mode 100644
index 0000000..1e50f90
--- /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',
+ MEDIA_BASE_URL . 'index.php'
+ );
+ $searchForm->configureForm(
+ Toolkit_Database::getInstance(),
+ $id
+ );
+
+ $widget->setSearchForm($searchForm);
+
+ $couponForm = new HTML_QuickForm(
+ 'coupon_form',
+ 'post',
+ MEDIA_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 = '';
+ foreach ($this->paragraphLinks as $anchor) {
+ $links .= "$anchor ";
+ }
+ $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..7b9648f
--- /dev/null
+++ b/Toolkit/Template/PageControllerAbstract.php
@@ -0,0 +1,106 @@
+
+ * @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 ($memberId = filter_var($_REQUEST['member_id'], FILTER_VALIDATE_INT)) {
+ // get member name and put in title
+ $sql = "
+ SELECT member_name,description
+ FROM member
+ WHERE member_id = {$memberId}";
+ if ($member = $this->registry->dbh->query($sql)->fetch(PDO::FETCH_ASSOC)) {
+ $memberName = htmlentities(strip_tags($member['member_name']));
+ $glmPage->pageTitle = $memberName.' - '.$glmPage->pageTitle;
+ $glmPage->metaTags
+ = htmlentities(
+ substr(
+ trim(strip_tags($member['description'])), 0, 250
+ ), ENT_QUOTES, 'UTF-8'
+ );
+ }
+ }
+
+ $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 '' . $this->getPath() . '
';
+ }
+
+ // }}}
+ // {{{ 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..64c5b9b
--- /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..bb7e35e
--- /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: ' . MEDIA_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: ' . MEDIA_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..3d47d78
--- /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: ' . MEDIA_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: ' . MEDIA_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..5c87fdf
--- /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',
+ MEDIA_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: ' . MEDIA_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..10a9cc1
--- /dev/null
+++ b/Toolkit/Toolbox/Forms/EditPage.php
@@ -0,0 +1,1158 @@
+
+ * @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 = " ";
+
+ $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',
+ 'name'
+ );
+
+ // 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 = MEDIA_BASE_URL;
+
+ $renderer->setFormTemplate(
+ ""
+ );
+
+ $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",
+ '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'][]
+ = MEDIA_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js';
+ $GLOBALS['bottomScripts'][]
+ = CKEDITOR_JS . '';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_BASE_URL . 'Toolkit/Toolbox/libjs/edit-page.js';
+
+ $GLOBALS['styleSheets'][]
+ = MEDIA_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.css';
+ $GLOBALS['styleSheets'][]
+ = MEDIA_BASE_URL . 'css/contactform.css';
+ $GLOBALS['styleSheets'][]
+ = MEDIA_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..f83c4a4
--- /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:
+
+
+
+ Remove File
+
+
+
+
+ ';
+ }
+ $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'][]
+ = MEDIA_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js';
+ $GLOBALS['bottomScripts'][]
+ = CKEDITOR_JS . '';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/plugins/ajaxUpload/3.9/ajaxupload.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/development-bundle/ui/minified/jquery.ui.sortable.min.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_BASE_URL . 'Toolkit/Toolbox/libjs/edit-paragraph.js';
+
+ $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'css/contactform.css';
+ $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'Toolkit/Toolbox/styles.css';
+ $GLOBALS['styleSheets'][]
+ = MEDIA_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..d0e367e
--- /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'][]
+ = MEDIA_BASE_URL . 'css/contactform.css';
+ $GLOBALS['styleSheets'][]
+ = MEDIA_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..627ffd1
--- /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..bddb1e7
--- /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..528d4b7
--- /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' => MEDIA_BASE_URL . 'admin/toolbox.php',
+ 'desc' => "Display all the published pages",
+ ),
+ 'draftPages' => array(
+ 'Title' => 'Page Drafts',
+ 'url' => MEDIA_BASE_URL . 'admin/toolbox.php?rt=ListDrafts',
+ 'desc' => 'Display all the page drafts'
+
+ ),
+ 'editPage' => array(
+ 'Title' => "Create New Page",
+ 'url' => MEDIA_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' => MEDIA_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' => MEDIA_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..d25ca29
--- /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..356d9e5
--- /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 = " ";
+ $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..6a9c237
--- /dev/null
+++ b/Toolkit/Toolbox/PageGatewayPublish.php
@@ -0,0 +1,610 @@
+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)
+ {
+ $keyword = strtolower(trim($keyword));
+ try {
+ $pageSql = "
+ SELECT id
+ FROM pages
+ WHERE lower(trim(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)
+ RETURNING id";
+
+ $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();
+
+ $pageId = $pageStmt->fetchColumn();
+
+ if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ $this->_updateMemberCategories(
+ $data['member_categories'],
+ $pageId
+ );
+ $this->_updateMemberRegions(
+ $data['member_regions'],
+ $pageId
+ );
+ }
+
+ if (defined('COUPONS') && COUPONS) {
+ $this->_updateCouponCategories(
+ $data['coupon_categories'],
+ $pageId
+ );
+ }
+
+ $paragraphStmt = $this->dbh->prepare($paragraphSql);
+ $this->setParagraphVars($paragraphStmt, $data);
+ $paragraphStmt->bindParam(':page', $pageId);
+ $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 $pageId;
+ } 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..4ee4b5e
--- /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 ' ';
+ }
+
+ $activeFormat = '';
+ $activeFormat .= $this->getActiveBallImage($branch);
+ $activeFormat .= ' ';
+
+ return sprintf(
+ $activeFormat,
+ $branch['id'],
+ MEDIA_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 ' ';
+ }
+
+ $activeFormat = '';
+ $activeFormat .= $this->getActiveMobileBallImage($branch);
+ $activeFormat .= ' ';
+
+ return sprintf(
+ $activeFormat,
+ $branch['id'],
+ MEDIA_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 = ' ';
+
+ $up = sprintf(
+ $format,
+ MEDIA_APP_BASE_URL . "assets/icons/arrow_up.png",
+ 'Move Up Arrow'
+ );
+
+ $down = sprintf(
+ $format,
+ MEDIA_APP_BASE_URL . "assets/icons/arrow_down.png",
+ 'Move Down Arrow'
+ );
+ } else {
+ $format = ' ';
+
+ $up = sprintf(
+ $format,
+ MEDIA_APP_BASE_URL . "assets/icons/arrow_up.png",
+ 'Up',
+ 'Up'
+ );
+
+ $down = sprintf(
+ $format,
+ MEDIA_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 = MEDIA_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'][] = MEDIA_BASE_URL . 'Toolkit/Toolbox/libjs/pagesTree.js';
+ $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js';
+ $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/lib/jquery.cookie.js';
+ $GLOBALS['bottomScripts'][] = MEDIA_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..357d865
--- /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 = MEDIA_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..1e20995
--- /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 = MEDIA_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..2c0d153
--- /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..6bc23e8
--- /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',
+ MEDIA_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: ' . MEDIA_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: '
+ . MEDIA_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..5553293
--- /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',
+ MEDIA_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: ' . MEDIA_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: ' . MEDIA_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..7ffc526
--- /dev/null
+++ b/Toolkit/Toolbox/ParagraphsDraftTree.php
@@ -0,0 +1,86 @@
+';
+ $activeFormat .= $this->getActiveBallImage($branch);
+ $activeFormat .= '';
+
+ return sprintf(
+ $activeFormat,
+ MEDIA_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'][] = MEDIA_BASE_URL . 'Toolkit/Toolbox/libjs/paragraph-tree.js';
+ $GLOBALS['bottomScripts'][] = MEDIA_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..1f836c5
--- /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'],
+ MEDIA_BASE_URL . "admin/toolbox.php?rt=Paragraphs&id={$branch['id']}",
+ $branch['active_alt']
+ );
+ }
+
+ // }}}
+ // {{{ _getMoveArrows()
+
+ private function _getMoveArrows()
+ {
+ $format = ' ';
+
+ $up = sprintf(
+ $format,
+ MEDIA_APP_BASE_URL . "assets/icons/arrow_up.png",
+ 'Up',
+ 'Up'
+ );
+
+ $down = sprintf(
+ $format,
+ MEDIA_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'][] = MEDIA_BASE_URL . 'Toolkit/Toolbox/libjs/paragraph-tree.js';
+ $GLOBALS['bottomScripts'][] = MEDIA_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..56fbb25
--- /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..b5a4b0a
--- /dev/null
+++ b/Toolkit/Toolbox/SearchTree.php
@@ -0,0 +1,35 @@
+ ';
+ $img = $branch['active'] ? 'grnball.gif' : 'redball.gif';
+ $q = urlencode(stripslashes($_GET['q']));
+ return sprintf(
+ $activeFormat,
+ MEDIA_BASE_URL . "admin/toolbox.php?id={$branch['id']}&_qf__search_form=&rt=Search&q=$q",
+ $branch['active_alt'],
+ MEDIA_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..58d2abc
--- /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 = ' ';
+
+ $show = sprintf(
+ $imgFormat,
+ ($branch['active']) ? '' : 'style="display: none;"',
+ MEDIA_BASE_URL . "Toolkit/Toolbox/assets/grnball.gif",
+ 'Active Ball'
+ );
+
+ $hide = sprintf(
+ $imgFormat,
+ ($branch['active']) ? 'style="display: none;"' : '',
+ MEDIA_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 = ' ';
+
+ $show = sprintf(
+ $imgFormat,
+ ($branch['mobile_active']) ? '' : 'style="display: none;"',
+ MEDIA_BASE_URL . "Toolkit/Toolbox/assets/mobilemgreen.jpg",
+ 'Active Ball'
+ );
+
+ $hide = sprintf(
+ $imgFormat,
+ ($branch['mobile_active']) ? 'style="display: none;"' : '',
+ MEDIA_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'][] = MEDIA_BASE_URL . 'admin/main.css';
+ $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'Toolkit/Toolbox/styles.css';
+ $GLOBALS['topScripts'][]
+ = MEDIA_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 0000000..ee11ab4
Binary files /dev/null and b/Toolkit/Toolbox/assets/arrow.png differ
diff --git a/Toolkit/Toolbox/assets/arrowClosed.png b/Toolkit/Toolbox/assets/arrowClosed.png
new file mode 100755
index 0000000..3b34262
Binary files /dev/null and b/Toolkit/Toolbox/assets/arrowClosed.png differ
diff --git a/Toolkit/Toolbox/assets/arrowOpen.png b/Toolkit/Toolbox/assets/arrowOpen.png
new file mode 100755
index 0000000..6967dea
Binary files /dev/null and b/Toolkit/Toolbox/assets/arrowOpen.png differ
diff --git a/Toolkit/Toolbox/assets/collapse.png b/Toolkit/Toolbox/assets/collapse.png
new file mode 100755
index 0000000..d10e051
Binary files /dev/null and b/Toolkit/Toolbox/assets/collapse.png differ
diff --git a/Toolkit/Toolbox/assets/expand.png b/Toolkit/Toolbox/assets/expand.png
new file mode 100755
index 0000000..38dcfc0
Binary files /dev/null and b/Toolkit/Toolbox/assets/expand.png differ
diff --git a/Toolkit/Toolbox/assets/grnball.gif b/Toolkit/Toolbox/assets/grnball.gif
new file mode 100755
index 0000000..5f7740b
Binary files /dev/null and b/Toolkit/Toolbox/assets/grnball.gif differ
diff --git a/Toolkit/Toolbox/assets/mobilemgreen.jpg b/Toolkit/Toolbox/assets/mobilemgreen.jpg
new file mode 100644
index 0000000..a5fc6ce
Binary files /dev/null and b/Toolkit/Toolbox/assets/mobilemgreen.jpg differ
diff --git a/Toolkit/Toolbox/assets/mobilemred.jpg b/Toolkit/Toolbox/assets/mobilemred.jpg
new file mode 100644
index 0000000..217826d
Binary files /dev/null and b/Toolkit/Toolbox/assets/mobilemred.jpg differ
diff --git a/Toolkit/Toolbox/assets/redball.gif b/Toolkit/Toolbox/assets/redball.gif
new file mode 100755
index 0000000..7005133
Binary files /dev/null and b/Toolkit/Toolbox/assets/redball.gif differ
diff --git a/Toolkit/Toolbox/assets/template1.gif b/Toolkit/Toolbox/assets/template1.gif
new file mode 100755
index 0000000..327d943
Binary files /dev/null and b/Toolkit/Toolbox/assets/template1.gif differ
diff --git a/Toolkit/Toolbox/assets/template2.gif b/Toolkit/Toolbox/assets/template2.gif
new file mode 100755
index 0000000..edf3d8b
Binary files /dev/null and b/Toolkit/Toolbox/assets/template2.gif differ
diff --git a/Toolkit/Toolbox/assets/template3.gif b/Toolkit/Toolbox/assets/template3.gif
new file mode 100755
index 0000000..16e2107
Binary files /dev/null and b/Toolkit/Toolbox/assets/template3.gif differ
diff --git a/Toolkit/Toolbox/assets/template4.gif b/Toolkit/Toolbox/assets/template4.gif
new file mode 100755
index 0000000..32174dd
Binary files /dev/null and b/Toolkit/Toolbox/assets/template4.gif differ
diff --git a/Toolkit/Toolbox/assets/template5.gif b/Toolkit/Toolbox/assets/template5.gif
new file mode 100755
index 0000000..6c36b50
Binary files /dev/null and b/Toolkit/Toolbox/assets/template5.gif differ
diff --git a/Toolkit/Toolbox/assets/template6.gif b/Toolkit/Toolbox/assets/template6.gif
new file mode 100644
index 0000000..28d140e
Binary files /dev/null and b/Toolkit/Toolbox/assets/template6.gif differ
diff --git a/Toolkit/Toolbox/config.ini b/Toolkit/Toolbox/config.ini
new file mode 100644
index 0000000..3d81908
--- /dev/null
+++ b/Toolkit/Toolbox/config.ini
@@ -0,0 +1,3 @@
+[conf]
+applicationName = "Toolbox"
+lockMainNavPages = Off
diff --git a/Toolkit/Toolbox/fixPageNoContent.php b/Toolkit/Toolbox/fixPageNoContent.php
new file mode 100644
index 0000000..8b59bad
--- /dev/null
+++ b/Toolkit/Toolbox/fixPageNoContent.php
@@ -0,0 +1,48 @@
+beginTransaction();
+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('Uploading ');
+ $('#filename').after(' Successfully uploaded ');
+ 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 = ''+i+' ';
+ $(this).children('select').append(html);
+ }
+ });
+ },
+
+ moveBack: function($li, $sibling)
+ {
+ alert('There was an error moving your page');
+ $li.detach();
+ $li.insertBefore($sibling);
+ PagesTree.updateMoveArrowVisibility();
+ },
+
+ updateMoveArrowVisibility: function()
+ {
+ $('img.moveUp, img.moveDown').show().removeClass('tOff');
+
+ var $tree = $('#tree');
+ $tree.find('ul').each(function() {
+ var $firstUpArrow = $(this).find('img.moveUp:first'),
+ $lis = $(this).children().last();
+ $firstUpArrow.addClass('tOff');
+
+ $lis.each(function() {
+ var $lastDownArrow = $(this).find('.right-element:first img.moveDown:last');
+ $lastDownArrow.addClass('tOff');
+ });
+ });
+ }
+};
+
+$(document).ready(PagesTree.init);
diff --git a/Toolkit/Toolbox/libjs/paragraph-tree.js b/Toolkit/Toolbox/libjs/paragraph-tree.js
new file mode 100644
index 0000000..f0fdba6
--- /dev/null
+++ b/Toolkit/Toolbox/libjs/paragraph-tree.js
@@ -0,0 +1,143 @@
+var ParagraphTree =
+{
+ init: function()
+ {
+ ParagraphTree.updateMoveArrowVisibility();
+ var $myTree = $('#tree');
+ if ($myTree.children('ul').size() > 0) {
+ $myTree.tree();
+ }
+
+ $('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);
+ ParagraphTree.updateMoveArrowVisibility();
+ $.ajax({
+ url : '../toolbox-paragraph-move/'+$id+'/down/',
+ async: false,
+ cache: false,
+ success: function(html) {
+ if (html == 0) {
+ ParagraphTree.moveBack($li, $sibling);
+ } else if ($sibling.hasClass('last')) {
+ $sibling.removeClass('last');
+ $li.addClass('last');
+ }
+ },
+ error: function() {
+ ParagraphTree.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);
+ if ($li.hasClass('last')) {
+ $li.removeClass('last');
+ $sibling.addClass('last');
+ }
+ ParagraphTree.updateMoveArrowVisibility();
+ $.ajax({
+ url : '../toolbox-paragraph-move/'+$id+'/up/',
+ async: false,
+ cache: false,
+ success: function(html) {
+ if (html == 0) {
+ ParagraphTree.moveBack($li, $sibling);
+ } else if ($li.hasClass('last')) {
+ $li.removeClass('last');
+ $sibling.addClass('last');
+ }
+ },
+ error: function() {
+ ParagraphTree.moveBack($li, $sibling);
+ }
+ });
+ }
+ });
+
+ $('.active-ball').click(function(event) {
+ event.preventDefault();
+ var id = $(this).attr('rel');
+ var _this = $(this);
+ $.get('../toolbox-paragraph-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);
+ }
+ });
+ });
+ $('ul.ltr').each(function(){
+ var count = $(this).children('li').size();
+ ParagraphTree.loadSelectOptions(
+ $(this).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-paragraph-move-sel/' + id + '/' + oldpos + '/' + newpos + '/';
+ });
+ });
+ },
+
+ loadSelectOptions: function(ul, count)
+ {
+ ul.each(function(){
+ var selCount = $(this).children('select').attr('rel');
+ var begin = 1;
+ for (i = begin; i <= count; ++i) {
+ var realNum = i + 1;
+ var html = ''+ i +' ';
+ $(this).children('select').append(html);
+ }
+ });
+ },
+
+ moveBack: function($li, $sibling)
+ {
+ alert('There was an error moving your page');
+ $li.detach();
+ $li.insertBefore($sibling);
+ ParagraphTree.updateMoveArrowVisibility();
+ },
+
+ updateMoveArrowVisibility: function()
+ {
+ $('img.moveUp, img.moveDown').show().removeClass('tOff');
+
+ var $tree = $('#tree');
+ $tree.find('ul').each(function() {
+ var $firstUpArrow = $(this).find('img.moveUp:first');
+ $firstUpArrow.addClass('tOff');
+
+ var $lis = $(this).children().last();
+ $lis.each(function() {
+ var $lastDownArrow = $(this).find('.right-element:first img.moveDown:last');
+ $lastDownArrow.addClass('tOff');
+ });
+ });
+ }
+};
+
+$(document).ready(ParagraphTree.init);
diff --git a/Toolkit/Toolbox/moveBySelect.php b/Toolkit/Toolbox/moveBySelect.php
new file mode 100644
index 0000000..35dfcb3
--- /dev/null
+++ b/Toolkit/Toolbox/moveBySelect.php
@@ -0,0 +1,126 @@
+'.print_r($_REQUEST, true).'';
+$someNewPos = 999;
+try {
+ // start transaction
+ $dbh->beginTransaction();
+ $sql = "
+ SELECT parent
+ FROM pages
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ":id",
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $parent = $stmt->fetchColumn();
+ //var_dump($parent);
+ $updateSql = "
+ UPDATE pages
+ SET pos = :pos
+ WHERE id = :id";
+ $updateStmt = $dbh->prepare($updateSql);
+ $moveDownSql = "
+ SELECT id
+ FROM pages
+ WHERE parent = :parent
+ AND pos >= :oldpos
+ AND pos <= :newpos
+ ORDER BY pos";
+ $moveDownStmt = $dbh->prepare($moveDownSql);
+ $moveUpSql = "
+ UPDATE pages
+ SET pos = pos + 1
+ WHERE parent = :parent
+ AND pos BETWEEN :newpos AND :oldpos";
+ $moveUpStmt = $dbh->prepare($moveUpSql);
+
+ $updateStmt->bindParam(
+ ':pos',
+ $someNewPos,
+ PDO::PARAM_INT
+ );
+ $updateStmt->bindParam(
+ ':id',
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $updateStmt->execute();
+ // going to a higher pos (moving down)
+ if ($_REQUEST['newpos'] > $_REQUEST['oldpos']) {
+ //echo ' '.print_r($_REQUEST, true).' ';
+ //var_dump($parent);
+ $moveDownStmt->bindParam(
+ ':parent',
+ $parent,
+ PDO::PARAM_INT
+ );
+ $moveDownStmt->bindParam(
+ ':oldpos',
+ $_REQUEST['oldpos'],
+ PDO::PARAM_INT
+ );
+ $moveDownStmt->bindParam(
+ ':newpos',
+ $_REQUEST['newpos'],
+ PDO::PARAM_INT
+ );
+ $moveDownStmt->execute();
+ $pos = $_REQUEST['oldpos'];
+ while ($row = $moveDownStmt->fetch(PDO::FETCH_ASSOC)) {
+ //var_dump($row);
+ $updateStmt->bindParam(
+ ':pos',
+ $pos,
+ PDO::PARAM_INT
+ );
+ $updateStmt->bindParam(
+ ':id',
+ $row['id']
+ );
+ $updateStmt->execute();
+ ++$pos;
+ }
+ // moving up
+ } else {
+ $moveUpStmt->bindParam(
+ ':parent',
+ $parent,
+ PDO::PARAM_INT
+ );
+ $moveUpStmt->bindParam(
+ ':oldpos',
+ $_REQUEST['oldpos'],
+ PDO::PARAM_INT
+ );
+ $moveUpStmt->bindParam(
+ ':newpos',
+ $_REQUEST['newpos'],
+ PDO::PARAM_INT
+ );
+ $moveUpStmt->execute();
+ }
+
+ $updateStmt->bindParam(
+ ':pos',
+ $_REQUEST['newpos'],
+ PDO::PARAM_INT
+ );
+ $updateStmt->bindParam(
+ ':id',
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $updateStmt->execute();
+ $dbh->commit();
+} catch (PDOException $e) {
+ $dbh->rollback();
+ Toolkit_Logger::logException('DB Error', $e);
+}
+$cache = new Cache_Lite($GLOBALS['cacheOptions']);
+$cache->clean('Toolbox');
+header('Location: '.MEDIA_BASE_URL.'admin/toolbox.php?showpos=1');
diff --git a/Toolkit/Toolbox/moveBySelectPara.php b/Toolkit/Toolbox/moveBySelectPara.php
new file mode 100644
index 0000000..b0d0865
--- /dev/null
+++ b/Toolkit/Toolbox/moveBySelectPara.php
@@ -0,0 +1,119 @@
+beginTransaction();
+ $sql = "
+ SELECT page
+ FROM paragraphs
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ":id",
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $page = $stmt->fetchColumn();
+ $updateSql = "
+ UPDATE paragraphs
+ SET pos = :pos
+ WHERE id = :id";
+ $updateStmt = $dbh->prepare($updateSql);
+ $moveDownSql = "
+ SELECT id
+ FROM paragraphs
+ WHERE page = :page
+ AND pos >= :oldpos
+ AND pos <= :newpos
+ ORDER BY pos";
+ $moveDownStmt = $dbh->prepare($moveDownSql);
+ $moveUpSql = "
+ UPDATE paragraphs
+ SET pos = pos + 1
+ WHERE page = :page
+ AND pos BETWEEN :newpos AND :oldpos";
+ $moveUpStmt = $dbh->prepare($moveUpSql);
+
+ $updateStmt->bindParam(
+ ':pos',
+ $someNewPos,
+ PDO::PARAM_INT
+ );
+ $updateStmt->bindParam(
+ ':id',
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $updateStmt->execute();
+ if ($_REQUEST['newpos'] > $_REQUEST['oldpos']) {
+ $moveDownStmt->bindParam(
+ ':page',
+ $page,
+ PDO::PARAM_INT
+ );
+ $moveDownStmt->bindParam(
+ ':oldpos',
+ $_REQUEST['oldpos'],
+ PDO::PARAM_INT
+ );
+ $moveDownStmt->bindParam(
+ ':newpos',
+ $_REQUEST['newpos'],
+ PDO::PARAM_INT
+ );
+ $moveDownStmt->execute();
+ $pos = $_REQUEST['oldpos'];
+ while ($row = $moveDownStmt->fetch(PDO::FETCH_ASSOC)) {
+ //var_dump($row);
+ $updateStmt->bindParam(
+ ':pos',
+ $pos,
+ PDO::PARAM_INT
+ );
+ $updateStmt->bindParam(
+ ':id',
+ $row['id']
+ );
+ $updateStmt->execute();
+ ++$pos;
+ }
+ } else {
+ $moveUpStmt->bindParam(
+ ':page',
+ $page,
+ PDO::PARAM_INT
+ );
+ $moveUpStmt->bindParam(
+ ':oldpos',
+ $_REQUEST['oldpos'],
+ PDO::PARAM_INT
+ );
+ $moveUpStmt->bindParam(
+ ':newpos',
+ $_REQUEST['newpos'],
+ PDO::PARAM_INT
+ );
+ $moveUpStmt->execute();
+ }
+
+ $updateStmt->bindParam(
+ ':pos',
+ $_REQUEST['newpos'],
+ PDO::PARAM_INT
+ );
+ $updateStmt->bindParam(
+ ':id',
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $updateStmt->execute();
+ $dbh->commit();
+} catch (PDOException $e) {
+ $dbh->rollback();
+ Toolkit_Logger::logException('DB Error', $e);
+}
+$cache = new Cache_Lite($GLOBALS['cacheOptions']);
+$cache->clean('Toolbox');
+header('Location: '.MEDIA_BASE_URL.'admin/toolbox.php?rt=Paragraphs&pageid='.$page);
diff --git a/Toolkit/Toolbox/pageChangeState.php b/Toolkit/Toolbox/pageChangeState.php
new file mode 100644
index 0000000..d4da710
--- /dev/null
+++ b/Toolkit/Toolbox/pageChangeState.php
@@ -0,0 +1,32 @@
+prepare($sql);
+ $stmt->bindParam(':id', $_GET['catid'], PDO::PARAM_INT);
+ $res = $stmt->execute();
+
+ $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+ $cache->clean('Toolbox');
+
+ echo (int) $res;
+ return $res;
+} catch (PDOException $e) {
+ Toolkit_Logger::logException('DB Error', $e);
+ return false;
+}
+?>
diff --git a/Toolkit/Toolbox/pageMobileChangeState.php b/Toolkit/Toolbox/pageMobileChangeState.php
new file mode 100644
index 0000000..015aa55
--- /dev/null
+++ b/Toolkit/Toolbox/pageMobileChangeState.php
@@ -0,0 +1,31 @@
+prepare($sql);
+ $stmt->bindParam(':id', $_GET['catid'], PDO::PARAM_INT);
+ $res = $stmt->execute();
+
+ $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+ $cache->clean('Toolbox');
+
+ echo (int) $res;
+ return $res;
+} catch (PDOException $e) {
+ Toolkit_Logger::logException('DB Error', $e);
+ return false;
+}
+?>
diff --git a/Toolkit/Toolbox/pageMove.php b/Toolkit/Toolbox/pageMove.php
new file mode 100644
index 0000000..b989d7b
--- /dev/null
+++ b/Toolkit/Toolbox/pageMove.php
@@ -0,0 +1,96 @@
+setRequest($request);
+$channel->setResponse($response);
+
+// start output buffering
+ob_start();
+
+// Now you can make calls to the logger
+
+$dbh = Toolkit_Database::getInstance();
+
+extract($_GET);
+
+try {
+ $dbh->beginTransaction();
+ if ($direction == 'down') {
+ $sql = "
+ UPDATE pages
+ SET pos = pos - 1
+ WHERE id <> :id
+ AND id <> :home_id
+ AND pos = (
+ SELECT pos + 1
+ FROM pages
+ WHERE id = :id)
+ AND parent = (
+ SELECT parent
+ FROM pages
+ WHERE id = :id)";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+ $stmt->bindValue(':home_id', HOME_ID, PDO::PARAM_INT);
+ $stmt->execute();
+
+ $sql = "
+ UPDATE pages
+ SET pos = pos + 1
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+ $stmt->execute();
+ } elseif ($direction == 'up') {
+ $sql = "
+ UPDATE pages
+ SET pos = pos + 1
+ WHERE id <> :id
+ AND id <> :home_id
+ AND pos = (
+ SELECT pos - 1
+ FROM pages
+ WHERE id = :id)
+ AND parent = (
+ SELECT parent
+ FROM pages
+ WHERE id = :id)";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+ $stmt->bindValue(':home_id', HOME_ID, PDO::PARAM_INT);
+ $stmt->execute();
+
+ $sql = "
+ UPDATE pages
+ SET pos = pos - 1
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+ $stmt->execute();
+ }
+
+ $dbh->commit();
+ echo 1;
+} catch (PDOException $e) {
+ $dbh->rollback();
+ if ('production' == strtolower($_SERVER['GLM_HOST_ID'])) {
+ $logger->crit($e->getMessage());
+ } else {
+ Toolkit_Logger::logException('DB Error', $e);
+ }
+ echo 0;
+}
+// Flush log data to browser
+$channel->flush();
+$response->sendHeaders();
+die();
diff --git a/Toolkit/Toolbox/paragraphChangeState.php b/Toolkit/Toolbox/paragraphChangeState.php
new file mode 100644
index 0000000..88aa1a9
--- /dev/null
+++ b/Toolkit/Toolbox/paragraphChangeState.php
@@ -0,0 +1,44 @@
+prepare($sql);
+ $stmt->bindParam(':id', $_GET['paragraphId'], PDO::PARAM_INT);
+ $res = $stmt->execute();
+
+
+ $sql = "
+ SELECT page
+ FROM paragraphs
+ WHERE id = :id";
+
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $_GET['paragraphId'], PDO::PARAM_INT);
+ $stmt->execute();
+ $stmt->bindColumn('page', $pageId);
+ $stmt->fetch(PDO::FETCH_ASSOC);
+
+ $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+ $cache->clean('Toolbox');
+
+ echo (int) $res;
+ return $res;
+} catch (PDOException $e) {
+ Toolkit_Logger::logException('DB Error', $e);
+ return false;
+}
+?>
diff --git a/Toolkit/Toolbox/paragraphFileUpload.php b/Toolkit/Toolbox/paragraphFileUpload.php
new file mode 100644
index 0000000..2bc5553
--- /dev/null
+++ b/Toolkit/Toolbox/paragraphFileUpload.php
@@ -0,0 +1,14 @@
+upload('userfile');
+} 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 json_encode($res);
+?>
diff --git a/Toolkit/Toolbox/paragraphMove.php b/Toolkit/Toolbox/paragraphMove.php
new file mode 100644
index 0000000..d53ebe7
--- /dev/null
+++ b/Toolkit/Toolbox/paragraphMove.php
@@ -0,0 +1,51 @@
+beginTransaction();
+ if ($direction == 'down') {
+ // Update paragraph nodes on this page who lie at the target node
+ // position and the position just after it.
+ $sql = "
+ UPDATE paragraphs
+ SET pos = CASE WHEN id = :id
+ THEN pos + 1 ELSE pos - 1 END
+ WHERE page = (SELECT page FROM paragraphs WHERE id = :id)
+ AND pos BETWEEN (SELECT pos FROM paragraphs WHERE id = :id)
+ AND (SELECT pos + 1 FROM paragraphs WHERE id = :id)";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+ $stmt->execute();
+ } elseif ($direction == 'up') {
+ // Update paragraph nodes on this page who lie at the target node
+ // position and the position just before it.
+ $sql = "
+ UPDATE paragraphs
+ SET pos = CASE WHEN id = :id
+ THEN pos - 1 ELSE pos + 1 END
+ WHERE page = (SELECT page FROM paragraphs WHERE id = :id)
+ AND pos BETWEEN (SELECT pos - 1 FROM paragraphs WHERE id = :id)
+ AND (SELECT pos FROM paragraphs WHERE id = :id)";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+ $stmt->execute();
+ }
+
+ $dbh->commit();
+ die();
+} catch (PDOException $e) {
+ $dbh->rollback();
+ Toolkit_Logger::logException('DB Error', $e);
+ throw new Toolkit_Toolbox_Exception(
+ "unable to move paragraph `$id` `$direction`"
+ );
+}
+?>
diff --git a/Toolkit/Toolbox/styles.css b/Toolkit/Toolbox/styles.css
new file mode 100644
index 0000000..3be1ead
--- /dev/null
+++ b/Toolkit/Toolbox/styles.css
@@ -0,0 +1,132 @@
+.webform table { width: 742px; }
+.fieldcell { width: auto; }
+
+/* form section arrows */
+tr.hdr td {
+ background: #DDD url("//app.gaslightmedia.com/assets/icons/bullet_arrow_right.png") no-repeat;
+ padding-left: 15px;
+ cursor: pointer;
+ cursor: hand;
+}
+tr.hdr td:hover {
+ background-color: #e5e5e5;
+}
+tr.hdr td.open{
+ background-image: url("//app.gaslightmedia.com/assets/icons/bullet_arrow_down.png");
+}
+
+/* paragraph files */
+.files {
+ list-style-type: none;
+ margin: 0;
+ padding: 0;
+ width: 60%;
+}
+.files li {
+ margin: 0 3px 3px 3px;
+ padding: 0.4em;
+ padding-left: 1.5em;
+}
+.files li span {
+ position: absolute;
+ margin-left: -1.3em;
+}
+.files .ui-state-highlight {
+ height: 1.5em;
+ line-height: 1.2em;
+}
+#success_notification {
+ font-weight: bold;
+ color: #11a52f;
+}
+
+/* right tree element */
+.right-element {
+ float: left;
+ }
+.paragraph-line {
+ float: none !important;
+}
+.paragraph-line strong {
+ margin-left: 10px;
+ }
+/* highlight search matches in tree */
+.search {
+ color: orange;
+}
+
+/* Ove */
+#q {
+ border: 2px inset black;
+ height: 20px;
+ padding: 2px;
+ font-size: 16px;
+ width: 200px;
+ margin-right: 10px;
+ font-weight: bold}
+
+#tree li {
+ display: block;
+ line-height: 24px !important;
+}
+li.closed { background: url(assets/arrowClosed.png) no-repeat !important;}
+li.open { background: url(assets/arrowOpen.png) no-repeat !important;}
+/*.ltr>li {
+ border-bottom: 1px dashed #ccc;
+}*/
+#tree li.last {
+ float: none;
+}
+#tree {
+ width: 630px;
+}
+
+/*
+ * #tree ul {
+ * background: #ece;
+ * }
+ * #tree ul ul {
+ * background: #cee;
+ * }
+ * #tree ul ul ul {
+ * background: #eec;
+ * }
+ * #tree ul ul ul ul {
+ * background: #ede;
+ * }
+ */
+.right-element a {
+ text-decoration: underline !important;
+}
+
+#tree .editPage, .editPage:hover,
+#tree .editParagraphs, .editParagraphs:hover,
+#tree .pagePreview, .pagePreview:hover {
+ height: 16px;
+ padding: 0 5px 0 0px !important;
+ border: 0;
+}
+
+/*
+#tree .editPage, .editPage:hover { background: url(//app.gaslightmedia.com/assets/icons/page_edit.png) no-repeat; }
+#tree .editParagraphs, .editParagraphs:hover { background: url(//app.gaslightmedia.com/assets/icons/page_add.png) no-repeat; }
+#tree .pagePreview, .pagePreview:hover { background: url(//app.gaslightmedia.com/assets/icons/page_go.png) no-repeat; }
+
+#tree a:hover { color: green;}
+*/
+/* Lines */
+#tree li {
+ /* border-bottom: 1px dotted #666;
+ * padding-bottom: 1px;
+ */
+}
+
+/* Mousetip */
+.moveUp, .moveDown {
+ cursor: hand;
+ cursor: pointer;
+}
+.tOff {
+ visibility: hidden;
+}
+.form-success {border:1px solid green;color:green;padding:10px;margin:5px;}
diff --git a/Toolkit/Videos/AdminEditVideoForm.php b/Toolkit/Videos/AdminEditVideoForm.php
new file mode 100644
index 0000000..0977087
--- /dev/null
+++ b/Toolkit/Videos/AdminEditVideoForm.php
@@ -0,0 +1,309 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Videos_AdminEditVideoForm
+ *
+ * Handles the form generation and processing of the Video Edit Page
+ *
+ * @category Toolkit
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2008 Gaslight media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_Videos_AdminEditVideoForm
+ extends Toolkit_FormBuilder
+{
+ /**
+ * What do you want the success msg to be if the form validates successfully
+ *
+ * @var string
+ * @access protected
+ */
+ protected $successMsg
+ = 'Coupon 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'
+ )
+ );
+ public $errorMsg = '
+ There was a Problem with your form!
';
+
+ /**
+ * Setup Form Constants
+ *
+ * Constants are form values (hidden) fields most likely that cannot be
+ * changed by user input
+ *
+ * @return void
+ */
+ public function configureConstants()
+ {
+ $c = array();
+ $this->setConstants($c);
+ }
+
+ /**
+ * Setup Form Defaults
+ *
+ * if $_GET['id'] is numeric then it creates a Toolkit_Videos_Video
+ * class object and gets set as form element defaults
+ *
+ * @param PDO $dbh Database Connection
+ *
+ * @return void
+ */
+ public function configureDefaults(PDO $dbh)
+ {
+ $d = array();
+ if (is_numeric($_GET['id'])) {
+ $video = new Toolkit_Videos_VideoMapper($dbh);
+ $d = $video->getVideoById($_GET['id']);
+ }
+ $this->setDefaults($d);
+ }
+
+ /**
+ * Setup the Form elements
+ *
+ * @param PDO $dbh Database Connection
+ * @param Config_Container $c PEAR::Config_Container object
+ *
+ * @return void
+ */
+ public function configureElements(PDO $dbh, Config_Container $c)
+ {
+ $e = array();
+
+ // get reference to [conf] section of config file
+ $appHasFeaturedVideos
+ = $c->getItem('section', 'conf')
+ ->getItem('directive', 'featuredVideos')
+ ->getContent();
+ // All Elements are created here.
+ // This includes group element definitions.
+ $e[] = array(
+ 'type' => 'advcheckbox',
+ 'req' => false,
+ 'name' => 'active',
+ 'display' => 'Active',
+ 'val' => array(0, 1)
+ );
+ if ($appHasFeaturedVideos) {
+ $e[] = array(
+ 'type' => 'advcheckbox',
+ 'req' => false,
+ 'name' => 'featured',
+ 'display' => 'Featured',
+ 'val' => array(0, 1)
+ );
+ } else {
+ $e[] = array(
+ 'type' => 'hidden',
+ 'req' => false,
+ 'name' => 'featured'
+ );
+ }
+ $e[] = array(
+ 'type' => 'text',
+ 'req' => true,
+ 'name' => 'video_url',
+ 'display' => 'Video Link
+
+ Click on the \'Share\' function on the YouTube video
+ to get your link. If you\'re having problems click on "show options"
+ and select "long link" ',
+ 'opts' => array('class' => 'text','size'=>50)
+ );
+ $e[] = array(
+ 'type' => 'submit',
+ 'req' => false,
+ 'name' => 'submit_rmv',
+ 'display' => 'Submit Video',
+ 'opts' => array('id' => 'submit')
+ );
+ if (ctype_digit($_GET['id'])) {
+ $e[] = array(
+ 'type' => 'submit',
+ 'req' => false,
+ 'name' => 'delete_rmv',
+ 'display' => 'Delete Video',
+ 'opts' => array('id' => 'delete')
+ );
+ }
+
+ $this->setupElements($e);
+ }
+
+ /**
+ * Setup Form filters
+ *
+ * @return void
+ */
+ public function configureFilters()
+ {
+ $f = array();
+ $f[] = array(
+ 'element' => '__ALL__',
+ 'filter' => 'trim'
+ );
+ $f[] = array(
+ 'element' => 'url',
+ 'filter' => array('Toolkit_Common', 'filterURI')
+ );
+
+ $this->setupFilters($f);
+ }
+
+ /**
+ * Runs all function to setup the Form
+ *
+ * @param PDO $dbh Database Connection
+ * @param Config_Container $c PEAR::Config_Container object
+ *
+ * @return void
+ */
+ public function configureForm(
+ PDO $dbh,
+ Config_Container $c
+ ) {
+ $this->configureElements($dbh, $c);
+ $this->configureFilters();
+ $this->configureRules();
+ $this->configureDefaults($dbh);
+ $this->configureConstants();
+ }
+
+ /**
+ * Setup the Form's rules
+ *
+ * @return void
+ */
+ public function configureRules()
+ {
+ $r = array();
+
+ $r[] = array(
+ 'element' => 'video_url',
+ 'message' => 'ERROR: Invalid URL format (http)',
+ 'type' => 'checkURI',
+ 'format' => array(
+ 'allowed_schemes' => array('http'),
+ 'strict' => false
+ ),
+ 'validation' => $this->validationType,
+ 'reset' => false,
+ 'force' => false
+ );
+
+
+ $this->setupRules($r);
+ }
+
+ /**
+ * _processData function creates an video object Toolkit_Videos_Video
+ * if id exists it creates the object by id
+ * else it creates a new object
+ * saved is called and the object is either created or updated
+ *
+ * If the $values['id'] is given it creates a Toolkit_Videos_VideoMapper
+ * object and get the video object using the getVideoById method
+ * If not it then just creates an empty video object
+ * The object is then updated using it's accessor method and saved
+ *
+ * @param type $dbh Database Connection
+ * @param type $values Form $values
+ *
+ * @return void
+ */
+ private function _processData($dbh, $values)
+ {
+ $videoMapper = new Toolkit_Videos_VideoMapper($dbh);
+ if ($_GET['id']) {
+ $video = $videoMapper->getVideoById($_GET['id'], false);
+ } else {
+ $video = new Toolkit_Videos_Video();
+ }
+ $video->setVideo_url($values['video_url'])
+ ->setFeatured($values['featured'])
+ ->setActive($values['active']);
+
+ $video->save($dbh);
+ }
+
+ /**
+ * Output HTML for the form
+ *
+ * @param PDO $dbh Database Connection
+ *
+ * @return string|boolean
+ */
+ public function toHtml(PDO $dbh)
+ {
+ // Handle Deleting banner.
+ if ( $this->isSubmitted()
+ && ctype_digit($_GET['id'])
+ ) {
+ if ($this->getSubmitValue('delete_rmv')) {
+ $videoMapper = new Toolkit_Videos_VideoMapper($dbh);
+ $video = $videoMapper->getVideoById($_GET['id'], false);
+ if ($video instanceof Toolkit_Videos_Video) {
+ if ($video->delete($dbh, $is)) {
+ return 'Video successfully deleted.';
+ }
+ } else {
+ // the coupon has already been deleted or doesn't exist.
+ return "The video has already been deleted or doesn't exists.";
+ }
+ header ('Location: videos.php');
+ return false;
+ }
+ }
+
+ $this->setupRenderers();
+ if ($this->validate()) {
+ $this->cleanForm();
+
+ $submitValues = $this->getSubmitValues();
+ if ($this->_processData($dbh, $submitValues)) {
+ $this->freeze();
+ $output = $this->successMsg;
+ }
+ header('Location: videos.php');
+ } elseif ($this->isSubmitted()) {
+ $output = $this->errorMsg;
+ $output .= parent::toHTML();
+ } else {
+ $output = parent::toHTML();
+ }
+ return $output;
+ }
+
+}
diff --git a/Toolkit/Videos/Controller.php b/Toolkit/Videos/Controller.php
new file mode 100644
index 0000000..d33be54
--- /dev/null
+++ b/Toolkit/Videos/Controller.php
@@ -0,0 +1,58 @@
+flexyOptions;
+ }
+
+ public function setFlexyOptions($flexyOptions)
+ {
+ $this->flexyOptions = $flexyOptions;
+ }
+
+ function __construct()
+ {
+ $options = $GLOBALS['flexyOptions'];
+ $options['templateDir']
+ = dirname(__FILE__) . '/templates';
+ $options['compileDir']
+ = dirname(__FILE__) . '/templates/compiled';
+ $this->flexyOptions = $options;
+ }
+
+ public function toHtml(PDO $dbh, Config_Container $appConf)
+ {
+ switch ($_GET['module']) {
+ case 'editVideo':
+ $form = new Toolkit_Videos_AdminEditVideoForm(
+ 'edit-video'
+ );
+ $form->configureForm($dbh, $appConf);
+ $ret = $form->toHtml($dbh);
+ break;
+ case 'listVideo':
+ default:
+ $videos = new Toolkit_Videos_VideosDataGrid($dbh);
+ $videos->setConfig($appConf);
+ $videos->setQuery();
+ $videos->setDefaultSort(array('pos' => 'ASC'));
+ $ret .= $videos->toHtml($appConf);
+ break;
+ }
+ return $ret;
+ }
+}
+?>
diff --git a/Toolkit/Videos/Database/application.sql b/Toolkit/Videos/Database/application.sql
new file mode 100644
index 0000000..178e2fd
--- /dev/null
+++ b/Toolkit/Videos/Database/application.sql
@@ -0,0 +1,12 @@
+--
+-- setup schema
+--
+
+CREATE SCHEMA videos;
+GRANT ALL ON SCHEMA videos TO nobody;
+
+--
+-- Tables
+--
+
+\i ./table/videos.sql
diff --git a/Toolkit/Videos/Database/removeApplication.sql b/Toolkit/Videos/Database/removeApplication.sql
new file mode 100644
index 0000000..6c60d9c
--- /dev/null
+++ b/Toolkit/Videos/Database/removeApplication.sql
@@ -0,0 +1,6 @@
+--
+-- Drops schema
+-- WARNING: CANNOT BE UNDONE
+--
+
+DROP SCHEMA IF EXISTS videos CASCADE;
\ No newline at end of file
diff --git a/Toolkit/Videos/Database/table/videos.sql b/Toolkit/Videos/Database/table/videos.sql
new file mode 100644
index 0000000..0411150
--- /dev/null
+++ b/Toolkit/Videos/Database/table/videos.sql
@@ -0,0 +1,12 @@
+CREATE TABLE videos.videos (
+ id SERIAL,
+ create_date DATE DEFAULT current_date,
+ video_url TEXT,
+ active BOOLEAN,
+ featured BOOLEAN,
+ pos INT DEFAULT 1,
+ PRIMARY KEY (id)
+);
+
+GRANT ALL ON videos.videos TO nobody;
+GRANT ALL ON videos.videos_id_seq TO nobody;
\ No newline at end of file
diff --git a/Toolkit/Videos/IDecorator.php b/Toolkit/Videos/IDecorator.php
new file mode 100644
index 0000000..1095b2d
--- /dev/null
+++ b/Toolkit/Videos/IDecorator.php
@@ -0,0 +1,56 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Videos_IDecorator
+ *
+ * Inteface class for the Toolkit_Videos_Decorators
+ * In future there may be more decorators here we're insurring that they have
+ * simular API's
+ *
+ * @category Toolkit
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2008 Gaslight media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+interface Toolkit_Videos_IDecorator
+{
+ /**
+ * Class Constructor
+ *
+ * @return void
+ */
+ public function __construct();
+
+ /**
+ * Handles setting up the PEAR::HTML_Template_Flexy options
+ *
+ * @return void
+ */
+ public function setFlexyOptions();
+ /**
+ * Handles creating HTML output
+ *
+ * @param PDO $dbh Database Connection
+ * @param object $gateway Gateway Object
+ *
+ * @return string
+ */
+ public function toHtml(
+ PDO $dbh,
+ $gateway = null
+ );
+}
diff --git a/Toolkit/Videos/Navigation.php b/Toolkit/Videos/Navigation.php
new file mode 100644
index 0000000..0428d7a
--- /dev/null
+++ b/Toolkit/Videos/Navigation.php
@@ -0,0 +1,123 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Videos_Navigation
+ *
+ * Handles the navigation for the Video admin side
+ *
+ * @category Toolkit
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2008 Gaslight media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_Videos_Navigation
+ extends Toolkit_NavigationAbstract
+ implements Toolkit_INavigation
+{
+ // {{{ __construct()
+
+ /**
+ * Class Constructor
+ *
+ * @param HTML_Menu $menu Menu to use
+ * @param HTML_Menu_Renderer $rEngine Render to use
+ *
+ * @return void
+ */
+ public function __construct(
+ HTML_Menu $menu,
+ HTML_Menu_Renderer $rEngine
+ ) {
+ $this->menu = $menu;
+ $this->rEngine = $rEngine;
+ $this->currIndex = 'listCoupons';
+ }
+
+ /**
+ * Create templates for the navigation
+ *
+ * @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('');
+ }
+
+ /**
+ * force the current index to $_GET['page']
+ *
+ * @return void
+ */
+ protected function setCurrentIndex()
+ {
+ $this->menu->forceCurrentIndex($_GET['page']);
+ }
+
+ // }}}
+ // {{{ 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
+ $singularType = $c->getItem('section', 'listing type')
+ ->getItem('directive', 'singular')
+ ->getContent();
+ $pluralType = $c->getItem('section', 'listing type')
+ ->getItem('directive', 'plural')
+ ->getContent();
+
+ $nav = array(
+ 'listVideos' => array(
+ 'Title' => "List {$pluralType}",
+ 'url' => MEDIA_BASE_URL . 'admin/videos.php?page=listVideos&module=listVideos',
+ 'desc' => "Display all the {$pluralType}",
+ ),
+ 'editVideo' => array(
+ 'Title' => "Add {$singularType}",
+ 'url' => MEDIA_BASE_URL . 'admin/videos.php?page=editVideo&module=editVideo',
+ 'desc' => "Edit a {$singularType}"
+ ),
+ );
+
+ return $nav;
+ }
+
+ // @codeCoverageIgnoreEnd
+}
diff --git a/Toolkit/Videos/Video.php b/Toolkit/Videos/Video.php
new file mode 100644
index 0000000..8e5f6e3
--- /dev/null
+++ b/Toolkit/Videos/Video.php
@@ -0,0 +1,346 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Videos_Video
+ *
+ * Object Data pattern class for the Video PDO Table
+ *
+ * @category Toolkit
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2008 Gaslight media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_Videos_Video
+{
+
+ protected $id;
+ protected $video_url;
+ protected $pos;
+ protected $featured;
+ protected $active;
+
+ /**
+ * Handles the work of Inserting a video record into the database
+ * returns the id for the new record
+ *
+ * @param PDO $dbh Database Connection
+ *
+ * @return int
+ */
+ private function _insert(PDO $dbh)
+ {
+ $classData = $this->getClassAsArray();
+ unset($classData['id']);
+ $pos = $this->getMaxPos();
+ $classData['pos'] = ++$pos;
+ $sql = Toolkit_Common::createSQLInsert(
+ 'videos',
+ array_keys($classData)
+ );
+ $sql .= " RETURNING id";
+ $stmt = Toolkit_Common::prepareQuery(
+ $dbh,
+ 'videos',
+ $sql,
+ $classData
+ );
+ $stmt->execute();
+ return $stmt->fetchColumn();
+ }
+
+ /**
+ * Handles the update of the record on the database record
+ *
+ * @param PDO $dbh Database Connection
+ *
+ * @return int
+ */
+ private function _update(PDO $dbh)
+ {
+ $classData = $this->getClassAsArray();
+ $sql = Toolkit_Common::createSQLUpdate(
+ 'videos',
+ array_keys($classData),
+ array('id = :id')
+ );
+ return Toolkit_Common::processQuery(
+ $dbh,
+ 'videos',
+ $sql,
+ $classData
+ );
+ }
+
+ /**
+ * Handles the deletion of the record in the database and reordering
+ * any other videos in the table
+ *
+ * @param PDO $dbh Database Connection
+ *
+ * @return void
+ */
+ public function delete(PDO $dbh)
+ {
+ try {
+ $dbh->beginTransaction();
+ $sql = "
+ DELETE
+ FROM videos
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ':id',
+ $this->getId(),
+ PDO::PARAM_INT
+ );
+ $stmt->execute();
+ // we have to reorder the positions for the rest of the videos
+ $sql = "
+ UPDATE videos
+ SET pos = pos - 1
+ WHERE pos >= :oldpos";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(':oldpos', $this->getPos(), PDO::PARAM_INT);
+ $stmt->execute();
+ $dbh->commit();
+ } catch(PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+ }
+
+ /**
+ * active getter
+ *
+ * @return boolean
+ */
+ public function getActive()
+ {
+ return $this->active;
+ }
+
+ /**
+ * active setter the given values is cast to a boolean value
+ * so if you send in a string 'true' or 'false' both will be cast to true
+ *
+ * @param boolean $active Active flag
+ *
+ * @return Toolkit_Videos_Video
+ */
+ public function setActive($active)
+ {
+ $this->active = (bool)$active;
+ return $this;
+ }
+
+ /**
+ * id getter
+ *
+ * @return int
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ /**
+ * id setter
+ *
+ * @param int $id integer for the record id
+ *
+ * @return Toolkit_Videos_Video
+ */
+ public function setId($id)
+ {
+ if (!$this->id) {
+ $this->id = $id;
+ }
+ return $this;
+ }
+
+ /**
+ * video_url getter
+ *
+ * @return string
+ */
+ public function getVideo_url()
+ {
+ return $this->video_url;
+ }
+
+ /**
+ * video_url settur
+ *
+ * @param string $video_url the youtube video url
+ *
+ * @return Toolkit_Videos_Video
+ */
+ public function setVideo_url($video_url)
+ {
+ $this->video_url = $video_url;
+ return $this;
+ }
+
+ /**
+ * pos getter
+ *
+ * @return int
+ */
+ public function getPos()
+ {
+ return $this->pos;
+ }
+
+ /**
+ * pos setter
+ *
+ * @param type $pos Position number for the video
+ *
+ * @return Toolkit_Videos_Video
+ */
+ public function setPos($pos)
+ {
+ $this->pos = $pos;
+ return $this;
+ }
+
+ /**
+ * featured getter
+ *
+ * @return boolean
+ */
+ public function getFeatured()
+ {
+ return $this->featured;
+ }
+
+ /**
+ * featured setter needs to be boolean not a string
+ *
+ * @param boolean $featured Featured flag
+ *
+ * @return Toolkit_Videos_Video
+ */
+ public function setFeatured($featured)
+ {
+ $this->featured = (bool)$featured;
+ return $this;
+ }
+
+ /**
+ * Handles the saving of the object to the database
+ *
+ * If the object has an id field set then update the record or else
+ * create a new one
+ *
+ * @param PDO $dbh Database Connection
+ *
+ * @return void
+ */
+ public function save(PDO $dbh)
+ {
+ if ($this->getId()) {
+ $this->_update($dbh);
+ } else {
+ $this->_insert($dbh);
+ }
+ }
+
+ /**
+ * Create an array of the class fields
+ *
+ * @return array
+ */
+ public function getClassAsArray()
+ {
+ $data = array();
+ $classData = get_class_vars(get_class($this));
+ foreach ($classData as $fieldName => $element) {
+ $getFunc = 'get' . ucfirst($fieldName);
+ $data[$fieldName] = $this->$getFunc();
+ }
+ return $data;
+ }
+
+ /**
+ * Get the max position for the videos
+ *
+ * @staticvar int $maxPos position of the video
+ * @return int
+ */
+ public function getMaxPos()
+ {
+ static $maxPos;
+ if (!$maxPos) {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT count(id) as maxpos
+ FROM videos";
+ $ret = $dbh->query($sql);
+ $maxPos = $ret->fetchColumn();
+ }
+ return (int)$maxPos;
+ }
+
+ /**
+ * Create the youtube url
+ *
+ * Using preg_match on two pattern to return the video url portion
+ * first is /v=(.*)$/ older style
+ * second is /youtu.be\/(.*)/
+ * These may need to be updated if youtube creates newer embed codes
+ *
+ * @return boolean
+ */
+ public function getVideoCode()
+ {
+ $pattern = '/v=(.*)$/';
+ $pattern2 = '/youtu.be\/(.*)/';
+ $vidUrl = $this->getVideo_url();
+ if (preg_match($pattern, $vidUrl, $match)) {
+ return $match[1];
+ } else if (preg_match($pattern2, $vidUrl, $match)) {
+ return $match[1];
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Using the youtube API get the video title for the embed url
+ *
+ * @return string
+ */
+ public function getVideoTitle()
+ {
+ $url = "http://gdata.youtube.com/feeds/api/videos/". $this->getVideoCode();
+ $ch = curl_init();
+ $curlOptions = array(
+ CURLOPT_URL => $url,
+ CURLOPT_HEADER => 0,
+ CURLOPT_RETURNTRANSFER => 1
+ );
+ curl_setopt_array($ch, $curlOptions);
+
+ $response = curl_exec($ch);
+ curl_close($ch);
+ $doc = new DOMDocument;
+ $doc->loadXML($response);
+ $title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
+ return $title;
+ }
+
+}
diff --git a/Toolkit/Videos/VideoMapper.php b/Toolkit/Videos/VideoMapper.php
new file mode 100644
index 0000000..2a00c87
--- /dev/null
+++ b/Toolkit/Videos/VideoMapper.php
@@ -0,0 +1,111 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Videos_Video
+ *
+ * Object Mapper pattern class for the Video PDO Table. Creates
+ * Toolkit_Video_Video objects by values or by id
+ *
+ * @category Toolkit
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2008 Gaslight media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_Videos_VideoMapper
+{
+
+ /**
+ * Class Constructor
+ *
+ * @param PDO $pdo Database Connection
+ */
+ function __construct(PDO $pdo)
+ {
+ $this->dbh = $pdo;
+ }
+
+ /**
+ * Creates Video object by a given array of values
+ * values must be set with the Videos fields as keys
+ *
+ * @param array $values array of values
+ *
+ * @return Toolkit_Videos_Video
+ */
+ public function createByValues($values)
+ {
+ $video = new Toolkit_Videos_Video();
+ $video->setId($values['id'])
+ ->setVideo_url($values['video_url'])
+ ->setActive($values['active'])
+ ->setfeatured($values['featured'])
+ ->setPos($this->getMaxPos());
+ return $video;
+ }
+
+ public function getMaxPos()
+ {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT count(id) as maxpos
+ FROM videos";
+ $ret = $dbh->query($sql);
+ $maxPos = $ret->fetchColumn();
+ if ((int) $maxPos == 0) {
+ $maxPos = 1;
+ }
+ return $maxPos;
+ }
+ /**
+ * Create Video object by a given id
+ * if the id is not found then it does not return
+ *
+ * @param int $id id for the video record
+ * @param array $returnArray Can return the array instead of object
+ *
+ * @return mixed
+ */
+ public function getVideoById($id, $returnArray = true)
+ {
+ try {
+ $sql = "
+ SELECT *
+ FROM videos
+ WHERE id = :id";
+ $stmt = $this->dbh->prepare($sql);
+ $stmt->bindParam(
+ ':id', $id, PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $res = $stmt->fetch(PDO::FETCH_ASSOC);
+ if ($res) {
+ $video = new Toolkit_Videos_Video();
+ $video->setId($res['id'])
+ ->setVideo_url($res['video_url'])
+ ->setActive($res['active'])
+ ->setfeatured($res['featured'])
+ ->setPos($res['pos']);
+ return ($returnArray)
+ ? $video->getClassAsArray()
+ : $video;
+ }
+ } catch(PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+ }
+
+}
diff --git a/Toolkit/Videos/VideosDataGrid.php b/Toolkit/Videos/VideosDataGrid.php
new file mode 100644
index 0000000..f2403e8
--- /dev/null
+++ b/Toolkit/Videos/VideosDataGrid.php
@@ -0,0 +1,300 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Videos_VideosDataGrid
+ *
+ * Handles the listing of the videos using the PEAR::Structures_DataGrid
+ * extended from our class Toolkit_DataGridBuilder
+ *
+ * @category Toolkit
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2008 Gaslight media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_Videos_VideosDataGrid
+ extends Toolkit_DataGridBuilder
+{
+
+ /**
+ * Description for protected
+ * @var string
+ * @access protected
+ */
+ protected $noRecMessage = 'No Videos Found.';
+
+ protected $config;
+
+ /**
+ * Set the config
+ *
+ * @param Config_Container $config
+ */
+ public function setConfig(Config_Container $config)
+ {
+ $this->config = $config;
+ }
+
+ /**
+ * Configure the columns for the datagrid
+ *
+ * @param Config_Container $c PEAR::Config_Container object
+ *
+ * @return void
+ * @access protected
+ */
+ protected function configureColumns()
+ {
+ // get reference to [conf] section of config file
+ $appHasFeaturedVideos
+ = $this->config->getItem('section', 'conf')
+ ->getItem('directive', 'featuredVideos')
+ ->getContent();
+
+ $this->addColumn(
+ new Structures_DataGrid_Column(
+ 'Function',
+ null,
+ null,
+ array('class' => 'editLink'),
+ null,
+ array(&$this, 'renderEditLink')
+ )
+ );
+
+ $this->addColumn(
+ new Structures_DataGrid_Column(
+ 'Active',
+ null,
+ null,
+ null,
+ null,
+ array($this, 'renderActive')
+ )
+ );
+
+ if ($appHasFeaturedVideos) {
+ $this->addColumn(
+ new Structures_DataGrid_Column(
+ 'Featured',
+ null,
+ null,
+ null,
+ null,
+ array($this, 'renderFeatured')
+ )
+ );
+ }
+
+ $this->addColumn(
+ new Structures_DataGrid_Column(
+ 'Position',
+ null,
+ null,
+ null,
+ null,
+ array($this, 'renderPos')
+ )
+ );
+
+ $this->addColumn(
+ new Structures_DataGrid_Column(
+ 'Video Url',
+ 'video_url',
+ null
+ )
+ );
+
+ $this->addColumn(
+ new Structures_DataGrid_Column(
+ 'Thumbnail',
+ null,
+ null,
+ null,
+ null,
+ array($this, 'renderThumbNail')
+ )
+ );
+ }
+
+ /**
+ * Get the max position for the videos for generating a drop down for
+ * reordering them in the datagrid
+ *
+ * @staticvar type $maxPos
+ * @return int
+ */
+ public function getMaxPos()
+ {
+ static $maxPos;
+ if (!$maxPos) {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT count(id) as maxpos
+ FROM videos";
+ $ret = $dbh->query($sql);
+ $row = $ret->fetch(PDO::FETCH_ASSOC);
+ if ((int)$row['maxpos'] == 0) {
+ $maxPos = 1;
+ } else {
+ $maxPos = $row['maxpos'];
+ }
+ }
+ return (int)$maxPos;
+ }
+
+ /**
+ * Render the edit link for a category
+ *
+ * @param array $data DB record
+ *
+ * @return mixed Link to edit a category
+ * @access public
+ */
+ public function renderEditLink($data)
+ {
+ extract($data['record']);
+ $link = 'Edit ';
+ return sprintf($link, MEDIA_BASE_URL, $id);
+ }
+
+ /**
+ * Handles rendering the pos column
+ *
+ * @param type $data Data array
+ *
+ * @return string
+ */
+ public function renderPos($data)
+ {
+ extract($data['record']);
+ $html = '';
+ $maxPos = $this->getMaxPos();
+ for ($i = 1; $i <= $maxPos; ++$i) {
+ $html .= '';
+ }
+ $html .= ' ';
+ return $html;
+ }
+
+ /**
+ * Handles rendering the thumbnail column
+ *
+ * @param type $data Data array
+ *
+ * @return string
+ */
+ public function renderThumbNail($data)
+ {
+ extract($data['record']);
+ $pattern = '/v=(.*)/';
+ $pattern2 = '/youtu.be\/(.*)/';
+ if (preg_match($pattern, $video_url, $match)) {
+ $vidCode = $match[1];
+ } else if (preg_match($pattern2, $video_url, $match)) {
+ $vidCode = $match[1];
+ }
+ $thumb = ($vidCode)
+ ? ' '
+ : '';
+ return $thumb;
+ }
+
+ /**
+ * Handles rendering the active column
+ *
+ * @param type $data Data array
+ *
+ * @return string
+ */
+ public function renderActive($data)
+ {
+ $active = $data['record']['active'];
+ $link = MEDIA_BASE_URL . 'video-active-toggle/'.$data['record']['id'].'/';
+ $ball
+ = ($active)
+ ? 'grnball.gif'
+ : 'redball.gif';
+ $html = sprintf(
+ ' ',
+ $link,
+ MEDIA_BASE_URL,
+ $ball
+ );
+ return $html;
+ }
+
+ /**
+ * Handles rendering the featured column
+ *
+ * @param type $data Data array
+ *
+ * @return type
+ */
+ public function renderFeatured($data)
+ {
+ $featured = $data['record']['featured'];
+ $link = MEDIA_BASE_URL . 'video-featured-toggle/'.$data['record']['id'].'/';
+ $ball
+ = ($featured)
+ ? 'grnball.gif'
+ : 'redball.gif';
+ $html = sprintf(
+ ' ',
+ $link,
+ MEDIA_BASE_URL,
+ $ball
+ );
+ return $html;
+ }
+
+ /**
+ * Handles setting the query for the datagrid
+ *
+ * @return void
+ */
+ public function setQuery()
+ {
+ $sql = "
+ SELECT *
+ FROM videos";
+
+ parent::setQuery($sql);
+ }
+
+ /**
+ * Handles creation of the HTML for the datagrid
+ *
+ * @return string
+ */
+ public function toHtml()
+ {
+ $GLOBALS['styleSheets'][]
+ = MEDIA_BASE_URL . 'Toolkit/Videos/styles.css';
+ $GLOBALS['styleSheets'][]
+ = MEDIA_APP_BASE_URL . 'gallery/colorbox/colorbox.css';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/plugins/colorbox/1.3.15/jquery.colorbox-min.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_BASE_URL . 'Toolkit/Videos/libjs/videos.js';
+ return parent::toHTML();
+ }
+
+}
diff --git a/Toolkit/Videos/WebDecorator.php b/Toolkit/Videos/WebDecorator.php
new file mode 100644
index 0000000..50c2092
--- /dev/null
+++ b/Toolkit/Videos/WebDecorator.php
@@ -0,0 +1,102 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+
+/**
+ * Toolkit_Videos_WebDecorator
+ *
+ * Handles the listing of the videos using the PEAR::Structures_DataGrid
+ * extended from our class Toolkit_DataGridBuilder
+ *
+ * @category Toolkit
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2008 Gaslight media
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_Videos_WebDecorator
+ implements Toolkit_Videos_IDecorator
+{
+
+ private $_flexyOptions = array();
+ private $_template = 'webDecorator.html';
+
+ /**
+ * Class Constructor
+ *
+ * @return void
+ */
+ public function __construct()
+ {
+ $this->setFlexyOptions();
+ }
+
+ /**
+ * Handles setting the flexyOptions
+ *
+ * @return void
+ */
+ public function setFlexyOptions()
+ {
+ $this->_flexyOptions = $GLOBALS['flexyOptions'];
+ $this->_flexyOptions['templateDir']
+ = BASE . 'Toolkit/Videos/templates';
+ $this->_flexyOptions['compileDir']
+ = BASE . 'Toolkit/Videos/templates/compiled';
+ }
+
+ /**
+ * Handles HTML output
+ *
+ * @param PDO $dbh Database Connection
+ * @param type $gateway Gateway object
+ *
+ * @return boolean
+ */
+ public function toHtml(
+ PDO $dbh,
+ $gateway = null
+ ) {
+ try {
+ $sql = "
+ SELECT id
+ FROM videos
+ WHERE featured = true
+ ORDER BY pos
+ LIMIT 1
+ OFFSET 0";
+ $row = $dbh->query($sql)->fetch(PDO::FETCH_ASSOC);
+ if ($row) {
+ $tpl = new HTML_Template_Flexy($this->_flexyOptions);
+ $page = new stdClass;
+ $page->videoUrl = Toolkit_Template_Page::getSeoUrl($gateway, 189);
+ $videoMapper
+ = new Toolkit_Videos_VideoMapper($dbh);
+ $video = $videoMapper->getVideoById($row['id'], false);
+ if ($video) {
+ $page->vCode = $video->getVideoCode();
+ $page->title = $video->getVideoTitle();
+ }
+
+ $tpl->compile($this->_template);
+ return $tpl->bufferedOutputObject($page);
+ } else {
+ return false;
+ }
+ } catch(PDOException $e) {
+ Toolkit_Common::handle_error($e);
+ }
+ }
+
+}
diff --git a/Toolkit/Videos/WebPageDecorator.php b/Toolkit/Videos/WebPageDecorator.php
new file mode 100644
index 0000000..689f220
--- /dev/null
+++ b/Toolkit/Videos/WebPageDecorator.php
@@ -0,0 +1,100 @@
+
+ * @copyright 2009 Gaslight Media
+ * @license Gaslight Media
+ * @version CVS: $Id: Display.php,v 1.10 2010/07/04 23:55:12 jamie Exp $
+ * @link <>
+ */
+
+/**
+ * WebPageDecorator
+ *
+ * Description of class
+ *
+ * @category Category
+ * @package Videos
+ * @author Steve Sutton
+ * @copyright 2009 Gaslight Media
+ * @license Gaslight Media
+ * @link <>
+ */
+class Toolkit_Videos_WebPageDecorator implements Toolkit_Videos_IDecorator
+{
+ private $_flexyOptions = array();
+ private $_template = 'webPageDecorator.html';
+ private $_perRow = 5;
+
+ public function __construct()
+ {
+ $this->setFlexyOptions();
+ }
+
+ public function setFlexyOptions()
+ {
+ $this->_flexyOptions = $GLOBALS['flexyOptions'];
+ $this->_flexyOptions['templateDir']
+ = BASE . 'Toolkit/Videos/templates';
+ $this->_flexyOptions['compileDir']
+ = BASE . 'Toolkit/Videos/templates/compiled';
+ }
+
+ public function toHtml(
+ PDO $dbh,
+ $gateway = null
+ ) {
+ $GLOBALS['styleSheets'][]
+ = MEDIA_APP_BASE_URL . 'gallery/colorbox/colorbox.css';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_APP_BASE_URL . 'libjs/plugins/colorbox/1.3.15/jquery.colorbox-min.js';
+ $GLOBALS['bottomScripts'][]
+ = MEDIA_BASE_URL . 'Toolkit/Videos/libjs/videos.js';
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT id
+ FROM videos
+ WHERE active = true
+ ORDER BY pos";
+ $stmt = $dbh->query($sql);
+ $page = new stdClass;
+ $page->videos = array();
+ while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ $videoMapper
+ = new Toolkit_Videos_VideoMapper($dbh);
+ $video = $videoMapper->getVideoById($row['id'], false);
+ if ($video) {
+ $page->videos[] = array(
+ 'title' => $video->getVideoTitle(),
+ 'code' => $video->getVideoCode()
+ );
+ }
+ }
+ $count = 1;
+ $trueCount = 1;
+ $num = count($page->videos);
+ foreach ($page->videos as &$row) {
+ $row['firstInRow'] = ($count == 1);
+ if ($count == $this->_perRow || $trueCount == $num) {
+ $row['lastInRow'] = true;
+ $count = 0;
+ } else {
+ $row['lastInRow'] = false;
+ }
+ ++$count;
+ ++$trueCount;
+ }
+ $tpl = new HTML_Template_Flexy($this->_flexyOptions);
+ $tpl->compile($this->_template);
+ return $out . $tpl->bufferedOutputObject($page);
+ }
+}
diff --git a/Toolkit/Videos/config.ini b/Toolkit/Videos/config.ini
new file mode 100644
index 0000000..ced83b7
--- /dev/null
+++ b/Toolkit/Videos/config.ini
@@ -0,0 +1,7 @@
+[conf]
+applicationName = "Videos"
+featuredVideos = Off
+
+[listing type]
+singular = "Video"
+plural = "Videos"
diff --git a/Toolkit/Videos/libjs/videos.js b/Toolkit/Videos/libjs/videos.js
new file mode 100644
index 0000000..6080caf
--- /dev/null
+++ b/Toolkit/Videos/libjs/videos.js
@@ -0,0 +1,14 @@
+var GLMColorBox = {
+ init: function() {
+ $('a.colorbox').colorbox({iframe: true, innerWidth:425, innerHeight:344});
+ $('select.posSelect').each(function () {
+ $(this).change(function(){
+ var id = $(this).attr('rel');
+ var newpos = $(this).attr('value');
+ window.location.href = '../video-move/' + id + '/' + newpos + '/';
+ });
+ });
+ }
+};
+
+$(document).ready(GLMColorBox.init);
diff --git a/Toolkit/Videos/moveVideo.php b/Toolkit/Videos/moveVideo.php
new file mode 100644
index 0000000..74e4f49
--- /dev/null
+++ b/Toolkit/Videos/moveVideo.php
@@ -0,0 +1,81 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+if (!isset($_GET['kpass'])) {
+ die();
+}
+require_once '../../setup.phtml';
+
+$dbh = Toolkit_Database::getInstance();
+$newpos = $_REQUEST['newpos'];
+$id = $_REQUEST['id'];
+$error = false;
+try {
+ $dbh->beginTransaction();
+ $sql = "
+ SELECT pos
+ FROM videos
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ":id", $_REQUEST['id'], PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $oldpos = $stmt->fetchColumn();
+ if ($oldpos < $newpos) {
+ $sql = "
+ UPDATE videos
+ SET pos = pos - 1
+ WHERE pos BETWEEN :oldpos AND :newpos";
+ $updateStmt = $dbh->prepare($sql);
+ } else if ($oldpos > $newpos) {
+ $sql = "
+ UPDATE videos
+ SET pos = pos + 1
+ WHERE pos BETWEEN :newpos AND :oldpos";
+ $updateStmt = $dbh->prepare($sql);
+ } else {
+ $error = true;
+ }
+
+ if (!$error) {
+ $updateStmt->bindParam(
+ ':newpos', $newpos, PDO::PARAM_INT
+ );
+ $updateStmt->bindParam(
+ ':oldpos', $oldpos, PDO::PARAM_INT
+ );
+ $updateStmt->execute();
+ // now change the real video to its position
+ $sql = "
+ UPDATE videos
+ SET pos = :pos
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ':pos', $newpos, PDO::PARAM_INT
+ );
+ $stmt->bindParam(
+ ':id', $id, PDO::PARAM_INT
+ );
+ $stmt->execute();
+ }
+ $dbh->commit();
+} catch (PDOException $e) {
+ $dbh->rollback();
+ Toolkit_Logger::logException('DB Error', $e);
+}
+
+header('Location: '.MEDIA_BASE_URL.'admin/videos.php');
diff --git a/Toolkit/Videos/styles.css b/Toolkit/Videos/styles.css
new file mode 100644
index 0000000..cc82e07
--- /dev/null
+++ b/Toolkit/Videos/styles.css
@@ -0,0 +1,154 @@
+#form-warning-top {
+ color: #FF0000;
+ font-size: 14px;
+ font-weight: bold;
+ margin-bottom: 0.5em;
+ margin-top: 1em;
+}
+.required, .req {
+ color: #FF0000;
+}
+.group {
+ display: -moz-inline-box;
+ width: 100%;
+}
+.group td {
+ width: 324px;
+}
+.requiredNote {
+ text-align: center;
+}
+#contact {
+ margin: 10px;
+}
+#contact table {
+ background-color: #FFFFFF;
+ border: 1px solid #EEEEEE;
+ border-collapse: collapse;
+}
+#contact td {
+ border: 1px solid #EEEEEE;
+ border-collapse: collapse;
+ color: #000000;
+ font-family: arial, helvetica, sans-serif;
+ padding: 3px;
+ font-size: 12px;
+}
+.labelcell {
+ background-color: transparent;
+ padding-right: 10px;
+ padding-top: 3px;
+ text-align: right;
+ white-space: nowrap;
+ width: 140px;
+}
+.fieldcell {
+ padding-left: 4px;
+ width: 320px;
+}
+.fieldcell .text {
+ width: 90%;
+}
+#contact table.group {
+ font-size: 10px;
+ border: none;
+ padding-top: 4px;
+}
+#contact table.group td {
+ border: none;
+}
+#contact .hdr {
+ background-color: #999999;
+ border: 1px solid #666666;
+ font-weight: bold;
+}
+.paging {
+ text-align: center;
+ background-color: #F6F6F6;
+ border-color: #E86a10;
+ border-color: #296DC0;
+ border-style: solid;
+ border-width: 1px 0;
+ margin: 1.0em 0;
+ padding: 8px 0;
+ text-align: center;
+ width: 100%;
+ font-size: 12px;
+
+}
+.paging b {
+ border: 1px solid #b22c2c;
+ border: 1px solid #E86A10;
+ background: #FFF;
+ padding: 5px 7px;
+ margin: 0 5px;
+}
+.paging a {
+ background: #FFF;
+ border: 1px solid #CCC;
+ padding: 5px 7px;
+ text-decoration: none;
+ font-family: helvetica, times;
+ color: #000;
+ margin: 0 5px;
+}
+.paging a:hover {
+ border: 1px solid #999;
+ border: 1px solid #b22c2c;
+ border: 1px solid #E86A10;
+}
+#dataGrid {
+ margin: 10px auto;
+ border: 1px solid #296DC0;
+ width: 100%;
+ border-collapse: collapse;
+}
+#dataGrid thead th {
+ background: #296DC0;
+ border: 1px solid #1b4880;
+ color: #000;
+ font-weight: normal;
+}
+#dataGrid th a {
+ font-weight: bolder;
+ color: #000;
+ text-decoration: none;
+}
+#dataGrid th a:hover {
+ color: #E86A10;
+ text-decoration: underline;
+}
+#dataGrid tr {
+ border: 1px solid #296DC0;
+ border-collapse: collapse;
+}
+#dataGrid tbody tr td {
+ padding: 5px;
+}
+#dataGrid .editLink, #dataGrid .delLink,
+#dataGrid .mailLink, #dataGrid .dateLink,
+#dataGrid .posLink {
+ text-align: center;
+}
+img.status {
+ border: none;
+}
+.even {
+ background-color: #D9D9D9;
+}
+#gridSorter {
+ margin: 0 auto;
+ padding: 10px;
+ text-align: center;
+ border: 1px solid #296DC0;
+}
+#gridSorter table {
+ border: none;
+}
+#gridSorter td {
+ border: none;
+}
+.fieldcell textarea {
+ width: 90%;
+ height: 70px;
+}
diff --git a/Toolkit/Videos/templates/webDecorator.html b/Toolkit/Videos/templates/webDecorator.html
new file mode 100644
index 0000000..d7114d0
--- /dev/null
+++ b/Toolkit/Videos/templates/webDecorator.html
@@ -0,0 +1,11 @@
+
diff --git a/Toolkit/Videos/templates/webPageDecorator.html b/Toolkit/Videos/templates/webPageDecorator.html
new file mode 100644
index 0000000..71622ca
--- /dev/null
+++ b/Toolkit/Videos/templates/webPageDecorator.html
@@ -0,0 +1,14 @@
+
+ {foreach:videos,v}
+ {if:v[firstInRow]}
{end:}
+
+
+
+
+
+ {v[title]:h}
+
+
+ {if:v[lastInRow]}
{end:}
+ {end:}
+
diff --git a/Toolkit/Videos/toggleActive.php b/Toolkit/Videos/toggleActive.php
new file mode 100644
index 0000000..1b2eec6
--- /dev/null
+++ b/Toolkit/Videos/toggleActive.php
@@ -0,0 +1,65 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+if (!isset($_GET['kpass'])) {
+ die();
+}
+require_once '../../setup.phtml';
+
+$dbh = Toolkit_Database::getInstance();
+$id = $_REQUEST['id'];
+
+try {
+ $dbh->beginTransaction();
+ $sql = "
+ SELECT active
+ FROM videos
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ":id",
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $activeState = $stmt->fetchColumn();
+
+ if ($activeState) {
+ $sql = "
+ UPDATE videos
+ SET active = false
+ WHERE id = :id";
+ $updateStmt = $dbh->prepare($sql);
+ } else {
+ $sql = "
+ UPDATE videos
+ SET active = true
+ WHERE id = :id";
+ $updateStmt = $dbh->prepare($sql);
+ }
+
+ $updateStmt->bindParam(
+ ':id',
+ $id,
+ PDO::PARAM_INT
+ );
+ $updateStmt->execute();
+ $dbh->commit();
+} catch (PDOException $e) {
+ $dbh->rollback();
+ Toolkit_Logger::logException('DB Error', $e);
+}
+
+header('Location: '.MEDIA_BASE_URL.'admin/videos.php');
diff --git a/Toolkit/Videos/toggleFeatured.php b/Toolkit/Videos/toggleFeatured.php
new file mode 100644
index 0000000..53b6294
--- /dev/null
+++ b/Toolkit/Videos/toggleFeatured.php
@@ -0,0 +1,65 @@
+
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link http://demo.gaslightmedia.com
+ */
+if (!isset($_GET['kpass'])) {
+ die();
+}
+require_once '../../setup.phtml';
+
+$dbh = Toolkit_Database::getInstance();
+$id = $_REQUEST['id'];
+
+try {
+ $dbh->beginTransaction();
+ $sql = "
+ SELECT featured
+ FROM videos
+ WHERE id = :id";
+ $stmt = $dbh->prepare($sql);
+ $stmt->bindParam(
+ ":id",
+ $_REQUEST['id'],
+ PDO::PARAM_INT
+ );
+ $stmt->execute();
+ $featuredState = $stmt->fetchColumn();
+
+ if ($featuredState) {
+ $sql = "
+ UPDATE videos
+ SET featured = false
+ WHERE id = :id";
+ $updateStmt = $dbh->prepare($sql);
+ } else {
+ $sql = "
+ UPDATE videos
+ SET featured = true
+ WHERE id = :id";
+ $updateStmt = $dbh->prepare($sql);
+ }
+
+ $updateStmt->bindParam(
+ ':id',
+ $id,
+ PDO::PARAM_INT
+ );
+ $updateStmt->execute();
+ $dbh->commit();
+} catch (PDOException $e) {
+ $dbh->rollback();
+ Toolkit_Logger::logException('DB Error', $e);
+}
+
+header('Location: '.MEDIA_BASE_URL.'admin/videos.php');
diff --git a/Toolkit/qfcaptcha.php b/Toolkit/qfcaptcha.php
new file mode 100755
index 0000000..8b789de
--- /dev/null
+++ b/Toolkit/qfcaptcha.php
@@ -0,0 +1,39 @@
+
+ * @copyright 2006-2008 by Philippe Jausions / 11abacus
+ * @license http://www.opensource.org/licenses/bsd-license.php New BSD
+ * @version CVS: $Id: qfcaptcha.php,v 1.2 2009/10/01 16:00:02 jamie Exp $
+ * @filesource
+ * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA
+ * @see qfcaptcha_form_image.php
+ * @see qfcaptcha_form_random.php
+ */
+
+// Require the class before opening the session
+// so the instance unserialize properly
+require_once '../setup.phtml';
+require_once 'Text/CAPTCHA.php';
+require_once 'Text/CAPTCHA/Driver/Image.php';
+
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+header('Content-Type: image/jpeg');
+
+$sessionVar = (empty($_REQUEST['var']))
+ ? '_HTML_QuickForm_CAPTCHA'
+ : $_REQUEST['var'];
+
+// Force a new CAPTCHA for each one displayed
+$_SESSION[$sessionVar]->setPhrase();
+
+echo $_SESSION[$sessionVar]->getCAPTCHAAsJPEG();
+?>
diff --git a/admin/.htaccess b/admin/.htaccess
new file mode 100644
index 0000000..38dcd05
--- /dev/null
+++ b/admin/.htaccess
@@ -0,0 +1 @@
+RewriteEngine Off
diff --git a/admin/Contact/contact_inquiry.phtml b/admin/Contact/contact_inquiry.phtml
new file mode 100755
index 0000000..0b89a92
--- /dev/null
+++ b/admin/Contact/contact_inquiry.phtml
@@ -0,0 +1,125 @@
+
+ * @copyright 2009 Gaslight Media
+ * @license Gaslight Media
+ * @version CVS: $Id: contact_inquiry.phtml,v 1.3 2009/07/24 14:27:45 matrix Exp $
+ * @link http://pear.php.net/package/Contacts
+ * @see References to other sections (if any)...
+ */
+
+/**
+ * base setup file for all apps
+ */
+require_once '../../setup.phtml';
+
+/**
+ * base setup for contact admin section
+ */
+require_once "contact_setup.inc";
+GLM_TOOLBOX::top('Contact Inquiries', '');
+// Adjust the nav for this page, add the Edit Groups page.
+if (is_array($nav) && array_key_exists('Contact Inquiry Fields', $nav)) {
+ $tmp = array('Inquiry Groups' => 'list_groups.php');
+ array_insert($nav, 'Contact Inquiry Fields', $tmp);
+}
+GLM_TOOLBOX::html_nav_table($nav, $navWidth);
+$qs = "
+ SELECT id, header, groupid, pos
+ FROM contact_inq
+ ORDER BY groupid, pos;";
+$result = $DB->db_exec($qs);
+$query = "
+ SELECT id, name
+ FROM inq_group
+ ORDER BY name;";
+if ($groupData = $DB->db_auto_get_data($query)) {
+ foreach ($groupData as $groupRow) {
+ $gRow[$groupRow['id']] = $groupRow['name'];
+ }
+}
+?>
+
+
diff --git a/admin/Contact/contact_setup.inc b/admin/Contact/contact_setup.inc
new file mode 100755
index 0000000..95f721e
--- /dev/null
+++ b/admin/Contact/contact_setup.inc
@@ -0,0 +1,475 @@
+
+* @copyright 2009 Steve Sutton
+* @license Gaslight Media
+* @version CVS: $Id: contact_setup.inc,v 1.7 2010/05/13 17:05:53 matrix Exp $
+* @link <>
+*/
+extract($_REQUEST);
+// The Contact Type array is now is one location and is used by the
+// Toolkit_Contacts_Admin_EditContact class
+$conf = new Config;
+$contactRoot =& $conf->parseConfig(
+ BASE . 'Toolkit/Contacts/config.ini',
+ 'IniFile'
+);
+if (!defined("ENTRIES_PER_PAGE")) {
+
+ /**
+ * how many per page on list contacts
+ */
+ define("ENTRIES_PER_PAGE", 10); // Entries per Page in list_contact.phtml
+}
+
+/**
+* define for customer table
+*/
+define("CUSTOMER_TABLE", "customer"); // name of customer table
+
+/**
+* define for contact table
+*/
+define("CONTACT_TABLE", "contact"); // name of contact table
+
+$table = $contactRoot->getItem('section', 'conf')
+ ->getItem('directive', 'table')
+ ->getContent();
+/**
+* Table to user in db
+*/
+define("TABLE", $table); // which table to use
+
+/**
+* postgres date formate
+*/
+define("DATEFORMAT", "US"); // date format (for edit_contact.phmtl)
+
+/**
+* template for the newsletter
+*/
+define("NEWSLETTER_PROTOTYPE", "newsletter_template.html"); // date format (for edit_contact.phmtl)
+
+/**
+* class_template needed for GLM_TEMPLATE::get_seo_url()
+*/
+require_once BASE.'classes/class_template.inc';
+$DB = new GLM_DB();
+if (!defined("HTML_EMAIL")) {
+
+ /**
+ * HTML_EMAIL = ON or OFF
+ */
+ define("HTML_EMAIL", "ON");
+}
+if (!defined("PRODUCTION_MODE")) {
+
+ /**
+ * PRODUCTION_MODE off/on mail sent
+ */
+ define("PRODUCTION_MODE", "ON");
+}
+if (!defined("NEWSLETTER")) {
+
+ /**
+ * NEWSLETTER 1 or true will allow newsletters
+ */
+ define("NEWSLETTER", 1); //bool- does the contact database mail out a newsletter?
+}
+
+if (!function_exists("template_read")) {
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $template Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ */
+ function template_read($template)
+ {
+ $fp = fopen($template, "r");
+ $contents = fread($fp, filesize($template));
+ fclose($fp);
+ if ($contents) {
+ return $contents;
+ } else {
+ return "";
+ }
+ }
+}
+// {{{ array_insert()
+
+
+/**
+* insert an array into another array after position.
+* You can specify an associative array key or index key
+* to dictact the positioning of the new array
+*
+* @param array &$array array to be used
+* @param unknown $position position to add array
+* @param unknown $insert_array array to be inserted
+*
+* @return void
+*/
+function array_insert(&$array, $position, $insert_array)
+{
+ if (!is_int($position)) {
+ $i = 0;
+ foreach ($array as $key => $value) {
+ if ($key == $position) {
+ $position = ++$i;
+ break;
+ }
+ ++$i;
+ }
+ }
+ $first_array = array_splice($array, 0, $position);
+ $array = array_merge($first_array, $insert_array, $array);
+}
+// }}}
+// {{{ explode_template()
+if (!function_exists("explode_template")) {
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $template Parameter description (if any) ...
+ * @param unknown $data Parameter description (if any) ...
+ *
+ * @return unknown Return description (if any) ...
+ */
+ function explode_template($template, $data)
+ {
+ $template = template_read($template);
+ $output = template_replacement($template, $data);
+ $output = wordwrap($output, 72);
+ return $output;
+
+ }
+}
+// }}}
+// {{{ template_replacement($template, $fieldarr)
+if (!function_exists("template_replacement")) {
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $template Parameter description (if any) ...
+ * @param array $fieldarr Parameter description (if any) ...
+ *
+ * @return unknown Return description (if any) ...
+ */
+ function template_replacement($template, $fieldarr)
+ {
+ if (is_array($fieldarr)) {
+ foreach ($fieldarr as $key => $value) {
+ $template = str_replace("", $value, $template);
+ }
+ }
+ return $template;
+ }
+}
+// }}}
+// {{{ add_image($image, $align)
+if (!function_exists("add_image")) {
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $image Parameter description (if any) ...
+ * @param string $align Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ */
+ function add_image($image, $align)
+ {
+ if ($image != "") {
+ return '';
+ }
+ }
+}
+// }}}
+// {{{ Navigation array
+$nav = array(
+ "Report Builder" => "index.phtml",
+ "Add Contact" => "edit_contact.php",
+ "List Contacts" => "list_contact.phtml",
+ "Contact Inquiry Fields" => "contact_inquiry.phtml",
+ "HTML Emails" => "emails.php",
+ "Saved Reports" => "list_query.phtml",
+);
+// }}}
+$navWidth = 7;
+$query = "select * from contact_inq order by pos;";
+$cData = $DB->db_auto_get_data($query);
+if (is_array($cData)) {
+ foreach ($cData as $key => $value) {
+ $int_array[$value['id']] = $value['header'];
+ }
+}
+$contactTypesSetup =
+ $contactRoot->getItem('section', 'contact_types')
+ ->toArray();
+$cType = $contactTypesSetup['contact_types'];
+// {{{ search_where($name, $search_where)
+
+/**
+* Short description for function
+*
+* Long description (if any) ...
+*
+* @param string $name Parameter description (if any) ...
+* @param string $search_where Parameter description (if any) ...
+*
+* @return string Return description (if any) ...
+*/
+function search_where($name, $search_where)
+{
+ $out = '
+
+ Anywhere
+ Begining
+ Ending
+ ';
+ return $out;
+}
+// }}}
+// {{{ search_type($name, $search_type)
+
+/**
+* Short description for function
+*
+* Long description (if any) ...
+*
+* @param string $name Parameter description (if any) ...
+* @param string $search_type Parameter description (if any) ...
+*
+* @return string Return description (if any) ...
+*/
+function search_type($name, $search_type)
+{
+ $out = '
+
+ And
+ Or
+ Not
+ ';
+ return $out;
+}
+// }}}
+// {{{ search_bool($name, $search_type)
+
+/**
+* Short description for function
+*
+* Long description (if any) ...
+*
+* @param string $name Parameter description (if any) ...
+* @param string $search_type Parameter description (if any) ...
+*
+* @return string Return description (if any) ...
+*/
+function search_bool($name, $search_type)
+{
+ $out = '
+
+ Don\'t Care
+ Yes
+ No
+ ';
+ return( $out );
+}
+// }}}
+// {{{ interest($field)
+
+/**
+* Short description for function
+*
+* Long description (if any) ...
+*
+* @param unknown $field Parameter description (if any) ...
+*
+* @return boolean Return description (if any) ...
+*/
+function interest($field)
+{
+ if (!is_array($GLOBALS['int_array'])) {
+ return false;
+ }
+ echo "";
+}
+/**
+* Get a group of select elements to represent a date
+*
+* @param string $M Name attribute of the month select list
+* @param string $D Name attribute of the day select list
+* @param string $Y Name attribute of the year select list
+* @param string $m Selected value of the month select list
+* @param string $d Selected value of the day select list
+* @param string $y Selected value of the year select list
+*
+* @return string Html string of group select lists
+* @access public
+*/
+function dateSelector($M, $D, $Y, array $m = null, array $d = null, array $y = null)
+{
+ // Get a Select element
+ $month = new HTML_Select($M);
+ // Get a Range of months jan-dec
+ $monthArray = array_flip(range(1, 12));
+ // Make the keys and values the same
+ foreach ($monthArray as $i => &$j) {
+ $j = $i;
+ }
+ $month->loadArray($monthArray);
+ if (is_null($m)) {
+ $month->setSelectedValues(array(date('m')));
+ } else {
+ $month->setSelectedValues($m);
+ }
+
+ // Get a Select element
+ $day = new HTML_Select($D);
+ // Get a Range of months jan-dec
+ $dayArray = array_flip(range(1, 31));
+ // Make the keys and values the same
+ foreach ($dayArray as $i => &$j) {
+ $j = $i;
+ }
+ $day->loadArray($dayArray);
+ if (is_null($d)) {
+ $day->setSelectedValues(array(date('d')));
+ } else {
+ $day->setSelectedValues($d);
+ }
+
+ // Get a Select element
+ $year = new HTML_Select($Y);
+ // Get a Range of months jan-dec
+ $yearArray = array_flip(range(CONTACTS_FIRST_YEAR, date('Y')));
+ // Make the keys and values the same
+ foreach ($yearArray as $i => &$j) {
+ $j = $i;
+ }
+ $year->loadArray($yearArray);
+ if (is_null($y)) {
+ $year->setSelectedValues(array(date('Y')));
+ } else {
+ $year->setSelectedValues($y);
+ }
+
+ return $month->toHtml() . $day->toHtml() . $year->toHtml();
+}
+
+// }}}
+// default query on create_date
+$c_date_from = GLM_TOOLBOX::contact_date_entry("", "", "", "fc_month", "fc_day", "fc_year");
+$c_date_to = GLM_TOOLBOX::contact_date_entry("", "", "", "tc_month", "tc_day", "tc_year");
+
+// The Following $DB_fields array is no longer used for the edit contact page
+// You must alter the class Toolkit_Contacts_Admin_EditContact
+// The following is only used for the search form and the listing pages
+
+$primaryKey = $contactRoot->getItem('section', 'conf')
+ ->getItem('directive', 'primarykey')
+ ->getContent();
+/**
+* Description for define
+*/
+define("ID", $primaryKey);
+
+/**
+* Description for define
+*/
+define("MAILOK", "mail_ok");
+
+$sequence = $contactRoot->getItem('section', 'conf')
+ ->getItem('directive', 'sequence')
+ ->getContent();
+/**
+* Description for define
+*/
+define("SEQUENCE", $sequence);
+
+/**
+* Description for define
+*/
+define("WHERE", ID." IS NOT NULL");
+// $DB_fields are used for edit and updating contacts
+$DB_fields[] = array("name" => "id", "title" => "id", "type" => "hide");
+$DB_fields[] = array("name" => "create_date", "title" => "Create Date", "type" => "static");
+$DB_fields[] = array("name" => "fname", "title" => "First Name", "type" => "text");
+$DB_fields[] = array("name" => "lname", "title" => "Last Name", "type" => "text");
+if (TABLE == 'customer') {
+ $DB_fields[] = array("name" => "add1", "title" => "Address", "type" => "text");
+ $DB_fields[] = array("name" => "add2", "title" => "Address 2", "type" => "text");
+} else {
+ $DB_fields[] = array("name" => "company", "title" => "Company Name", "type" => "text");
+ $DB_fields[] = array("name" => "address", "title" => "Address", "type" => "text");
+ $DB_fields[] = array("name" => "address2", "title" => "Address 2", "type" => "text");
+}
+$DB_fields[] = array("name" => "city", "title" => "City", "type" => "text");
+$DB_fields[] = array("name" => "state", "title" => "State", "type" => "state");
+$DB_fields[] = array("name" => "zip", "title" => "Zip", "type" => "text");
+$DB_fields[] = array("name" => "phone", "title" => "Phone", "type" => "text");
+$DB_fields[] = array("name" => "fax", "title" => "Fax", "type" => "text");
+$DB_fields[] = array("name" => "email", "title" => "Email", "type" => "text");
+$DB_fields[] = array("name" => "mail_ok", "title" => "Mail Ok?", "type" => "radio");
+$DB_fields[] = array("name" => "interest", "title" => "Interest", "type" => "interest");
+$DB_fields[] = array("name" => "contact_type", "title" => "Contact Type", "type" => "drop", "drop" => $cType);
+
+// $fields are used for building the query page
+foreach ($DB_fields as $key=>$value) {
+ if ($value['type'] == "text" || $value['type'] == "state") {
+ $fields[$value['name']] = $value['title'];
+ } elseif ( $value['type'] == "radio") {
+ $boolean[$value['name']] = $value['title'];
+ } elseif ( $value['type'] == "drop") {
+ $dropdowns[$value['name']] = array('title' => $value['title'], 'drop' => $value['drop']);
+ }
+}
+
+$data['bailout'] .= "You are receiving this message because you have expressed an interest in ";
+$data['bailout'] .= "receiving specials and information from ".SITENAME.". If you do not ";
+$data['bailout'] .= "wish to receive future items of this nature, please reply to this e-mail ";
+$data['bailout'] .= "with the word \"CANCEL\" on the subject line. You will then be removed ";
+$data['bailout'] .= "from future mailings. ";
+$data['bailout'] .= "".OWNER_EMAIL." ";
+?>
diff --git a/admin/Contact/del_query.phtml b/admin/Contact/del_query.phtml
new file mode 100755
index 0000000..0ad9363
--- /dev/null
+++ b/admin/Contact/del_query.phtml
@@ -0,0 +1,20 @@
+db_auto_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,1);
+}
+GLM_TOOLBOX::html_header("Admin","Deleted","");
+?>
+
+Query is Deleted
+Close This
+Window
diff --git a/admin/Contact/download.phtml b/admin/Contact/download.phtml
new file mode 100755
index 0000000..c60bd88
--- /dev/null
+++ b/admin/Contact/download.phtml
@@ -0,0 +1,228 @@
+
+ * @copyright 2009 Gaslight Media
+ * @license Gaslight Media
+ * @version CVS: $Id: download.phtml,v 1.3 2009/08/05 15:15:00 matrix Exp $
+ * @link <>
+ */
+
+/**
+ * main site setup config file
+ */
+require_once "../../setup.phtml";
+
+/**
+ * main contact setup file
+ */
+require_once "contact_setup.inc";
+
+// check that the site sending this request is the same
+// as the base_url
+$base = str_replace("admin/Contact/list_contact.phtml",
+ "",
+ $_SERVER['HTTP_REFERER']
+);
+if ($base != MEDIA_BASE_URL) {
+ // redirect them
+ header("Location: index.phtml");
+}
+
+$delimiter = str_replace("comma", ",", $delimiter);
+$delimiter = str_replace("tab", "\t", $delimiter);
+$delimiter = str_replace("csv", ",", $delimiter);
+$delimiter = str_replace("pipe", "|", $delimiter);
+
+if ($_REQUEST['query_string']) {
+ /* Remove the old reports if they exsists */
+ if (is_file("report.csv")) {
+ unlink("report.csv");
+ }
+ if (is_file("report.tar.gz")) {
+ unlink("report.tar.gz");
+ }
+ if (is_file("report.zip")) {
+ unlink("report.zip");
+ }
+
+ if (!$fp = fopen("report.csv", "w")) {
+ html_error("Cant open report", 0);
+ }
+ $query_string = stripslashes($_REQUEST['query_string']);
+ $query_string = str_replace("SELECT " . ID . ",", "SELECT ", $query_string);
+ $query_string = str_replace(" FROM ",
+ ",contact_type,interest FROM ",
+ $query_string);
+
+ $dbh = Toolkit_Database::getInstance();
+
+ $res = $dbh->prepare($query_string);
+ $res->execute();
+ $total = $res->rowCount();
+ $headers =array();
+ $headerString = '';
+ if ($total > 0) {
+ for ($i = 0; $i < $total; ++$i) {
+ $result_string = "";
+ $row = $res->fetch(PDO::FETCH_ASSOC);
+ $cConTypes = array();
+ foreach ($row as $fieldName => $value) {
+ if ($i == 0) {
+ if (in_array($fieldName, array('contact_type', 'interest'))) {
+ switch ($fieldName) {
+ case 'contact_type' :
+ foreach ($cType as $contactTypeName) {
+ $headers[] = $contactTypeName;
+ }
+ break;
+ case 'interest' :
+ if ( is_array($int_array)
+ && !empty($int_array)
+ ) {
+ foreach ($int_array as $interesName) {
+ $headers[] = $interesName;
+ }
+ }
+ break;
+ }
+ } else {
+ $headers[] = $fieldName;
+ }
+ }
+ // this section creates the contact_type part of the rows
+ // need to make this one a set number of fields for the contact
+ // types needed for all contacts
+ // so create count($cType) number of columns for this one field
+ if ($fieldName == 'contact_type') {
+ $cConTypes = array();
+ $st = array();
+ if (strstr($value, ":")) {
+ $cConTypesStr = preg_replace("/^:|:$/",
+ "",
+ $value
+ );
+ $cConTypes = explode(":", $cConTypesStr);
+ }
+ if (is_array($cType) && !empty($cType)) {
+ foreach ($cType as $contactTypeId => $contactTypeName) {
+ $st[]
+ = ( is_array($cConTypes)
+ && in_array($contactTypeId, $cConTypes))
+ ? $contactTypeName
+ : '';
+ }
+ $result_string .= implode("|", $st);
+ }
+ $result_string .= '|';
+ }
+ // this section creates the interest part of the rows
+ // need to make this one a set number of fields for the contact
+ // types needed for all contacts
+ // so create count($int_array) number of columns for this one field
+ else if ($fieldName == 'interest') {
+ $iIntTypes = array();
+ $st = array();
+ if (strstr($value, ":")) {
+ $iIntTypesStr = preg_replace("/^:|:$/",
+ "",
+ $value);
+ $iIntTypes = explode(":", $iIntTypesStr);
+ }
+ if ( is_array($int_array)
+ && !empty($int_array)
+ ) {
+ foreach ($int_array as $interestId => $interestName) {
+ $st[]
+ = ( is_array($iIntTypes)
+ && in_array($interestId, $iIntTypes))
+ ? $interestName
+ : '';
+ }
+ $result_string .= implode("|", $st);
+ }
+ $result_string .= '|';
+ }
+ // this one deals with al the other fields
+ else if (!in_array($fieldName, array('contact_type', 'interest'))) {
+ $result_string .= $value.'|';
+ }
+ }
+ $result_string = substr($result_string, 0, strlen($result_string)-1);
+ if ($i == 0) {
+ if ($csv) {
+ $headerString = '"'.implode('","', $headers)."\"\n";
+ } else {
+ $headerString = implode($delimiter, $headers)."\n";
+ }
+ fputs($fp, $headerString, strlen($headerString));
+ }
+ if ($csv) {
+ $result_string = str_replace("|", "\",\"", $result_string);
+ $result_string = "\"".$result_string."\"\n";
+ } else {
+ $result_string = str_replace("|", $delimiter, $result_string);
+ $result_string = $result_string."\n";
+ }
+ fputs($fp, $result_string, strlen($result_string));
+ }
+ }
+ if (!fclose($fp)) {
+ html_error("Cant close filepointer", 0);
+ }
+ chmod("report.csv", 0660);
+ $output = "report.csv";
+
+ if ($file == "gz") {
+ $output = "report.tar.gz";
+ exec("tar -czvf report.tar.gz report.csv 2>&1", $result_array, $result);
+ if ($result != 0) {
+ echo $result_array[0];
+ exit;
+ }
+ chmod("report.tar.gz", 0660);
+ }
+
+ if ($file == "zip") {
+ $output = "report.zip";
+ exec("zip report report.csv 2>&1", $result_array, $result);
+ if ($result != 0) {
+ echo $result_array[0];
+ exit;
+ }
+ chmod("report.zip", 0660);
+ }
+ if ($file == "rpt") {
+ $output = "report.csv";
+ chmod("report.csv", 0660);
+ }
+ if (ini_get('zlib.output_compression')) {
+ ini_set('zlib.output_compression', 'Off');
+ }
+ header("Content-Type: application/force-download\n");
+ /* Correction for the stupid MSIE thing */
+ if (strstr(getenv('HTTP_USER_AGENT'), 'MSIE')) {
+ header("Content-Disposition: inline; filename=\"$output\"");
+ } else {
+ header("Content-Disposition: attachment; filename=\"$output\"");
+ }
+ //header("Location: $output");
+ $fn = fopen($output, "r");
+ fpassthru($fn);
+ @fclose($fn);
+ exit();
+} else {
+ header("Location: list_contact.phtml");
+}
+?>
diff --git a/admin/Contact/edit_autoresponse.phtml b/admin/Contact/edit_autoresponse.phtml
new file mode 100755
index 0000000..3000ae6
--- /dev/null
+++ b/admin/Contact/edit_autoresponse.phtml
@@ -0,0 +1,102 @@
+db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__, 1);
+ }
+ $row = $DB->db_fetch_array($res,0, PGSQL_ASSOC);
+} else {
+ $row['subject'] = '';
+ $row['response'] = '';
+}
+?>
+
+
+
+
+
+ ';
+GLM_TOOLBOX::footer();
+?>
diff --git a/admin/Contact/edit_contact.php b/admin/Contact/edit_contact.php
new file mode 100644
index 0000000..01a7f2f
--- /dev/null
+++ b/admin/Contact/edit_contact.php
@@ -0,0 +1,25 @@
+setConfig($contactRoot);
+$form->setTableName(
+ $contactRoot->getItem('section', 'conf')
+ ->getItem('directive', 'table')
+ ->getContent()
+);
+$form->setPrimaryKey(
+ $contactRoot->getItem('section', 'conf')
+ ->getItem('directive', 'primarykey')
+ ->getContent()
+);
+
+$form->configureForm($contactRoot);
+$formOutput = $form->toHtml();
+GLM_TOOLBOX::top("Updatable Listings (Add/Edit)", "help/contact.phtml?key=Edit");
+GLM_TOOLBOX::html_nav_table($nav, $navWidth);
+echo $formOutput;
+GLM_TOOLBOX::footer();
diff --git a/admin/Contact/edit_group.php b/admin/Contact/edit_group.php
new file mode 100644
index 0000000..93c4751
--- /dev/null
+++ b/admin/Contact/edit_group.php
@@ -0,0 +1,99 @@
+db_exec($qs);
+ header('Location: list_groups.php');
+ } else if ($sub_oktogo && isset($qs)) {
+ $DB->db_exec($qs);
+ header('Location: list_groups.php');
+ }
+}
+?>
+
+
+ 'list_groups.php');
+ array_insert($nav, 'Contact Inquiry Fields', $tmp);
+}
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+if (is_numeric($_GET['id'])) {
+ $query = 'SELECT * FROM inq_group WHERE id = '.$_GET['id'];
+ if ($data = $DB->db_auto_get_data($query)) {
+ $name = $data[0]['name'];
+ $id = $data[0]['id'];
+ }
+} else {
+ $name = '';
+}
+?>
+
+
+
+
diff --git a/admin/Contact/edit_inquiry.phtml b/admin/Contact/edit_inquiry.phtml
new file mode 100755
index 0000000..fbf65ae
--- /dev/null
+++ b/admin/Contact/edit_inquiry.phtml
@@ -0,0 +1,129 @@
+
+
+
+ 'list_groups.php');
+ array_insert($nav, 'Contact Inquiry Fields', $tmp);
+}
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+if (is_numeric($_GET['id'])) {
+ $query = "SELECT * FROM contact_inq WHERE id = $id";
+ if ($data = $DB->db_auto_get_data($query)) {
+ $header = $data[0]['header'];
+ $description = $data[0]['description'];
+ $pos = $data[0]['pos'];
+ $groupid = $data[0]['groupid'];
+ }
+} else {
+ $header = '';
+ $description = '';
+ $groupid = '';
+}
+$query = "SELECT * FROM inq_group ORDER BY name;";
+if ($gData = $DB->db_auto_get_data($query)) {
+ $group_sel = '';
+ $group_sel .= 'New Group - >> ';
+ foreach ($gData as $gRow) {
+ $group_sel .= '
+
+
+
+
+
diff --git a/admin/Contact/emails.php b/admin/Contact/emails.php
new file mode 100644
index 0000000..86695f7
--- /dev/null
+++ b/admin/Contact/emails.php
@@ -0,0 +1,36 @@
+db_auto_get_data( $query );
+GLM_TOOLBOX::top( "Email HTML Newsletters", "");
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+$out = '
+
+
+ Add HTML EMAIL
+
+
+ Function:
+ Subject:
+ Last Update:
+
+ ';
+
+if (is_array($data)) {
+ foreach ($data as $key => $val) {
+ $out .= '
+ [Edit]
+ [View]
+ '.$val["subject"].'
+ '.$val["last_update"].'
+ [Delete]
+ ';
+ }
+}
+$out .= '
';
+echo $out;
+GLM_TOOLBOX::footer();
+?>
diff --git a/admin/Contact/form.js b/admin/Contact/form.js
new file mode 100755
index 0000000..0bbabf0
--- /dev/null
+++ b/admin/Contact/form.js
@@ -0,0 +1,42 @@
+function reshow(object) {
+ artist = object.options[object.selectedIndex].text;
+ for (var i = document.track.names.length;i > 0;i--)
+ document.track.names.options[0] = null;
+ reloading = true;
+ showlinks();
+ document.track.names.options[0].selected = true;
+ return false;
+}
+
+function load(object) {
+ alert('Just testing: ' + object.options[object.selectedIndex].value);
+ //window.location.href = object.options[object.selectedIndex].value;
+ return false;
+}
+
+function showlinks() {
+ if (artist == 'Chris Rea') {
+ opt('cr/one.zip','The Road To Hell');
+ opt('cr/two.zip','Let\'s Dance');
+ }
+
+ if (artist == 'Annie Lennox') {
+ opt('al/why.zip','Why');
+ opt('al/wobg.zip','Walking on Broken Glass');
+ }
+
+ if (artist == 'Dina Carrol') {
+ opt('dc/track1.zip','Escaping');
+ opt('dc/track2.zip','Only Human');
+ }
+}
+
+function opt(href,text) {
+ if (reloading) {
+ var optionName = new Option(text, href, false, false)
+ var length = document.track.names.length;
+ document.track.names.options[length] = optionName;
+ }
+ else
+ document.write(' ',text,'<\/OPTION>');
+}
diff --git a/admin/Contact/help/contact.phtml b/admin/Contact/help/contact.phtml
new file mode 100755
index 0000000..bdec6d7
--- /dev/null
+++ b/admin/Contact/help/contact.phtml
@@ -0,0 +1,146 @@
+
+
+Help
+
+
+
+Contact Help
+
+
+switch ($key) {
+ case "search":
+ ?>
+Contact Database Search
+
+
+In this page you will start to build your query to the contact database.
+
+
+Search:
+
+
+Search records for:
+
+Here is where you will enter any keywords to use in the search. You must
+enter in something in the "Search records for" box. You may use more than one
+word (ie.) Sam Field.
+HINT: To help search use wildcards!
+? optional space
+* optional spaces
++ at least one space
+. will match anything
+
+NOTE: Leaving this fields blank will select all
+contacts. You can leave this blank and choose "Mail OK" true to get all
+contacts that allow emails.
+Search Where in fields:
+Tells the database to Search "Anywhere", "Beginning", or "Ending" of the
+fields to be searched.
+In Fields:
+Select from "In Fields" box. This determines what fields to look in for
+this search.
+HINT
+If you want to select more than one field to search in hold down the 'Ctrl' key while clicking on the selection to select or
+deselect it from the list.
+HINT
+You can use the "All" and "None" buttons to help you save time. This will
+select all or none of the fields in the boxes.
+Search Type:
+Select the type of search you want (ie.) an "Exact string" search will return
+only those fields which match the "Search records" for string exactly as compared
+to "Or" which will return any field that match any words you place into "Search
+records for"
+Case Sensitivity:
+This will turn "On" and "Off" the case sensitivity.
+(ie.)If you leave it "Off" and enter "bob" it will return anything like
+"bob","BOB","Bob","BOb","boB",or "BoB" turned "On" will match only "bob".
+
+
+Output of records
+
+Output Fields:
+Select from "Output Fields" box. This determines what fields will be in the
+output of this search.
+HINT
+You can use the "All" and "None" buttons to help you save time. This will
+select all or none of the fields in the boxes.
+HINT
+If you want to select more than
+one Output field hold down the 'Ctrl' key while clicking on the selection to select or
+deselect it from the list.
+File Output:
+Select from here if you wish to download a file with the results of this
+search. The file will built "On the Fly" so you can download it.
+NOTE: The text file is output as report.doc. This
+is only a text file.
+
+Delimiter:
+This determines what separates the fields in your file.
+
+
+ break;
+
+ case "List":
+ ?>
+List Contacts
+
+This page is for listing the results of your query. You can download files if
+you have selected a file type or edit and delete the contact found.
+
+[Edit]
+Link to contact edit page.
+
+[Delete]
+Link to Delete Contact.
+
+Download Files
+If you see this then there is a file you can download.
+Click on the file and you can download it.
+
+ break;
+
+ case "Edit":
+ ?>
+Edit a Contact
+
+This page is for editing and modifying an existing Contact in the database.
+When editing is complete, click on the "Submit Query" button. The database will
+be updated, and you will be directed back to the "List Contacts" page.
+
+
+
+
+Submit Query
+
+When you have made the changes you want to the Contact,
+you can click "Submit Query." This will update the information about the
+Contact in the database.
+
+
+ break;
+
+ case "Add":
+ ?>
+Add an Contact
+
+This page is for Adding Contacts in the database.
+When form is complete, click on the "Submit Query" button. The database will
+be updated, and you will be directed back to the "List Contacts" page.
+
+
+
+Submit Query
+
+When you have made the changes you want to the Contact,
+you can click "Submit Query." This will update the information about the
+Contact in the database.
+
+
+ break;
+
+}
+?>
+
+
+
+
diff --git a/admin/Contact/htmlarea.css b/admin/Contact/htmlarea.css
new file mode 100644
index 0000000..23bdf7d
--- /dev/null
+++ b/admin/Contact/htmlarea.css
@@ -0,0 +1,180 @@
+.htmlarea { background: #fff; }
+
+.htmlarea .toolbar {
+ cursor: default;
+ background: ButtonFace;
+ padding: 1px 1px 2px 1px;
+ border: 1px solid;
+ border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+.htmlarea .toolbar table { font-family: tahoma,verdana,sans-serif; font-size: 11px; }
+.htmlarea .toolbar img { border: none; }
+.htmlarea .toolbar .label { padding: 0px 3px; }
+
+.htmlarea .toolbar .button {
+ background: ButtonFace;
+ color: ButtonText;
+ border: 1px solid ButtonFace;
+ padding: 1px;
+ margin: 0px;
+}
+.htmlarea .toolbar .buttonHover {
+ border: 1px solid;
+ border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+.htmlarea .toolbar .buttonActive, .htmlarea .toolbar .buttonPressed {
+ padding: 2px 0px 0px 2px;
+ border: 1px solid;
+ border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
+}
+.htmlarea .toolbar .buttonPressed {
+ background: ButtonHighlight;
+}
+.htmlarea .toolbar .indicator {
+ padding: 0px 3px;
+ overflow: hidden;
+ width: 20px;
+ text-align: center;
+ cursor: default;
+ border: 1px solid ButtonShadow;
+}
+
+.htmlarea .toolbar .buttonDisabled { background-color: #aaa; }
+
+.htmlarea .toolbar .buttonDisabled img {
+ filter: alpha(opacity = 25);
+ -moz-opacity: 25%;
+}
+
+.htmlarea .toolbar .separator {
+ position: relative;
+ margin: 3px;
+ border-left: 1px solid ButtonShadow;
+ border-right: 1px solid ButtonHighlight;
+ width: 0px;
+ height: 16px;
+ padding: 0px;
+}
+
+.htmlarea .toolbar .space { width: 5px; }
+
+.htmlarea .toolbar select { font: 11px Tahoma,Verdana,sans-serif; }
+
+.htmlarea .toolbar select,
+.htmlarea .toolbar select:hover,
+.htmlarea .toolbar select:active { background: FieldFace; color: ButtonText; }
+
+.htmlarea .statusBar {
+ border: 1px solid;
+ border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
+ padding: 2px 4px;
+ background-color: ButtonFace;
+ color: ButtonText;
+ font: 11px Tahoma,Verdana,sans-serif;
+}
+
+.htmlarea .statusBar .statusBarTree a {
+ padding: 2px 5px;
+ color: #00f;
+}
+
+.htmlarea .statusBar .statusBarTree a:visited { color: #00f; }
+.htmlarea .statusBar .statusBarTree a:hover {
+ background-color: Highlight;
+ color: HighlightText;
+ padding: 1px 4px;
+ border: 1px solid HighlightText;
+}
+
+
+/* Hidden DIV popup dialogs (PopupDiv) */
+
+.dialog {
+ color: ButtonText;
+ background: ButtonFace;
+}
+
+.dialog .content { padding: 2px; }
+
+.dialog, .dialog button, .dialog input, .dialog select, .dialog textarea, .dialog table {
+ font: 11px Tahoma,Verdana,sans-serif;
+}
+
+.dialog table { border-collapse: collapse; }
+
+.dialog .title {
+ background: #008;
+ color: #ff8;
+ border-bottom: 1px solid #000;
+ padding: 1px 0px 2px 5px;
+ font-size: 12px;
+ font-weight: bold;
+ cursor: default;
+}
+
+.dialog .title .button {
+ float: right;
+ border: 1px solid #66a;
+ padding: 0px 1px 0px 2px;
+ margin-right: 1px;
+ color: #fff;
+ text-align: center;
+}
+
+.dialog .title .button-hilite { border-color: #88f; background: #44c; }
+
+.dialog button {
+ width: 5em;
+ padding: 0px;
+}
+
+.dialog .buttonColor {
+ padding: 1px;
+ cursor: default;
+ border: 1px solid;
+ border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+
+.dialog .buttonColor-hilite {
+ border-color: #000;
+}
+
+.dialog .buttonColor .chooser, .dialog .buttonColor .nocolor {
+ height: 0.6em;
+ border: 1px solid;
+ padding: 0px 1em;
+ border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
+}
+
+.dialog .buttonColor .nocolor { padding: 0px; }
+.dialog .buttonColor .nocolor-hilite { background-color: #fff; color: #f00; }
+
+.dialog .label { text-align: right; width: 6em; }
+.dialog .value input { width: 100%; }
+.dialog .buttons { text-align: right; padding: 2px 4px 0px 4px; }
+
+.dialog legend { font-weight: bold; }
+.dialog fieldset table { margin: 2px 0px; }
+
+.popupdiv {
+ border: 2px solid;
+ border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+
+.popupwin {
+ padding: 0px;
+ margin: 0px;
+}
+
+.popupwin .title {
+ background: #fff;
+ color: #000;
+ font-weight: bold;
+ font-size: 120%;
+ padding: 3px 10px;
+ margin-bottom: 10px;
+ border-bottom: 1px solid black;
+ letter-spacing: 2px;
+}
+
+form { margin: 0px; border: none; }
diff --git a/admin/Contact/index.phtml b/admin/Contact/index.phtml
new file mode 100755
index 0000000..737ea2a
--- /dev/null
+++ b/admin/Contact/index.phtml
@@ -0,0 +1,315 @@
+db_auto_get_data($qs);
+$total = $res[0]['total'];
+GLM_TOOLBOX::top("Contact Database","help/contact.phtml?key=search","SteveContactsDatabase_1.0");
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+?>
+
+
diff --git a/admin/Contact/list_contact.phtml b/admin/Contact/list_contact.phtml
new file mode 100755
index 0000000..b36b176
--- /dev/null
+++ b/admin/Contact/list_contact.phtml
@@ -0,0 +1,287 @@
+db_auto_get_data($checkqs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__.$checkqs,1);
+}
+
+$numcontacts = $checkres[0]['contacts'];
+if ($numcontacts == 0) {
+ GLM_TOOLBOX::html_error("There are no contacts in the database",1);
+}
+//var_dump($query_string);
+//var_dump($_REQUEST);
+//exit;
+if(!isset($back) && !isset($query_string) && !isset($query_no)) {
+ $query = "SELECT ".ID.",*
+ FROM ".TABLE."
+ WHERE ".WHERE."
+ ORDER BY lname,fname";
+
+ $query = addslashes($query);
+ $qs = "SELECT id
+ FROM query_db
+ WHERE query_name = '(current)'";
+
+ if (!$res = $DB->db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__.$qs,1);
+ }
+
+ if ($DB->db_numrows($res)==0) {
+ $qs = "INSERT
+ INTO query_db
+ (query,query_name)
+ VALUES ('$query','(current)')";
+ } else {
+ $id = $res->fetchColumn();
+ $qs = "UPDATE query_db
+ SET query = '$query',
+ file = '',
+ delimiter = ''
+ WHERE id = $id";
+ }
+ if (!$res = $DB->db_exec($qs)) {
+ html_error(DB_ERROR_MSG.__LINE__.$qs,1);
+ }
+ unset($qs);
+}
+
+if ($delimiter == "csv") {
+ $csv = TRUE;
+}
+
+if (isset($query_string) && $query_string) {
+ $query_string = strtr($query_string,"\n"," ");
+ $query_string = strtr($query_string,"\t"," ");
+ $query_string = stripslashes($query_string);
+ $qs = $query_string;
+} elseif ($query_no) {
+ $qs = "select query from query_db where id = $query_no";
+ $queryres = $DB->db_exec($qs);
+ if ($queryres->rowCount() == 0) {
+ $qs = "SELECT ".ID.",*
+ FROM ".TABLE."
+ WHERE ".WHERE."
+ ORDER BY lname,fname";
+ } else {
+ $qs = $queryres->fetchColumn();
+ }
+} else {
+ $queryqs = "SELECT query
+ FROM query_db
+ WHERE query_name LIKE '(current)'";
+ $queryres = $DB->db_exec($queryqs);
+ if ($queryres->rowCount() == 0) {
+ $qs = "SELECT ".ID.",*
+ FROM ".TABLE."
+ WHERE ".WHERE."
+ ORDER BY lname,fname";
+ } else {
+ $qs = $queryres->fetchColumn();
+ }
+}
+
+GLM_TOOLBOX::top("List Contacts","help/contact.phtml?key=List");
+?>
+
+
+
+db_exec($mquery);
+ $mailout = array();
+ while ($mrow = $mres->fetch())
+ {
+ $mailout[] = $mrow;
+ }
+?>
+
+
+ db_numrows($res) > 0) {
+?>
+
+
diff --git a/admin/Contact/list_groups.php b/admin/Contact/list_groups.php
new file mode 100644
index 0000000..ac03bb0
--- /dev/null
+++ b/admin/Contact/list_groups.php
@@ -0,0 +1,56 @@
+ 'list_groups.php');
+ array_insert($nav, 'Contact Inquiry Fields', $tmp);
+}
+GLM_TOOLBOX::html_nav_table($nav, $navWidth);
+$qs = "
+ SELECT id, name
+ FROM inq_group
+ ORDER BY name;";
+$result = $DB->db_exec( $qs );
+?>
+
+
diff --git a/admin/Contact/list_query.phtml b/admin/Contact/list_query.phtml
new file mode 100755
index 0000000..ab6d24b
--- /dev/null
+++ b/admin/Contact/list_query.phtml
@@ -0,0 +1,57 @@
+
+
+
+
+
+
+
+
+db_exec($qs)) GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,0);
+
+for($i=0;$i<$DB->db_numrows($res);$i++) {
+ $row = $DB->db_fetch_array($res,$i,PGSQL_ASSOC);
+
+?>
+
+
+
+ [Recall]
+
+ [Delete]
+
+
+
+
+
+
+
diff --git a/admin/Contact/mailout.phtml b/admin/Contact/mailout.phtml
new file mode 100644
index 0000000..c87e197
--- /dev/null
+++ b/admin/Contact/mailout.phtml
@@ -0,0 +1,160 @@
+
+
+Mailing out The Newsletter
+
+
+db_exec($postmail)) {
+ html_error(DB_ERROR_MSG.__LINE__.$postmail, 1);
+}
+
+$mailqs = "SELECT
+ DISTINCT ON (email) email
+ FROM temp_table
+ GROUP BY email;";
+flush();
+if (!$mailres = $DB->db_exec($mailqs)) {
+ html_error(DB_ERROR_MSG.__LINE__.$mailqs, 1);
+}
+
+if ($DB->db_numrows($mailres)>0) {
+ for($a=0;$a<$DB->db_numrows($mailres);$a++) {
+ $mvdata = $DB->db_fetch_array($mailres, $a, PGSQL_ASSOC);
+ $email = trim($mvdata["email"]);
+ if ($email) {
+ $mail[] = $email;
+ }
+ }
+}
+if (is_array($mail) && count($mail)>0) {
+ // write the temp.to file
+ $mail = implode("\n", $mail);
+ $fp = fopen($ToFilename, "w");
+ fputs($fp, $mail, strlen($mail));
+ fclose($fp);
+} else {
+ $mail = "";
+}
+
+
+if ($mail != "") {
+ // I am changing this to a two part mime type email
+ // html and text
+ // using class_html
+ $responseqs = "SELECT *
+ FROM news_response
+ WHERE id = $mail_id";
+ if (!$resres = $DB->db_exec($responseqs)) {
+ html_error(DB_ERROR_MSG.$responseqs, 0);
+ }
+
+ $responserow = $DB->db_fetch_array($resres, 0, PGSQL_ASSOC);
+
+ $subject = trim($responserow['subject']);
+ $data['subject'] = &$subject;
+ $message = $responserow['response'];
+ // html part of email
+ //$data['response'] = stripslashes(nl2br($message));
+ $data['response'] = $message;
+ $data['url'] = MEDIA_BASE_URL;
+
+ $html = explode_template(NEWSLETTER_PROTOTYPE,$data);
+
+ // text part of email
+ $text = strip_tags($message);
+ $text .= "\n\n-------------------------------------------------------------------\n";
+ $text .= "You are receiving this message because you have expressed an interest in\n";
+ $text .= "receiving specials and information from ".SITENAME.". If you do not\n";
+ $text .= "wish to receive future items of this nature, please reply to this e-mail\n";
+ $text .= "with the word \"CANCEL\" on the subject line. You will then be removed \n";
+ $text .= "from future mailings.\n";
+ $text .= "-------------------------------------------------------------------\n";
+
+ // Write the temp.header file
+ $glm_headers = "NotifyAddr: ".OWNER_EMAIL."\n"
+ . "ProcessName: ".SITENAME."\n"
+ . "From: ".FROM_NEWS_EMAIL."\n"
+ . "ReportInterval: 2\n"
+ . "BlockSize: 1\n"
+ . "ProductionMode: ".PRODUCTION_MODE."\n";
+
+ $fp = fopen($HeadFilename, "w");
+ fputs($fp, $glm_headers, strlen($glm_headers));
+ fclose($fp);
+
+ $headers = "From: ".FROM_NEWS_EMAIL."\n".
+ "To: ".OWNER_EMAIL."\n".
+ "Subject: $subject\n".
+ "Reply-to: ".REPLY_TO."\n".
+ "Mime-Version: 1.0\n".
+ "Content-Type: multipart/alternative; boundary=ContentBoundry\n\n";
+ $fp = fopen($BodyFilename,"w");
+ if(HTML_EMAIL=="ON"){
+ $body_html = '--ContentBoundry
+Content-Type: text/plain; charset="UTF-8"
+'.$text.'
+--ContentBoundry
+Content-Type: text/html; charset="UTF-8"
+
+'.$html.'
+
+--ContentBoundry--';
+ fputs($fp, $headers, strlen($headers));
+ fputs($fp, $body_html, strlen($body_html));
+ } else {
+ fputs($fp, $headers, strlen($headers));
+ fputs($fp, $text, strlen($text));
+ }
+ fclose($fp);
+ // write the temp.ready file and your done!
+ $fp = fopen($ReadyFilename, "w");
+ fclose($fp);
+?>
+
+
+ Mail the current
+
+
+
+
+
+
+
+
+ You will recieve notification on the mailing task by email at .
+
+
+
+
+
+ Newsletter Not Sent!
+
+
+
+
+
diff --git a/admin/Contact/main.css b/admin/Contact/main.css
new file mode 100755
index 0000000..fef38df
--- /dev/null
+++ b/admin/Contact/main.css
@@ -0,0 +1,23 @@
+body {
+ background-color: #FFFFFF;
+}
+
+.navlink {
+ font-size: 80%;
+ font-family: arial;
+}
+
+td {
+ font-size: 80%;
+ font-family: arial,helvetica;
+}
+
+.theader {
+ font-size: 120%;
+ font-family: arial,helvetica;
+ color: #FFFFFF;
+}
+
+.theadertd {
+ background-color: #000080;
+}
diff --git a/admin/Contact/msg.js b/admin/Contact/msg.js
new file mode 100755
index 0000000..8ed837d
--- /dev/null
+++ b/admin/Contact/msg.js
@@ -0,0 +1,29 @@
+function glm_confirm(o) {
+ var p = o.msg.split("\n");
+ var k = 0;
+ for(i = 0;i < p.length;i++) {
+ if(k > p[i].length)
+ continue;
+ else
+ k = p[i].length;
+ }
+
+ var bound = "";
+ for(i = 0; i < k; i++) {
+ bound = bound+'_';
+ }
+ var str = bound+"\n\n"+o.msg+"\n\n"+bound+"\n\nAre You Sure?";
+ if(confirm(str)) {
+ if(o.popup == '1') {
+ var nw = new Object();
+ nw.url = o.url;
+ nw.name = o.popup.name;
+ nw.width = o.width;
+ nw.height = o.height;
+ glm_open(nw);
+ }
+ else {
+ location.replace(o.url);
+ }
+ }
+}
diff --git a/admin/Contact/newsletter_template.html b/admin/Contact/newsletter_template.html
new file mode 100755
index 0000000..9a145a7
--- /dev/null
+++ b/admin/Contact/newsletter_template.html
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/admin/Contact/notes/ChangeLog b/admin/Contact/notes/ChangeLog
new file mode 100755
index 0000000..fc6c567
--- /dev/null
+++ b/admin/Contact/notes/ChangeLog
@@ -0,0 +1,327 @@
+2002-05-07 13:47 matrix
+
+ * contact_setup.inc, del_query.phtml, download.phtml,
+ edit_contact.phtml, form.js, index.phtml, list_contact.phtml,
+ list_query.phtml, mailout.phtml, main.css, msg.js,
+ query_contact.phtml, query_db.phtml, query_save.phtml,
+ update_contact.phtml, verify.js, wm.js, help/contact.phtml,
+ notes/ChangeLog, notes/Contact, notes/adm2.sql, notes/contact.sql,
+ notes/guest.sql: "version 2.4"
+
+2002-05-07 13:45 matrix
+
+ * contact.sql, contact_setup.inc, edit_contact.phtml,
+ list_contact.phtml, update_contact.phtml, notes/ChangeLog,
+ notes/contact.sql, notes/Contact: adding ChangeLog file and moving
+ sql file into notes. I have also set the insert part of
+ update_contact.phtml to use nextval to generate the PRIMEKEY so
+ this will work with previous version of th shop which don't have
+ the default set on cust_id
+
+2002-05-07 11:14 matrix
+
+ * contact.sql, contact_setup.inc, del_query.phtml, download.phtml,
+ edit_contact.phtml, form.js, index.phtml, list_contact.phtml,
+ list_query.phtml, mailout.phtml, main.css, msg.js,
+ query_contact.phtml, query_db.phtml, query_save.phtml,
+ update_contact.phtml, verify.js, wm.js, help/contact.phtml,
+ notes/adm2.sql, notes/guest.sql: testing out both contact and
+ customer table use
+
+2002-05-07 10:08 matrix
+
+ * form.js, msg.js, verify.js, wm.js: "putting javascript files in
+ dir"
+
+2002-05-07 09:57 matrix
+
+ * index.phtml: "all versions now 2.0"
+
+2002-05-07 09:57 matrix
+
+ * index.phtml: new file
+
+2002-05-07 09:44 matrix
+
+ * admin_constants.inc, contact.phtml, contact.sql,
+ contact_setup.inc, contact_test.sql, del_query.phtml,
+ download.phtml, edit_contact.phtml, index.html, list_contact.phtml,
+ list_cust_form.phtml, list_customers.phtml, list_query.phtml,
+ mailout.phtml, main.css, path.phtml, query_contact.phtml,
+ query_db.phtml, query_save.phtml, shopping_cart_setup.inc,
+ update_contact.phtml, help/contact.phtml, notes/adm2.sql,
+ notes/guest.sql: "merging final changes into one app"
+
+2002-03-14 11:23 matrix
+
+ * download.phtml: removed offending dot
+
+2002-03-12 10:32 matrix
+
+ * contact_setup.inc: file contact_setup.inc was initially added on
+ branch glm-Contact-2-0.
+
+2002-03-12 10:32 matrix
+
+ * download.phtml: file download.phtml was initially added on branch
+ glm-Contact-2-0.
+
+2002-03-12 10:32 matrix
+
+ * contact.phtml, contact_setup.inc, del_query.phtml,
+ download.phtml, edit_contact.phtml, list_contact.phtml,
+ list_query.phtml, mailout.phtml, query_contact.phtml,
+ query_db.phtml, update_contact.phtml: make it customer and ocntact
+
+2002-03-12 09:36 matrix
+
+ * list_cust_form.phtml, list_customers.phtml, path.phtml,
+ shopping_cart_setup.inc: updates
+
+2002-03-12 09:34 matrix
+
+ * contact.phtml, del_query.phtml, edit_contact.phtml,
+ list_contact.phtml, list_query.phtml, query_contact.phtml,
+ query_db.phtml, update_contact.phtml: prepare for merging
+
+2001-12-17 10:13 matrix
+
+ * list_contact.phtml, mailout.phtml: added ID
+
+2001-12-17 10:02 matrix
+
+ * list_contact.phtml, mailout.phtml: mail can't be sent by url
+
+2001-11-27 16:50 matrix
+
+ * contact.phtml, del_query.phtml, edit_contact.phtml,
+ list_contact.phtml, list_query.phtml, query_contact.phtml,
+ query_db.phtml, query_save.phtml, update_contact.phtml: needed to
+ update adding contacts to customer table as there is no default
+ value for cust_id
+
+2001-11-21 14:07 matrix
+
+ * contact.phtml, del_query.phtml, edit_contact.phtml,
+ list_contact.phtml, list_query.phtml, path.phtml,
+ query_contact.phtml, query_db.phtml, update_contact.phtml: using
+ setup.phtml not path.phtml
+
+2001-11-07 14:30 matrix
+
+ * list_contact.phtml: removed echo
+
+2001-11-07 14:27 matrix
+
+ * contact.phtml, del_query.phtml, edit_contact.phtml,
+ list_query.phtml, mailout.phtml, path.phtml, query_contact.phtml,
+ query_db.phtml, update_contact.phtml: updatng now using setup.phtml
+
+2001-11-07 14:24 matrix
+
+ * list_contact.phtml: correcting email out code
+
+2001-10-15 15:19 matrix
+
+ * contact.phtml, query_contact.phtml: adding date search
+
+2001-10-11 14:44 matrix
+
+ * list_contact.phtml: updating
+
+2001-10-11 14:34 matrix
+
+ * mailout.phtml: file mailout.phtml was initially added on branch
+ glm-Contact-2-0.
+
+2001-10-11 14:32 matrix
+
+ * list_contact.phtml, mailout.phtml: added autoresponder
+
+2001-09-25 10:14 matrix
+
+ * path.phtml: changed the path so we use one file
+
+2001-09-25 10:13 matrix
+
+ * contact.phtml: tr tag
+
+2001-07-02 14:29 matrix
+
+ * path.phtml: symplified the path files now this referes to the
+ main one in admin
+
+2001-06-22 08:55 matrix
+
+ * contact.phtml, contact.sql, edit_contact.phtml,
+ update_contact.phtml: adding field referred_by
+
+2001-06-19 08:50 matrix
+
+ * list_contact.phtml: no real change
+
+2001-06-19 08:49 matrix
+
+ * update_contact.phtml, edit_contact.phtml: modified for mailok
+
+2001-06-19 08:45 matrix
+
+ * list_contact.phtml: modified for errors on recalls
+
+2001-06-19 08:45 matrix
+
+ * edit_contact.phtml, update_contact.phtml: modified for mailok
+
+2001-06-18 10:08 matrix
+
+ * query_db.phtml: shop_query_db
+
+2001-06-18 10:08 matrix
+
+ * help/helpbg.gif: file helpbg.gif was initially added on branch
+ glm-Contact-shop-1-0.
+
+2001-06-18 10:08 matrix
+
+ * help/: closewindow.gif, contact.phtml, helpbg.gif: added images
+ to help folder
+
+2001-06-18 10:08 matrix
+
+ * help/closewindow.gif: file closewindow.gif was initially added on
+ branch glm-Contact-shop-1-0.
+
+2001-06-18 10:05 matrix
+
+ * query_contact.phtml: shop_query_db
+
+2001-06-18 10:04 matrix
+
+ * list_query.phtml: added nav links
+
+2001-06-18 10:03 matrix
+
+ * list_query.phtml: new shop query db
+
+2001-06-11 13:14 matrix
+
+ * list_contact.phtml: error correction
+
+2001-06-11 10:51 matrix
+
+ * list_contact.phtml: if there are no queries insert current
+
+2001-06-11 10:31 matrix
+
+ * list_contact.phtml: if there are no contacts html_error
+
+2001-06-11 10:18 matrix
+
+ * list_query.phtml: added nav to top of page
+
+2001-06-11 10:15 matrix
+
+ * help/contact.phtml: corrected paths to help images
+
+2001-06-08 09:17 matrix
+
+ * contact.sql: changing query table name to keep from messing up
+ other application
+
+2001-06-08 09:16 matrix
+
+ * help/contact.phtml: updateing help file
+
+2001-06-08 09:12 matrix
+
+ * contact.phtml: changed radio buttons on mail_ok to drop down
+
+2001-06-08 08:50 matrix
+
+ * list_contact.phtml: modified
+
+2001-06-08 08:46 matrix
+
+ * contact.phtml: made the mail_ok a drop down
+
+2001-06-07 14:54 matrix
+
+ * contact.phtml, list_contact.phtml, query_contact.phtml: updated
+ per gloriebe contactdb
+
+2001-06-07 14:06 matrix
+
+ * query_contact.phtml, help/contact.phtml: made changes for ereg
+ wildcards
+
+2001-06-06 15:51 matrix
+
+ * contact.phtml, contact.sql, edit_contact.phtml,
+ list_contact.phtml, query_contact.phtml, query_save.phtml,
+ update_contact.phtml: shop version
+
+2001-06-06 15:42 matrix
+
+ * main.css: added file
+
+2001-06-06 15:40 matrix
+
+ * report.rpt: "removed"
+
+2001-06-06 15:00 matrix
+
+ * contact.phtml, list_contact.phtml, query_contact.phtml,
+ update_contact.phtml, help/contact.phtml: worked out some bugs
+
+2001-06-06 13:41 matrix
+
+ * help/contact.phtml: changed path on images
+
+2001-06-06 13:38 matrix
+
+ * main.css: adding needed files
+
+2001-06-06 13:38 matrix
+
+ * main.css: file main.css was initially added on branch
+ glm-Contact-2-0.
+
+2001-06-05 11:17 matrix
+
+ * path.phtml: changed path to help
+
+2001-06-05 11:13 matrix
+
+ * path.phtml: changed path to help
+
+2001-06-05 10:45 matrix
+
+ * path.phtml: added path file
+
+2001-06-05 10:38 matrix
+
+ * contact.phtml, list_contact.phtml, query_contact.phtml: added
+ pipe and csv delimiter
+
+2001-05-31 12:43 matrix
+
+ * contact.phtml, contact.sql, contact_test.sql, del_query.phtml,
+ edit_contact.phtml, list_contact.phtml, list_query.phtml,
+ query_contact.phtml, query_db.phtml, query_save.phtml,
+ update_contact.phtml, help/contact.phtml: combining the contact
+ databases
+
+2001-04-04 13:42 matrix
+
+ * admin_constants.inc, index.html, list_cust_form.phtml,
+ list_customers.phtml, path.phtml, report.rpt,
+ shopping_cart_setup.inc, notes/adm2.sql, notes/guest.sql: Initial
+ revision
+
+2001-04-04 13:42 matrix
+
+ * admin_constants.inc, index.html, list_cust_form.phtml,
+ list_customers.phtml, path.phtml, report.rpt,
+ shopping_cart_setup.inc, notes/adm2.sql, notes/guest.sql: imported
+ sources
+
diff --git a/admin/Contact/notes/Contact b/admin/Contact/notes/Contact
new file mode 100755
index 0000000..937f46f
--- /dev/null
+++ b/admin/Contact/notes/Contact
@@ -0,0 +1,4 @@
+All application setup stuff will be in contact_setup.phtml
+1) right now if you add to the $fields array you'll still have to change
+ edit_contact.phtml and update_contact.phtml
+2) contact.sql - contains the query to build the contact table and query_db table
diff --git a/admin/Contact/notes/contact.sql b/admin/Contact/notes/contact.sql
new file mode 100755
index 0000000..4fd960b
--- /dev/null
+++ b/admin/Contact/notes/contact.sql
@@ -0,0 +1,100 @@
+\connect - postgres
+
+CREATE TABLE "contact" (
+ "id" SERIAL PRIMARY KEY,
+ "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 'f',
+ "contact_type" text
+);
+
+REVOKE ALL on "contact" from PUBLIC;
+GRANT ALL on "contact" to "nobody";
+GRANT ALL on "contact" to "postgres";
+
+REVOKE ALL on "contact_id_seq" from PUBLIC;
+GRANT ALL on "contact_id_seq" to "nobody";
+GRANT ALL on "contact_id_seq" to "postgres";
+
+CREATE TABLE "query_db" (
+ "id" SERIAL PRIMARY KEY,
+ "query_name" text,
+ "query" text,
+ "file" text,
+ "delimiter" text
+);
+
+REVOKE ALL on "query_db" from PUBLIC;
+GRANT ALL on "query_db" to "nobody";
+GRANT ALL on "query_db" to "postgres";
+
+REVOKE ALL on "query_db_id_seq" from PUBLIC;
+GRANT ALL on "query_db_id_seq" to "nobody";
+GRANT ALL on "query_db_id_seq" to "postgres";
+
+CREATE TABLE "news_response" (
+ "id" SERIAL PRIMARY KEY,
+ "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
+);
+
+REVOKE ALL on "news_response" from PUBLIC;
+GRANT ALL on "news_response" to "postgres";
+GRANT ALL on "news_response" to "nobody";
+GRANT ALL on "news_response_id_seq" to "nobody";
+
+INSERT INTO news_response (subject,response) values ('subject','response');
+
+CREATE UNIQUE INDEX contact_id_indx ON contact(id);
+CREATE INDEX contact_email_indx ON contact(email);
+CREATE INDEX contact_fname_indx ON contact(fname);
+CREATE INDEX contact_lname_indx ON contact(lname);
+CREATE INDEX contact_create_date_indx ON contact(create_date);
+CREATE UNIQUE INDEX news_response_id_indx ON contact(id);
+CREATE UNIQUE INDEX query_db_id_indx ON contact(id);
+
+CREATE TABLE contact_inq (
+ id serial NOT NULL,
+ header text,
+ pos integer,
+ description text,
+ image text,
+ groupid integer
+);
+REVOKE ALL ON TABLE contact_inq FROM PUBLIC;
+GRANT ALL ON TABLE contact_inq TO nobody;
+REVOKE ALL ON TABLE contact_inq_id_seq FROM PUBLIC;
+GRANT ALL ON TABLE contact_inq_id_seq TO nobody;
+ALTER TABLE ONLY contact_inq
+ ADD CONSTRAINT contact_inq_pkey PRIMARY KEY (id);
+
+CREATE TABLE inq_group (
+ id SERIAL PRIMARY KEY,
+ name text
+);
+GRANT ALL ON inq_group TO nobody;
+GRANT ALL ON inq_group_id_seq TO nobody;
+
+INSERT INTO inq_group (name) VALUES ('Areas of Interest');
diff --git a/admin/Contact/preview.phtml b/admin/Contact/preview.phtml
new file mode 100755
index 0000000..aec6264
--- /dev/null
+++ b/admin/Contact/preview.phtml
@@ -0,0 +1,14 @@
+db_auto_get_data($query);
+$data['url'] = MEDIA_BASE_URL;
+$data['subject'] = $res[0]["subject"];
+$response = $res[0]["response"];
+$data['response'] = $response;
+
+$page = GLM_TOOLBOX::explode_template(NEWSLETTER_PROTOTYPE,$data);
+echo $page;
+?>
diff --git a/admin/Contact/query_contact.phtml b/admin/Contact/query_contact.phtml
new file mode 100755
index 0000000..2513a03
--- /dev/null
+++ b/admin/Contact/query_contact.phtml
@@ -0,0 +1,425 @@
+$value){
+ if ($value == ""){
+ unset($array[$counter]);
+ }
+ $counter++;
+ }
+ }
+}
+$sess_vars = $_POST;
+$_SESSION['sess_vars'] = $sess_vars;
+$query_no = filter_var($_REQUEST['query_no'], FILTER_VALIDATE_INT);
+if (!$query_no) {
+ /* The fields array is sent as a string
+ explode it out using : as delimiter */
+ $fvalue = preg_replace("/^:/","",$fvalue);
+ $fields = explode(":",$fvalue);
+ $rfvalue = preg_replace("/^:/","",$rfvalue);
+ $return_fields = explode(":",$rfvalue);
+ $dates = preg_replace("/^:/","",$rdvalue);
+ $dates = explode(":",$dates);
+
+ clean_array($return_fields);
+ clean_array($dates);
+ if (!isset($search)) {
+ header("Location: index.phtml");
+ }
+ /* Chop off whitespaces spaces */
+ $search = chop(trim($search));
+ $search = preg_replace("/\\\|\"/", "", $search);
+ if (!$search && (count ($fields) == 1 && $fields[0] == '')) {
+ $ALL = TRUE;
+ }
+
+ function getKeywords($keywords) {
+ /* Replace the whitespace with a , */
+ $keywords = str_replace(" ",",",$keywords);
+ $keywords = str_replace(",,",",",$keywords);
+ $seperated = explode(",",$keywords);
+ /* Return exploded string */
+ return $seperated;
+ }
+
+ switch($search_type) {
+ case "1":
+ $keywords = $search;
+ $compare = "OR";
+ break;
+
+ case "2":
+ $keywords = getKeywords($search);
+ $compare = "AND";
+ break;
+
+ case "3":
+ $keywords = getKeywords($search);
+ $compare = "OR";
+ break;
+
+ case "4":
+ $keywords = getKeywords($search);
+ $compare = "AND";
+ $NOT = TRUE;
+ break;
+
+ default:
+ echo "not valid";
+ break;
+ }
+
+ if (is_array($keywords)) {
+ for ($rip=0;$rip $bool_val) {
+ if ($_POST[$bool_key] == "1") {
+ $bstring[] = " $bool_key = 't'";
+ } elseif ($_POST[$bool_key] == "0") {
+ $bstring[] = " $bool_key = 'f'";
+ }
+ }
+ if (is_array($bstring)) {
+ $query_string .= ' and ('.implode(" $compare ",$bstring) .') ';
+ }
+ }
+ if( is_array( $dropdowns ) ) {
+ foreach( $dropdowns as $drop_key => $drop_val ) {
+ if( is_array( $_POST[$drop_key] ) ) {
+ foreach( $_POST[$drop_key] as $mdrop_key => $mdrop_val ){
+ if( $mdrop_val != '' ){
+ $dstring[] = " $drop_key $operator ':".$mdrop_val.":'";
+ }
+ }
+ }elseif( !is_array( $_POST[$drop_key] ) ) {
+ if( $_POST[$drop_key] != '' ){
+ $dstring[] = " $drop_key = '".$_POST[$drop_key]."'";
+ }
+ }
+ }
+ if( is_array($dstring) ) {
+ $query_string .= ' and ('.implode(" $compare ",$dstring).' ) ';
+ }
+ }
+ if (is_array ($cols) ) {
+ foreach ($cols as $ikey => $ival) {
+ $cstring[] = " interest $operator ':$ival:'";
+ }
+ if (is_array($cstring)) {
+ $query_string .= ' and ('.implode(" $compare ",$cstring).') ';
+ }
+ }
+ if (isset($fp_month)) {
+ $fp_str = mktime(0,0,0,$fp_month,$fp_day,$fp_year);
+ $tp_str = mktime(0,0,0,$tp_month,$tp_day,$tp_year);
+ $fa_str = mktime(0,0,0,$fa_month,$fa_day,$fa_year);
+ $ta_str = mktime(0,0,0,$ta_month,$ta_day,$ta_year);
+
+ if ($fp_str<$tp_str) {
+ $fp_date = $fp_month."/".$fp_day."/".$fp_year;
+ $tp_date = $tp_month."/".$tp_day."/".$tp_year;
+ $query_string .= " AND purch_date >= '$fp_date'
+ AND purch_date <= '$tp_date'";
+ }
+ if ($fa_str<$ta_str) {
+ $fa_date = $fa_month."/".$fa_day."/".$fa_year;
+ $ta_date = $ta_month."/".$ta_day."/".$ta_year;
+ $query_string .= " AND access_date >= '$fa_date'
+ AND access_date <= '$ta_date'";
+ }
+ if ($fp_str>$tp_str) {
+ $fp_date = $fp_month."/".$fp_day."/".$fp_year;
+ $tp_date = $tp_month."/".$tp_day."/".$tp_year;
+ $query_string .= " AND purch_date <= '$tp_date'";
+ }
+ if ($fa_str>$ta_str) {
+ $fa_date = $fa_month."/".$fa_day."/".$fa_year;
+ $ta_date = $ta_month."/".$ta_day."/".$ta_year;
+ $query_string .= " AND access_date <= '$ta_date'";
+ }
+ }
+ if (isset($fc_month)) {
+ $fc_str = mktime(0,0,0,$fc_month,$fc_day,$fc_year);
+ $tc_str = mktime(0,0,0,$tc_month,$tc_day,$tc_year);
+
+ if ($fc_str<$tc_str) {
+ $fc_date = $fc_month."/".$fc_day."/".$fc_year;
+ $tc_date = $tc_month."/".$tc_day."/".$tc_year;
+ $query_string .= " AND create_date >= '$fc_date'
+ AND create_date <= '$tc_date'";
+ }
+ if ($fc_str>$tc_str) {
+ $fc_date = $fc_month."/".$fc_day."/".$fc_year;
+ $tc_date = $tc_month."/".$tc_day."/".$tc_year;
+ $query_string .= " AND create_date <= '$tc_date'";
+ }
+ }
+} else {
+ $sql = "
+ SELECT query_name,query,delimiter,file
+ FROM query_db
+ WHERE id = $query_no";
+ $stmt = $DB->dbh->query($sql);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $query_name = $row['query_name'];
+ $file = $row['file'];
+ $delimiter = $row['delimiter'];
+ $query_string = $row['query'];
+ //var_dump($query_string);
+ //exit;
+}
+/* Thought the customer would like to see what's in the query */
+$showq = str_replace("SELECT","Return\n",$query_string);
+$showq = str_replace ("\nFROM\t".TABLE." \nWHERE\t".WHERE."\nAND\t",
+" \nfrom the contact database \nwhere ",$showq);
+$showq = str_replace ("\nFROM\t".TABLE." \nWHERE\t".WHERE."\n",
+" \nfrom the contact database",$showq);
+$showq = str_replace("fname","first name",$showq);
+$showq = str_replace("cust_id,","",$showq);
+$showq = str_replace("lname","last name",$showq);
+$showq = str_replace("!~*","does not contain",$showq);
+$showq = str_replace("!~","does not contain",$showq);
+$showq = str_replace("~*","contains",$showq);
+$showq = str_replace("~","is in",$showq);
+$showq = str_replace("does not contain '^"," does not start with ",$showq);
+$showq = str_replace("contains '^"," starts with ",$showq);
+$showq = str_replace("is in '^"," starts with ",$showq);
+$showq = str_replace("$"," in the ending ",$showq);
+$showq = str_replace("OR","or",$showq);
+$showq = str_replace("AND","and",$showq);
+$showq = str_replace("'","",$showq);
+if (!$ALL) {
+ if ($case == "OFF") {
+ $showq .= "\n(case insensitive match)";
+ } else {
+ $showq .= "\n(case sensitive match)";
+ }
+}
+if (isset($file) && $file != "") {
+ $showq .= "\noutput 1 file in ";
+ if ($file == "rpt") {
+ $showq .= "text";
+ }elseif ($file == "gz") {
+ $showq .= "tar ball";
+ }else {
+ $showq .= "zip";
+ }
+ if ($delimiter == "csv") {
+ $showq .= " format using ".$delimiter;
+ } else {
+ $showq .= " format using ".$delimiter." as delimiter";
+ }
+}
+$showq .= ".";
+$query = $query_string;
+
+GLM_TOOLBOX::top("QUERY BUILDER PAGE","");
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+?>
+
+
+
+
+
+
+
+db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,0);
+}
+
+if (!$row = $DB->db_fetch_array($res,0,PGSQL_ASSOC)) {
+ $sql = "
+ INSERT INTO query_db
+ (query_name, query, file, delimiter)
+ VALUES
+ (:query_name, :query, :file, :delimiter)";
+} else {
+ $rowId = $row['id'];
+ $sql = "
+ UPDATE query_db
+ SET query = :query,
+ file = :file,
+ delimiter = :delimiter
+ WHERE id = :id";
+}
+// save query
+$stmt = $DB->dbh->prepare($sql);
+$stmt->bindParam(':query', $query);
+$stmt->bindParam(':file', $file);
+$stmt->bindParam(':delimiter', $delimiter);
+if ($rowId) {
+ $stmt->bindParam(':id', $rowId);
+}
+$stmt->execute();
+if (!$DB->db_auto_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,0);
+}
+GLM_TOOLBOX::footer();
+?>
diff --git a/admin/Contact/query_db.phtml b/admin/Contact/query_db.phtml
new file mode 100755
index 0000000..97f9371
--- /dev/null
+++ b/admin/Contact/query_db.phtml
@@ -0,0 +1,19 @@
+db_auto_exec($qs))
+ {
+ html_error(DB_ERROR_MSG.$qs,1);
+ }
+GLM_TOOLBOX::html_header("Saving Query","Saved","");
+?>
+Query is saved as
+Close This
+Window
diff --git a/admin/Contact/query_save.phtml b/admin/Contact/query_save.phtml
new file mode 100755
index 0000000..596720c
--- /dev/null
+++ b/admin/Contact/query_save.phtml
@@ -0,0 +1,18 @@
+
+
+
+
+
diff --git a/admin/Contact/update_autoresponse.phtml b/admin/Contact/update_autoresponse.phtml
new file mode 100755
index 0000000..4c2578e
--- /dev/null
+++ b/admin/Contact/update_autoresponse.phtml
@@ -0,0 +1,82 @@
+prepare($sql);
+ $update->bindParam(
+ ':subject',
+ stripslashes($subject),
+ PDO::PARAM_STR
+ );
+ $update->bindParam(
+ ':response',
+ stripslashes($response),
+ PDO::PARAM_STR
+ );
+ $update->bindParam(
+ ':id',
+ $id,
+ PDO::PARAM_INT
+ );
+ $update->execute();
+ break;// }}}
+
+case "Insert":// {{{
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ INSERT INTO news_response
+ (last_update,subject,response)
+ VALUES
+ (current_date,:subject,:response)";
+ $insert = $dbh->prepare($sql);
+ $insert->bindParam(
+ ':subject',
+ stripslashes($subject),
+ PDO::PARAM_STR
+ );
+ $insert->bindParam(
+ ':response',
+ stripslashes($response),
+ PDO::PARAM_STR
+ );
+ $insert->execute();
+ $location = "emails.php";
+
+ break;// }}}
+
+case "Cancel":// {{{
+ $location = "emails.php";
+ break;// }}}
+
+case "Delete":// {{{
+ $query = "
+ DELETE FROM news_response
+ WHERE id = $id;";
+ $DB->db_exec( $query );
+ $location = "emails.php";
+ break;// }}}
+
+default:// {{{
+ GLM_TOOLBOX::html_error("incorrect value for Command",1);
+ break;// }}}
+}
+
+header("Location: $location");
+?>
diff --git a/admin/Contact/update_contact.phtml b/admin/Contact/update_contact.phtml
new file mode 100755
index 0000000..a6c1ee0
--- /dev/null
+++ b/admin/Contact/update_contact.phtml
@@ -0,0 +1,39 @@
+db_auto_exec($qs)) {
+ $ERRORS .= pg_errormessage($dbd).$qs;
+ }
+ $location .= '&Action=Contact+Deleted';
+
+ break;
+
+ case "Cancel":
+ break;
+
+ default:
+ $ERRORS .= "incorrect value for Command";
+ break;
+
+ }
+
+ header("Location: $location");
+}
+?>
diff --git a/admin/Contact/update_inquiry.phtml b/admin/Contact/update_inquiry.phtml
new file mode 100755
index 0000000..975673a
--- /dev/null
+++ b/admin/Contact/update_inquiry.phtml
@@ -0,0 +1,118 @@
+db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+ }
+ $data = $DB->db_fetch_array($result, 0, PGSQL_ASSOC);
+ $pos = $data['pos'];
+ if ($newpos < $pos) {
+ $qs = "select id,pos from contact_inq where pos < $pos and pos >= $newpos and groupid = $groupid order by pos";
+ if(!$res = $DB->db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+ }
+ $counter = ($newpos + 1);
+ $totalNum = $DB->db_numrows($res);
+ for ($i = 0;$i < $totalNum; $i++) {
+ $res_data = $DB->db_fetch_array($res, $i, PGSQL_ASSOC);
+ $res_id = $res_data['id'];
+ $res_pos = $res_data['pos'];
+ $qs = "update contact_inq set pos = $counter where id = $res_id";
+ if (!$DB->db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+ }
+ $counter++;
+ }
+ } else {
+ $qs = "select pos,id from contact_inq where pos > $pos and pos <= $newpos and groupid = $groupid order by pos";
+ if (!$res = $DB->db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+ }
+ $counter = ($pos);
+ $totalNum = $DB->db_numrows($res);
+ for ( $i = 0; $i < $totalNum; $i++) {
+ $res_data = $DB->db_fetch_array($res, $i, PGSQL_ASSOC);
+ $res_id = $res_data['id'];
+ $res_pos = $res_data['pos'];
+ $qs = "update contact_inq set pos = $counter where id = $res_id";
+ if (!$DB->db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+ }
+ $counter++;
+ }
+ }
+ $qs = "update contact_inq set pos = $newpos where id = $id";
+ if (!$DB->db_exec($qs)) {
+ GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+ }
+ break;
+
+case "Edit":
+ if ($_POST['new_group']) {
+ $query = "select id from inq_group where name = '".$_POST['new_group']."'";
+ if ($newData = $DB->db_auto_get_data($query)) {
+ // already exists use the id returned
+ $groupid = $newData[0]['id'];
+ } else {
+ $query = "
+ INSERT INTO inq_group
+ (name)
+ VALUES
+ ('{$_POST['new_group']}')
+ RETURNING id";
+ if ($newData = $DB->db_auto_get_data($query)) {
+ $groupid = $newData[0]['id'];
+ }
+ }
+ }
+ $qs = "update contact_inq set header = '$header',image = '$image_name',description = '$description',groupid = $groupid where id = $id;";
+ $DB->db_exec($qs);
+ break;
+
+case "Add":
+ if ($_POST['new_group']) {
+ $query = "select id from inq_group where name = '".$_POST['new_group']."'";
+ if ($newData = $DB->db_auto_get_data($query)) {
+ // already exists use the id returned
+ $groupid = $newData[0]['id'];
+ } else {
+ $query = "
+ INSERT INTO inq_group
+ (name)
+ VALUES
+ ('{$_POST['new_group']}')
+ RETURNING id";
+ if ($newData = $DB->db_auto_get_data($query)) {
+ $groupid = $newData[0]['id'];
+ }
+ }
+ }
+ $qs = "select MAX(pos) as maxpos from contact_inq where groupid = $groupid";
+ $res = $DB->db_exec($qs);
+ $row = $DB->db_fetch_array($res,0,PGSQL_ASSOC);
+ $nextpos = $row[maxpos];
+ $nextpos++;
+ $qs = "insert into contact_inq (header,description,image,pos,groupid) values ('$header','$description','$image_name',$nextpos,$groupid);";
+ $DB->db_exec($qs);
+ break;
+
+case "Delete":
+ $qs = "delete from contact_inq where id = $id";
+ $DB->db_exec($qs);
+ if ($_REQUEST['old_groupid']) {
+ $qs = "select pos,id from contact_inq where pos > $oldpos and groupid = $old_groupid order by pos";
+ $res = $DB->db_exec($qs);
+ $oldcatid_counter = $oldpos;
+ $totalNum = $DB->db_numrows($res);
+ for ($i = 0; $i < $totalNum; $i++) {
+ $row = $DB->db_fetch_array($res, $i, PGSQL_ASSOC);
+ $qs = "update contact_inq set pos = $oldcatid_counter where id = $row[id]";
+ }
+ $DB->db_exec($qs);
+ }
+ break;
+}
+header("Location: contact_inquiry.phtml");
diff --git a/admin/Contact/verify.js b/admin/Contact/verify.js
new file mode 100755
index 0000000..a254639
--- /dev/null
+++ b/admin/Contact/verify.js
@@ -0,0 +1,72 @@
+function isblank(s) {
+ for(var i = 0; i < s.length; i++) {
+ var c = s.charAt(i);
+ if((c != ' ') && (c != '\n') && (c != '\t'))
+ return(false);
+ }
+ return(true);
+}
+
+function verify(f) {
+ var msg;
+ var empty_fields = "";
+ var errors = "";
+
+ for(var i = 0; i < f.length; i++) {
+ var e = f.elements[i];
+ if(((e.type == "text") || (e.type == "textarea")) && !e.optional) {
+ if((e.value == null) || (e.value == "") || isblank(e.value)) {
+ empty_fields += "\n " + e.r;
+ continue;
+ }
+
+ if(e.d) {
+ if(isNaN(Date.parse(e.value)))
+ errors += "- The field " +e.r+" must be formated like 01/17/2001\n";
+ }
+ if(e.numeric || (e.min != null) || (e.max != null)) {
+ if(e.i) {
+ var v = parseInt(e.value);
+ if(v != e.value) {
+ errors += "- The field " +e.r + " must be a ";
+ errors += "number with no decimal\n";
+ continue;
+ }
+ }
+ else
+ var v = parseFloat(e.value);
+ if(isNaN(v) ||
+ ((e.min != null) && (v < e.min)) ||
+ ((e.max != null) && (v > e.max))) {
+
+ errors += "- The field " + e.r + " must be a number";
+ if(e.min != null)
+ errors += " that is greater than " + e.min;
+ if(e.max != null && e.min != null)
+ errors += " and less than " + e.max;
+ else if (e.max != null)
+ errors += " that is less than " + e.max;
+ errors += ".\n";
+ }
+ }
+ }
+ }
+
+ if(!empty_fields && !errors)
+ return(true);
+
+ msg = "_____________________________________________________\n\n";
+ msg +="The form was not submitted because of the following error(s).\n";
+ msg +="Please correct these error(s) and re-submit.\n";
+ msg +="_____________________________________________________\n\n";
+
+ if(empty_fields) {
+ msg += "- The following required field(s) are empty:"
+ + empty_fields + "\n";
+ if(errors)
+ msg += "\n";
+ }
+ msg += errors;
+ alert(msg);
+ return(false);
+}
diff --git a/admin/Contact/view_newsletter.phtml b/admin/Contact/view_newsletter.phtml
new file mode 100755
index 0000000..1c13387
--- /dev/null
+++ b/admin/Contact/view_newsletter.phtml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
';
+
+GLM_TOOLBOX::footer();
+?>
diff --git a/admin/Contact/wm.js b/admin/Contact/wm.js
new file mode 100755
index 0000000..7a7323e
--- /dev/null
+++ b/admin/Contact/wm.js
@@ -0,0 +1,13 @@
+function glm_open(o) {
+ var x = (screen.width/2) - (o.width/2);
+ var y = (screen.height/2) - (o.height/2);
+ var args = "width="+o.width+",height="+o.height+",screenX="+x+",screenY="+y+",top="+y+",left="+x;
+ if(o.scroll == true)
+ args += ",scrollbars=1";
+ //args += "\'";
+ //alert(args);
+ pow=window.open(o.url,o.name,args);
+ //confirm(args);
+ if (pow.opener == null)
+ pow.opener = self;
+}
diff --git a/admin/index.phtml b/admin/index.phtml
new file mode 100755
index 0000000..708d02e
--- /dev/null
+++ b/admin/index.phtml
@@ -0,0 +1,31 @@
+
+
+
+
+ Administration
+
+
+
+
+
+
+ Admin Requires Frames Capable Browser
+ You can get a Standard Compliant browser from:
+
+
+
+
diff --git a/admin/main.css b/admin/main.css
new file mode 100755
index 0000000..e3346d5
--- /dev/null
+++ b/admin/main.css
@@ -0,0 +1,132 @@
+body {
+ padding-left: 50px;
+ font-family: arial, helvetica, sans-serif;
+ font-size: 12px;
+ }
+.clearer {
+ height:1px;
+ overflow:hidden;
+ margin-top:-1px;
+ clear:left;
+}
+h1 {font-size: 18px; color: #777;}
+form {margin: 0; padding: 0;}
+/* TOOLBOX NAV */
+ul#toolbox {list-style-position:inside;list-style-type:circle;}
+ul#toolbox li {list-style-type:circle}
+ul#toolbox li.toolboxArrow {list-style-type:none;padding-left:0;margin-left:-7px;}
+* html ul#toolbox li.toolboxArrow {margin-left:-20px;} /*style for IE*/
+/* APP Nav*/
+ul.admin_nav
+{
+margin: 0;
+list-style-type: none;
+padding: 5px 0;
+}
+ul.admin_nav li { display: inline; }
+ul.admin_nav li a
+{
+border-top: 1px solid #eee;
+border-right: 1px solid #ccc;
+border-bottom: 1px solid #ccc;
+border-left: 1px solid #eee;
+text-decoration: none;
+background-color: #ddd;
+color: #000;
+padding: 2px 6px;
+margin: 0 1px;
+font-weight: bold;
+font-size: 12px;
+}
+ul.admin_nav.current { color: #111 }
+#admin-list-table {clear:left;width:500px;}
+#admin-list-table td {
+ border: 2px solid #ccc;
+ border-collapse: collapse;
+ background: #eee;
+ padding: 4px;}
+/*#admin-list-table img {border: 0; text-align: center; margin: 0 auto; display: block;}*/
+#admin-list-table a:link {color: #666;}
+#admin-list-table a:visited {color: #666;}
+#admin-list-table a:active {color: #666;}
+#admin-list-table a:hover {color: #000;}
+
+/*event-edit-table */
+#admin-edit-table {
+ clear:left;
+ font-family: arial, helvetica, sans-serif;
+ border: 2px solid #ccc;
+ border-collapse: collapse;
+ font-size: 12px;
+ }
+#admin-edit-table td {
+ border: 2px solid #ccc;
+ border-collapse: collapse;
+ background: #eee; padding: 4px;}
+#admin-list-table table td {border:none;padding:0;margin:0;}
+#admin-edit-table table td {border:none;padding:0;margin:0;}
+#admin-edit-table select,
+#admin-edit-table input,
+#admin-edit-table option {font-size: 12px;}
+#glm-manual {position:absolute;right:200px;top:10px;width:300px;}
+#glm-manual a {padding:5px 2px;width:149px;background-color:#DDDDDD;color:#000;}
+div.fileupload { border:1px solid black;float:left;margin:5px; padding:5px;background-color:white; color:black; }
+div.fileupload p { margin:0; padding:0;float:left; }
+div.fileupload span { background-color:#c0c0c0; }
+.level-0 {
+ font-weight: bold;
+ padding-left: 0;
+ background-color: #ccc;
+}
+.level-1 {
+ padding-left: 20px;
+ background-color: #ddd;
+ }
+.level-2 {padding-left: 40px;}
+.level-3 {padding-left: 60px;}
+.level-4 {padding-left: 80px;}
+.level-5 {padding-left: 100px;}
+.level-6 {padding-left: 120px;}
+.pager {
+ text-align: center;
+ background: #F6F6F6;
+ border-color: #DDD;
+ border-style: solid;
+ border-width: 1px 0;
+ margin: 1.0em 0;
+ padding: 8px 0;
+ text-align: center;
+ width: 100%;
+ font-size: 12px;
+
+}
+.pager b {
+ border: 1px solid #CCC;
+ border: 1px solid #17186A;
+ background: #FFF;
+ padding: 5px 7px;
+}
+.pager a {
+ background: #FFF;
+ border: 1px solid #CCC;
+ padding: 5px 7px;
+ text-decoration: none;
+ color: #000;
+}
+.pager a:hover {
+ border: 1px solid #999;
+ border: 1px solid #17186A;
+}
+#form-wrap legend {
+ color: #fff;
+ background: #1D58A5;
+ border: 1px solid #17186A;
+ padding: 2px 6px;
+}
+#form-wrap p {margin:1px;}
+#form-wrap label {
+ float: none;
+ margin-right: 0;
+ display: inline;
+ clear: left;
+}
\ No newline at end of file
diff --git a/admin/nav.phtml b/admin/nav.phtml
new file mode 100644
index 0000000..86816e3
--- /dev/null
+++ b/admin/nav.phtml
@@ -0,0 +1,167 @@
+
+
+
+
+Admin Navigation
+
+
+
+
+
+application->name] = $blocksConfig->application->path;
+}
+if (defined('ROTATING_IMAGES') && ROTATING_IMAGES) {
+ $rotatingImagesRoot =& $conf->parseConfig(
+ BASE . 'Toolkit/RotatingImages/config.ini',
+ 'IniFile'
+ );
+ $rotatingImagesName
+ = $rotatingImagesRoot->getItem('section', 'conf')
+ ->getItem('directive', 'applicationName')
+ ->getContent();
+ $nav[$rotatingImagesName] = MEDIA_BASE_URL.'admin/rotatingImages.php';
+}
+if (defined('SEASONS') && SEASONS) {
+ $seasonConfig = new Zend_Config_Ini(
+ BASE . 'Toolkit/Seasons/application.ini',
+ strtolower($_ENV['GLM_HOST_ID'])
+ );
+ $nav[$seasonConfig->application->name] = MEDIA_BASE_URL.'admin/seasons.php';
+}
+if (defined('BANNERS') && BANNERS) {
+ $nav['Banners'] = MEDIA_BASE_URL.'admin/banners.php';
+}
+if (defined('CONTACT_DB') && CONTACT_DB) {
+ $nav['Contacts'] = MEDIA_BASE_URL.'admin/Contact/';
+}
+if (defined('EVENT_DB') && EVENT_DB) {
+ $nav['Events']
+ = (defined('COMMON_EVENTS') && COMMON_EVENTS)
+ ? MEDIA_BASE_URL.'admin/CommonEvents/'
+ : MEDIA_BASE_URL.'admin/Events/';
+}
+if (defined('COUPONS') && COUPONS) {
+ $couponsRoot =& $conf->parseConfig(
+ BASE . 'Toolkit/Coupons/config.ini',
+ 'IniFile'
+ );
+ $couponsName
+ = $couponsRoot->getItem('section', 'conf')
+ ->getItem('directive', 'applicationName')
+ ->getContent();
+ $nav[$couponsName] = MEDIA_BASE_URL.'admin/coupons.php';
+}
+if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ $memberRoot =& $conf->parseConfig(
+ BASE . 'Toolkit/Members/config.ini',
+ 'IniFile'
+ );
+ $memberName
+ = $memberRoot->getItem('section', 'listing type')
+ ->getItem('directive', 'plural')
+ ->getContent();
+ $nav[$memberName] = MEDIA_BASE_URL.'admin/members.php';
+}
+if (defined('EMPLOYMENT') && EMPLOYMENT) {
+ $empConfig = new Zend_Config_Ini(
+ BASE . 'Toolkit/Employment/config.ini',
+ strtolower($_ENV['GLM_HOST_ID'])
+ );
+ $empName
+ = $empConfig->applicationName;
+ $nav[$empName] = MEDIA_BASE_URL.'admin/employment/index.php';
+}
+if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) {
+ $nav['Image Library'] = MEDIA_BASE_URL.'admin/photos.php';
+}
+if (defined('VIDEOS') && VIDEOS) {
+ $nav['Video Gallery'] = MEDIA_BASE_URL.'admin/videos.php';
+}
+if (defined('PRESS_DB') && PRESS_DB) {
+ $nav['Press'] = MEDIA_BASE_URL.'admin/Press/';
+}
+if (defined('TICKETING') && TICKETING) {
+ $nav['Ticketing'] = MEDIA_BASE_URL.'admin/ticketing/';
+}
+$nav['Support Form'] = MEDIA_APP_BASE_URL .
+ 'supportForm.php?sitename='.urlencode(SITENAME);
+if (defined('EVENT_MANAGEMENT') && EVENT_MANAGEMENT) {
+ $nav['Event Management']
+ = MEDIA_BASE_URL.'admin/EventManagement/EventManagement.php';
+}
+$nav['Server Statistics'] = MEDIA_BASE_URL.'admin/logs/';
+
+foreach ($nav as $name => $url) {
+ echo '
+
+ '.$name.'
+ ';
+}
+?>
+
+
+
+
+
+
+
diff --git a/admin/photos.php b/admin/photos.php
new file mode 100644
index 0000000..9ee553f
--- /dev/null
+++ b/admin/photos.php
@@ -0,0 +1,21 @@
+config = $config;
+$registry->page = MEDIA_BASE_URL . 'admin/photos.php';
+$appConfig = $config->application->toArray();
+$registry->dbh = Toolkit_Database::getInstance();
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath($appConfig['path']);
+$registry->router->setApplication($appConfig['application']);
+
+$html = $registry->router->loader();
+
+echo $html;
\ No newline at end of file
diff --git a/admin/rotatingImages.php b/admin/rotatingImages.php
new file mode 100644
index 0000000..5b4a1c5
--- /dev/null
+++ b/admin/rotatingImages.php
@@ -0,0 +1,42 @@
+parseConfig(
+ BASE . 'Toolkit/RotatingImages/config.ini',
+ 'IniFile'
+);
+
+$registry = new Toolkit_Registry;
+$registry->dbh = Toolkit_Database::getInstance();
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->config = $rotatingImagesRoot;
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/RotatingImages');
+$registry->router->setApplication('RotatingImages');
+
+$navigation = new Toolkit_RotatingImages_Navigation(
+ new HTML_Menu(),
+ new HTML_Menu_DirectRenderer()
+);
+
+$navArray = $navigation->getNavStructure($rotatingImagesRoot);
+$navHtml = $navigation->renderPageNav($navArray, 'rows');
+
+$html = $registry->router->loader();
+
+$appName
+ = $rotatingImagesRoot->getItem('section', 'conf')
+ ->getItem('directive', 'applicationName')
+ ->getContent();
+
+if (filter_input(INPUT_GET, 'ac') == 'preview') {
+ GLM_TOOLBOX::top('', '', null, false);
+ echo $html;
+ GLM_TOOLBOX::footer();
+} else {
+ GLM_TOOLBOX::top($appName, '');
+ echo $navHtml;
+ echo $html;
+ GLM_TOOLBOX::footer();
+}
+?>
diff --git a/admin/splash.phtml b/admin/splash.phtml
new file mode 100755
index 0000000..2186bbd
--- /dev/null
+++ b/admin/splash.phtml
@@ -0,0 +1,23 @@
+
+
+
+
+
+Welcome to GLM Toolbox
+
+
+
+
+
+ Welcome To The Administration Area
+
+
Please Choose The Area You Wish To Update.
+
+
+
+
+
+
diff --git a/admin/toolbox.php b/admin/toolbox.php
new file mode 100644
index 0000000..cfb8559
--- /dev/null
+++ b/admin/toolbox.php
@@ -0,0 +1,37 @@
+dbh = Toolkit_Database::getInstance();
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/Toolbox');
+$registry->router->setApplication('Toolbox');
+
+$tlbConf = new Config;
+$tbxRoot
+ =& $tlbConf->parseConfig(BASE . 'Toolkit/Toolbox/config.ini', 'IniFile');
+
+$navigation = new Toolkit_Toolbox_Navigation(
+ new HTML_Menu(),
+ new HTML_Menu_DirectRenderer()
+);
+
+$navArray = $navigation->getNavStructure($tbxRoot);
+$navHtml = $navigation->renderPageNav($navArray, 'rows');
+
+$html = $registry->router->loader();
+
+$appName
+ = $tbxRoot->getItem('section', 'conf')
+ ->getItem('directive', 'applicationName')
+ ->getContent();
+
+
+GLM_TOOLBOX::top($appName, '');
+echo '';
+echo $navHtml;
+echo $html;
+GLM_TOOLBOX::footer();
+?>
diff --git a/admin/videos.php b/admin/videos.php
new file mode 100644
index 0000000..1fd8de6
--- /dev/null
+++ b/admin/videos.php
@@ -0,0 +1,33 @@
+parseConfig(
+ BASE . 'Toolkit/Videos/config.ini',
+ 'IniFile'
+);
+
+// get reference to [conf] section of config file
+$appName
+ = $confRoot->getItem('section', 'conf')
+ ->getItem('directive', 'applicationName')
+ ->getContent();
+
+$navigation = new Toolkit_Videos_Navigation(
+ new HTML_Menu(),
+ new HTML_Menu_DirectRenderer()
+);
+
+$navArray = $navigation->getNavStructure($confRoot);
+$navHtml = $navigation->renderPageNav($navArray, 'rows');
+$c = new Toolkit_Videos_Controller();
+$videos = $c->toHtml(
+ Toolkit_Database::getInstance(),
+ $confRoot
+);
+
+GLM_TOOLBOX::top($appName, '');
+echo $navHtml;
+echo $videos;
+GLM_TOOLBOX::footer();
\ No newline at end of file
diff --git a/classes/class_db.inc b/classes/class_db.inc
new file mode 100755
index 0000000..a84eb0c
--- /dev/null
+++ b/classes/class_db.inc
@@ -0,0 +1,846 @@
+
+ * @copyright 2009 Gaslight Media
+ * @license Gaslight Media
+ * @version CVS: $Id: class_db.inc,v 1.8 2010/05/25 14:15:15 jamie Exp $
+ * @link <>
+ */
+
+/**
+ * Short description for class
+ *
+ * Long description (if any) ...
+ *
+ * @category Classes
+ * @package GLM_DB
+ * @author Steve Sutton
+ * @copyright 2009 Gaslight Media
+ * @license Gaslight Media
+ * @version Release: @package_version@
+ * @link <>
+ */
+class GLM_DB
+{
+ // {{{ Properties
+
+ /**
+ * host
+ * string host database host server name
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $host;
+ /**
+ * dbname
+ * string dbname name of the database
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $dbname;
+ /**
+ * user
+ * string user The user to connect as
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $user;
+ /**
+ * password
+ * string password The users password if any
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $password;
+ /**
+ * dbd
+ * string dbd Database connection result ID#
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $dbd;
+ /**
+ * conn
+ * string conn string postgres connection string default = CONN_STR
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $conn;
+ /**
+ * trans
+ * boolean trans bool if true a transaction is in process
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $trans;
+ /**
+ * Result
+ *
+ * @var mixed
+ * @access public
+ */
+ protected $Result;
+
+ /**
+ * Description for public
+ * @var unknown
+ * @access public
+ */
+ public $dbh;
+ // }}}
+ // {{{ GLM_DB()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $conn Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function GLM_DB($conn = CONN_STR)
+ {
+ $this->dbh = Toolkit_Database::getInstance();
+ $this->host = "";
+ $this->dbname = "";
+ $this->user = "nobody";
+ $this->password = "";
+ $this->conn = $conn;
+ $this->trans = 0;
+ $this->dbd = "";
+ }
+
+ // }}}
+ // {{{ db_auto_array()
+
+ /** db_auto_get_array
+ *
+ * The auto function for retrieving an array based soley on a query
+ * string. This function makes the connection, does the exec, fetches
+ * the array, closes the connection, frees memory used by the result,
+ * and then returns the array
+ *
+ * {@source }
+ * @param $qs SQL query string
+ * @param $i row number
+ * @param $type PGSQL_ASSOC or PGSQL_BOTH or PSQL_NUM
+ *
+ * @returns array - Returns an associative array of key-value pairs
+ * @access public
+ */
+
+ function db_auto_array($qs, $i, $type)
+ {
+ if ($this->dbh) {
+ return $this->dbh->query($qs)->fetch(PDO::FETCH_ASSOC);
+ }
+ if (!$this->dbd) {
+ $this->dbd =& $this->db_connect();
+ }
+ $res = $this->db_exec($qs);
+ if (!$res) {
+ return 0;
+ }
+ if ($this->db_numrows($res) == 0) {
+ return 0;
+ }
+
+ $row = $this->db_fetch_array($res, $i, $type);
+
+ if(!$this->db_freeresult($res)) {
+ return 0;
+ }
+
+ return $row;
+ }
+
+ // }}}
+ // {{{ db_auto_exec()
+
+ /** db_auto_exec
+ *
+ * The auto function for executing a query.
+ * This function makes the connection, does the exec, fetches
+ * the array, closes the connection, frees memory used by the result,
+ * and then returns success (not a valid result index)
+ *
+ * {@source }
+ * @param $qs SQL query string
+ * @returns int - Returns 1 for success 0 for failure
+ * @access public
+ */
+
+ function db_auto_exec($qs)
+ {
+ if ($this->dbh) {
+ return $this->dbh->query($qs);
+ }
+ $this->db_connect();
+ if (!$this->dbd) {
+ return 0;
+ }
+ if (!$this->db_exec( $qs)) {
+ return 0;
+ } else {
+ return 1;
+ }
+ }
+
+ // }}}
+ // {{{ db_auto_get_data()
+
+ /** db_auto_get_data
+ *
+ * The auto function for retrieving an array based soley on a query
+ * string. This function makes the connection, does the exec, fetches
+ * the array, closes the connection, frees memory used by the result,
+ * and then returns the array.
+ *
+ * {@source }
+ * @param string $qs SQL query string
+ *
+ * @returns mixed
+ * @access public
+ */
+ function db_auto_get_data($qs)
+ {
+ if ($this->dbh) {
+ return $this->dbh->query($qs)->fetchAll(PDO::FETCH_ASSOC);
+ }
+ if (!$this->dbd) {
+ $this->db_connect();
+ }
+ if (!( $res = $this->db_exec( $qs))) {
+ return false;
+ }
+ $totalrows = pg_NumRows( $res);
+ for ($i = 0 ; $i < $totalrows ; $i++) {
+ $data[$i] = $this->db_fetch_array ($res, $i, PGSQL_ASSOC);
+ }
+ if (isset( $data) && $data != "") {
+ return $data;
+ } else {
+ return 0;
+ }
+ }
+
+ // }}}
+ // {{{ db_close()
+
+ /** db_close
+ *
+ * Closes the connection to database specified by the handle dbd
+ * returns a boolean for success
+ *
+ * {@source }
+ * @returns bool - Returns 1 on success 0 if dbd is not a valid connection
+ * @access public
+ */
+
+ function db_close()
+ {
+ switch (DB_TYPE) {
+ case "postgres":
+ pg_close($this->dbd);
+ break;
+ default:
+ return false;
+ }
+ }
+
+ // }}}
+ // {{{ db_connect()
+
+ /**
+ * db_connect
+ *
+ * Creates a connection to database specified $conn_str,
+ * and returns a boolean for success.
+ *
+ * @uses GLM_DB::$dbd
+ * @uses GLM_DB::$conn
+ * @uses GLM_DB::$dbname
+ * @uses GLM_DB::$host
+ * @uses GLM_DB::$user
+ * @uses GLM_DB::$password
+ * {@source }
+ * @returns int
+ * @access public
+ */
+
+ function db_connect()
+ {
+ if (isset( $this->dbd) && $this->dbd != "") {
+ return $this->dbd;
+ }
+ switch (DB_TYPE) {
+ case "postgres":
+ if ($this->host == '' && $this->dbname == '') {
+ $conn = $this->conn;// CONN_STR;
+ } else {
+ $conn .= ($this->host != '') ? 'host='.$this->host.' ' : '';
+ $conn .= ($this->dbname != '') ? 'dbname='.$this->dbname.' ' : '';
+ $conn .= ($this->user != '') ? 'user='.$this->user." " : '';
+ $conn .= ($this->password != '') ? "password=".$this->password : '';
+ }
+ if (!$this->dbd = pg_connect($conn)) {
+ echo pg_errormessage($conn);
+ }
+ $this->_setSearchPath();
+ break;
+
+ default:
+ return 0;
+ break;
+ }
+ return $this->dbd;
+ }
+
+ // }}}
+
+ // {{{ _setSearchPath()
+
+ private function _setSearchPath()
+ {
+ // Add schemas to search path.
+ $format = "
+ SELECT set_config(
+ 'search_path',
+ current_setting('search_path') || ',%s',
+ false
+ )";
+
+ $sql = sprintf($format, 'toolbox');
+ $ret = $this->db_exec($sql);
+
+ $sql = sprintf($format, 'ckimages');
+ $this->db_exec($sql);
+
+ if (defined('CONTACT_DB') && CONTACT_DB) {
+ // define banner search path
+ $sql = sprintf($format, 'contacts');
+ $this->db_exec($sql);
+ }
+
+ if (defined('BANNERS') && BANNERS) {
+ // define banner search path
+ $sql = sprintf($format, 'banners');
+ $this->db_exec($sql);
+ }
+
+ if (defined('ROTATING_IMAGES') && ROTATING_IMAGES) {
+ // define rotating images search path
+ $sql = sprintf($format, 'rotatingImages');
+ $this->db_exec($sql);
+ }
+
+ if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) {
+ // define phot gallery search path
+ $sql = sprintf($format, 'photos');
+ $this->db_exec($sql);
+ }
+
+ if (defined('EVENT_DB') && EVENT_DB) {
+ // define members search path
+ $sql = sprintf($format, 'events');
+ $this->db_exec($sql);
+ }
+
+ if (defined('POSTCARD_DB') && POSTCARD_DB) {
+ // define members search path
+ $sql = sprintf($format, 'postcards');
+ $this->db_exec($sql);
+ }
+
+ if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ // define members search path
+ $sql = sprintf($format, 'members');
+ $this->db_exec($sql);
+ }
+
+ if (defined('COUPONS') && COUPONS) {
+ // define coupon search path
+ $sql = sprintf($format, 'coupons');
+ $this->db_exec($sql);
+ }
+ }
+
+ // }}}
+ // {{{ db_exec()
+
+ /** db_exec
+ *
+ * Execute an SQL query, * returning a valid result index or zero(0) on
+ * failure.
+ *
+ * {@source }
+ * @param $qs -- SQL query string
+ * @returns int Returns a valid result index on success 0 on failure
+ * @access public
+ */
+ function db_exec($qs)
+ {
+ if ($this->dbh) {
+ try {
+ $stmt = $this->dbh->query($qs);
+ $stmt->setFetchMode(PDO::FETCH_ASSOC);
+ return $stmt;
+ } catch(PDOEXception $e) {
+ Toolkit_Common::handleError($e);
+ }
+ }
+ if (!$this->dbd) {
+ $this->dbd = $this->db_connect();
+ }
+ switch (DB_TYPE) {
+ case "postgres":
+ if(!$ret = pg_exec($this->dbd, $qs)) {
+ echo "".$qs." ";
+ }
+ break;
+ default:
+ return false;
+ }
+ return $ret;
+ }
+
+ // }}}
+ // {{{ db_fetch_array()
+
+ /** db_fetch_array
+ *
+ * Stores the data in associative indices, using the field names as
+ * keys.
+ *
+ * {@source }
+ * @param $res -- valid database result index
+ * @param $i -- row number
+ * @param $type -- PGSQL_ASSOC,PGSQL_BOTH,PGSQL_NUM
+ * @returns array Returns an associative array of key-value pairs
+ * @access public
+ */
+
+ function db_fetch_array($res, $i = 0, $type = 'PGSQL_ASSOC')
+ {
+ if ($this->dbh) {
+ return $res->fetch(PDO::FETCH_ASSOC);
+ }
+ switch (DB_TYPE) {
+ case "postgres":
+ $row = pg_fetch_array($res, $i, $type);
+ break;
+
+ default:
+ return false;
+ }
+ return $row;
+ }
+
+ // }}}
+ // {{{ db_freeresult()
+
+ /** db_freeresult
+ *
+ * Free result memory.
+ *
+ * {@source }
+ * @param $res -- valid database result index
+ * @returns bool - Returns 1 for success 0 for failure
+ * @access public
+ */
+
+ function db_freeresult($res)
+ {
+ switch (DB_TYPE) {
+ case "postgres":
+ $ret = pg_freeresult($res);
+ break;
+
+ default:
+ return false;
+ }
+ return $ret;
+ }
+
+ // }}}
+ // {{{ db_numrows()
+
+ /** db_numrows
+ *
+ * Determine number of rows in a result index
+ *
+ * {@source }
+ * @param $res -- valid database result index
+ * @returns int - Returns number of rows
+ * @access public
+ */
+
+ function db_numrows($res)
+ {
+ if ($this->dbh) {
+ return $res->rowCount();
+ }
+ switch (DB_TYPE) {
+ case "postgres":
+ $ret = pg_numrows($res);
+ break;
+
+ default:
+ return -1;
+ }
+ return $ret;
+ }
+
+ // }}}
+ // {{{ delete()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $table Parameter description (if any) ...
+ * @param unknown $condition Parameter description (if any) ...
+ * @return unknown Return description (if any) ...
+ * @access public
+ */
+ function delete($table, $condition)
+ {
+ return $this->pgsql_delete($table, $condition);
+ }
+
+ // }}}
+ // {{{ insert()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $table Parameter description (if any) ...
+ * @param unknown $data Parameter description (if any) ...
+ * @param unknown $primary_key Parameter description (if any) ...
+ * @param unknown $sequence Parameter description (if any) ...
+ * @return unknown Return description (if any) ...
+ * @access public
+ */
+ function insert($table, $data, $primary_key, $sequence)
+ {
+ return $this->pgsql_insert($table, $data, $primary_key, $sequence);
+ }
+
+ // }}}
+ // {{{ pgsql_convert()
+
+ /**
+ * pgsql_convert
+ *
+ * converts an array (like _POST) and verifies field types to use in insert or update of postgres table
+ *
+ * @param mixed $table
+ * @param mixed $data
+ * @access public
+ * @return string
+ */
+ function pgsql_convert($table, $data)
+ {
+ $query = "select a.attname, format_type(a.atttypid, a.atttypmod)
+ from pg_class c, pg_attribute a
+ where c.relname = '$table'
+ and a.attnum > 0 and a.attrelid = c.oid
+ order by a.attnum";
+ if ($mData = $this->db_auto_get_data($query)) {
+ foreach ($mData as $mRow) {
+ $meta_data[$mRow['attname']] = $mRow['format_type'];
+ }
+ }
+ if (is_array($data)) {
+ foreach ($data as $field => $val) {
+ if ($meta_data[$field]) {
+ switch ($meta_data[$field]) {
+ case "integer":
+ case "double precision":
+ if ($val == '') {
+ $proc_data[$field] = 'NULL';
+ } elseif (is_numeric( $val)) {
+ $proc_data[$field] = $val;
+ } else{
+ die('value for field (int)'.$field.' is not a number');
+ }
+ break;
+ case "boolean":
+ if ($val == '') {
+ $proc_data[$field] = 'NULL';
+ } elseif ($val == 'f' || $val == 't') {
+ $proc_data[$field] = "'".$val."'";
+ } else{
+ die('value for field (boolean)'.$field.' is not a boolean');
+ }
+ break;
+ case "text":
+ // maybe check to see that the text is being slashed if not then prepare it for postgres
+ $text = addslashes( stripslashes( trim( $val)));
+ $proc_data[$field] = "'$text'";
+ break;
+ case "date":
+ if (preg_match( "/([0-9]{1,2})[\/-]?([0-9]{1,2})[\/-]?([0-9]{2,4})|/", $val)) {
+ $proc_data[$field] = "'".$val."'";
+ } else{
+ die('value for field (date)'.$field.' is not a date');
+ }
+ break;
+ default:
+ die('need case for this name:'.$field.' type: '.$meta_data[$field]);
+ break;
+ }
+ } else{
+ die('Error no field named '.$field.' exist in '.$table);
+ }
+ }
+ } else{
+ return false;
+ }
+ return $proc_data;
+ }
+
+ // }}}
+ // {{{ pgsql_delete()
+
+ /**
+ * pgsql_delete
+ *
+ * @param mixed $table
+ * @param mixed $condition
+ * @access public
+ * @return string
+ */
+ function pgsql_delete($table, $condition)
+ {
+ reset($condition);
+ $cKey = key($condition);
+ $query = "delete from $table where ";
+ $query .= $cKey;
+ $query .= " = ".$condition[$cKey];
+ return $this->db_exec( $query);
+ }
+
+ // }}}
+ // {{{ pgsql_insert()
+
+ /**
+ * pgsql_insert
+ *
+ * @param mixed $table
+ * @param mixed $data
+ * @param mixed $primary_key
+ * @param mixed $sequence
+ * @access public
+ * @return string
+ */
+ function pgsql_insert($table, $data, $primary_key, $sequence)
+ {
+ $converted = $this->pgsql_convert($table, $data);
+ if ($res = $this->db_exec("select nextval('$sequence') as $primary_key")) {
+ $insert_data = $this->db_fetch_array( $res, 0, PGSQL_ASSOC);
+ $insert_id = $insert_data[$primary_key];
+ } else {
+ die('returned no insert_id');
+ }
+ $query = "INSERT INTO $table ($primary_key,".implode(",",array_keys( $converted)).") values ($insert_id,".implode(",",array_values( $converted)).")";
+ if ($res = $this->db_exec($query)) {
+ $this->insert_id = $insert_id;
+ return $insert_id;
+ } else {
+ echo $query;
+ die('error');
+ }
+ }
+
+ // }}}
+ // {{{ pgsql_select()
+
+ /**
+ * pgsql_select
+ *
+ * @param mixed $query
+ * @access public
+ * @return string
+ */
+ function pgsql_select($query)
+ {
+ return $this->db_auto_get_data( $query);
+ }
+
+ // }}}
+ // {{{ pgsql_update()
+
+ /**
+ * pgsql_update
+ *
+ * @param mixed $table
+ * @param mixed $data
+ * @param mixed $condition
+ * @access public
+ * @return string
+ */
+ function pgsql_update($table, $data, $condition)
+ {
+ $converted = $this->pgsql_convert($table, $data);
+ foreach ($converted as $key => $value) {
+ $q_parts[] = "$key = $value";
+ }
+ reset($condition);
+ $cKey = key($condition);
+ if (is_array($converted)) {
+ $query = "update $table set ";
+ if (is_array($q_parts)) {
+ $query .= implode(",",$q_parts);
+ }
+ $query .= " where ";
+ $query .= $cKey;
+ $query .= " = ".$condition[$cKey];
+ }
+ $this->db_exec($query);
+ }
+
+ // }}}
+ // {{{ select()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $query Parameter description (if any) ...
+ * @return unknown Return description (if any) ...
+ * @access public
+ */
+ function select($query)
+ {
+ return $this->db_auto_get_data($query);
+ }
+
+ // }}}
+ // {{{ trans_end()
+
+ /** trans_end
+ *
+ * Commit the postgres transaction
+ *
+ * {@source }
+ * @returns bool true if successful
+ * @access public
+ */
+ function trans_end()
+ {
+ if (!$this->trans) {
+ if(!$this->db_exec("COMMIT WORK;")) {
+ return false;
+ } else{
+ return true;
+ }
+ } else{
+ return false;
+ }
+ }
+
+ // }}}
+ // {{{ trans_exec()
+
+ /** trans_exec
+ *
+ * exec a postgres query in a
+ * postgres transaction
+ *
+ * {@source }
+ * @param string query
+ * @access public
+ */
+ function trans_exec($query)
+ {
+ if ($query != "") {
+ if(!$ret = $this->db_exec($query)) {
+ $this->db_exec("ABORT WORK;");
+ return false;
+ } else {
+ return $ret;
+ }
+ } else {
+ return false;
+ }
+ }
+
+ // }}}
+ // {{{ trans_start()
+
+ /** trans_start
+ *
+ * Start a postgres transaction
+ *
+ * {@source }
+ * @returns bool true if sucessful
+ * @access public
+ */
+ function trans_start()
+ {
+ if (!$this->trans) {
+ if (!$this->dbd = $this->db_connect()) {
+ $this->trans = false;
+ return false;
+ } else {
+ $this->db_exec("BEGIN WORK;");
+ $this->trans = true;
+ return true;
+ }
+ } else {
+ return true;
+ }
+ }
+
+ // }}}
+ // {{{ update()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $table Parameter description (if any) ...
+ * @param unknown $data Parameter description (if any) ...
+ * @param unknown $condition Parameter description (if any) ...
+ * @return unknown Return description (if any) ...
+ * @access public
+ */
+ function update($table, $data, $condition)
+ {
+ return $this->pgsql_update($table, $data, $condition);
+ }
+
+ // }}}
+}
+?>
diff --git a/classes/class_template.inc b/classes/class_template.inc
new file mode 100644
index 0000000..bb27145
--- /dev/null
+++ b/classes/class_template.inc
@@ -0,0 +1,2983 @@
+
+ * $Id: class_template.inc,v 1.52 2010/07/04 23:53:44 jamie Exp $
+ * NOTE: for the search engine freindly url's use .htaccess file.
+ * need to make sure .htaccess is enabled or this work work
+ * to turn off seo url's set define SEO_URL to 0 in setup file
+ * NOTE: make sure you redo the www.domain.com lines in the .htaccess file
+ * need to set it up before testing with it.
+ *
+ *
+ * For the page title and meta tags make a $title and $meta vars depending on
+ * weather or not it is the home page.
+ *
+ *
+ * @package Toolbox Library
+ * @subpackage Template Library
+ * @category Template
+ * @author Steve Sutton
+ * @copyright 2007
+ * @version $Revision: 1.52 $
+ * @since $Date: 2010/07/04 23:53:44 $
+ * @todo update the phpdocs for all classes
+ * @todo add title for all the navigation links if and only if they have page title
+ * @todo some tutorial in the docs for how to set things up.
+ */
+class GLM_TEMPLATE
+{
+ // {{{ properties
+
+ /**
+ * The category id for the page
+ * @var integer
+ * @access public
+ */
+ public $catid;
+
+ /**
+ * The postgres database handler
+ * @var object
+ * @access public
+ */
+ public $DB;
+
+ /**
+ * The starting style for the header
+ *
+ * class="content" should not be used anymore
+ *
+ * @var string
+ * @access protected
+ */
+ protected $header_begin = '';
+
+ /**
+ * The ending style for the header
+ * @var string header_end
+ * @access protected
+ */
+ protected $header_end = ' ';
+
+ /**
+ * The starting style for the sub header
+ * @var string
+ * @access protected
+ */
+ protected $subheader_begin = '';
+
+ /**
+ * The ending style for the sub header
+ * @var string
+ * @access protected
+ */
+ protected $subheader_end = ' ';
+
+ /**
+ * The starting position for images
+ *
+ * @var string
+ * @access protected
+ */
+ protected $img_align = 'left';
+
+ /**
+ * Whether to alternate the images or not
+ *
+ * for alternating images set to 1 else leave alone
+ *
+ * @var string
+ * @access protected
+ */
+ protected $img_alternate = 1;
+
+ /**
+ * The path to the image directory
+ * @var string
+ * @access protected
+ */
+ protected $img_size;
+
+ /**
+ * The category array
+ * @var array
+ * @access protected
+ */
+ protected $data;
+
+ /**
+ * The items array
+ * @var array
+ * @access protected
+ */
+ protected $items;
+
+ /**
+ * @var string type The type
+ */
+ protected $type;
+
+ /**
+ * Used for menu generation
+ * @var string whole_thread The thread string
+ */
+ protected $whole_thread = null;
+
+ /**
+ * Used for menu generation
+ * @var integer thread_count The thread count
+ */
+ protected $thread_count = 1;
+
+ /**
+ * @var array $pages
+ * @access protected
+ */
+ protected $pages;
+
+ /**
+ * adds active = 't' to queries only if ACTIVE_FLAG is set to true
+ * @var string
+ * @access protected
+ */
+ protected $active_query;
+
+ /**
+ * determines page layout
+ * @var integer
+ * @access protected
+ */
+ protected $template;
+
+ /**
+ * Page extension for php pages .php or .phtml
+ * @var string
+ * @access protected
+ */
+ protected $php_ext = '.php';
+
+ // }}}
+ // {{{ __construct()
+
+ /**
+ * GLM_TEMPLATE
+ *
+ * @param mixed $catid current page category id
+ * @param mixed $DB Object passed from GLM_DB if done
+ * @access public
+ * @return string
+ */
+ function __construct($catid, $DB = NULL)
+ {
+ // set the cache option from $GLOBALS
+ $this->cacheOptions = $GLOBALS['cacheOptions'];
+ // redo the cachDir
+ $this->cacheOptions['cacheDir'] = BASE . 'cache/';
+ // create a new instance of Cache_Lite
+ $this->cache = new Cache_Lite($this->cacheOptions);
+ $this->catid = $this->get_catid($catid);
+ // using a reference to $DB (should be started on setup.phtml
+ $this->set_DB($DB);
+ // switching to $GLOBALS['dbh']
+ $this->dbh = Toolkit_Database::getInstance();
+ // used for cvb's
+ $this->Member = $this->set_member();
+ // img_size are RESIZED, MIDSIZED, THUMB do not use ORIGINAL
+ $this->img_size = RESIZED;
+
+ $this->set_body_tag();
+ // Uses the PAGE array set in setup.phtml
+ $this->set_pages($GLOBALS['PAGES']);
+ // tell if page is active, deleted or inactive
+ $this->page_status($catid);
+ // set active query string
+ $this->set_active_query();
+ }
+
+ // }}}
+
+ // {{{ build_picklist()
+
+ /**
+ * build_picklist:
+ * @param string $fieldname:
+ * @param array $data:
+ * @param mixed $selected:
+ * @param string $type = "standard":
+ * @param boolean $auto = 0:
+ * @param integer $width = NULL :
+ *
+ * @uses GLM_TOOLBOX::build_picklist()
+ *
+ * @return string
+ * @access public
+ */
+ function build_picklist( $fieldname, $data, $selected, $type = "standard",$auto = 0,$width = NULL )
+ {
+ return GLM_TOOLBOX::build_picklist( $fieldname, $data, $selected, $type = "standard",$auto = 0,$width = NULL );
+ }
+
+ // }}}
+
+ // {{{ clean_text()
+
+ /**
+ * clean_text:get rid of single br or p br tags left from htmlarea when textarea is empty.
+ * @param string $output:
+ *
+ * @return string text cleaned
+ * @access public
+ **/
+ function clean_text($output)
+ {
+ $output = str_replace(" "," ",$output);
+ $output = str_replace("
","",$output);
+ return $output;
+ }
+
+ // }}}
+ // {{{ convert_to_thread()
+
+ /**
+ * convert_to_thread:
+ *
+ * @param array $threads:
+ * @param array $thread:
+ * @uses GLM_TEMPLATE::$thread_count
+ * @uses GLM_TEMPLATE::$whole_thread
+ * @uses GLM_TEMPLATE::get_seo_url()
+ * @uses GLM_TEMPLATE::convert_to_thread()
+ *
+ * @return string
+ * @access public
+ */
+ function convert_to_thread($threads, $thread)
+ {
+ foreach($thread as $parent=>$value) {
+ $this->whole_thread .= str_repeat(".",$this->thread_count);
+ $this->whole_thread .= "|".htmlentities($value['category'],ENT_QUOTES,'UTF-8');
+ $url = $this->get_seo_url( $value['id'] );
+ $this->whole_thread .= "|$url";
+ $this->whole_thread .= "\n";
+ if ($threads[$parent]) {
+ $this->thread_count++;
+ GLM_TEMPLATE::convert_to_thread($threads, $threads[$parent]);
+ }
+ }
+ $this->thread_count--;
+ return $this->whole_thread;
+ }
+
+ // }}}
+
+ // {{{ has_children()
+
+ /**
+ * has_children: return true or false if this category has sub categories under it.
+ *
+ * @param integer $catid:
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function has_children($catid)
+ {
+ // returns number of children that $catid has
+ $qs = "
+ SELECT count(*)
+ FROM bus_category
+ WHERE parent = $catid {$this-> active_query}";
+ $row=$this->DB->db_auto_get_data($qs);
+ return $row[0]['count'];
+ }
+
+ // }}}
+ // {{{ has_subs()
+
+ /**
+ * has_subs:
+ * @param integer $catid:
+ * @param object $DB:
+ *
+ * @uses GLM_TEMPLATE::$active_query
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function has_subs($catid, &$DB)
+ {
+ $sql = "
+ SELECT id
+ FROM bus_category
+ WHERE parent = $catid {$this->active_query}
+ ORDER BY pos";
+ $data = $DB->db_auto_get_data($sql);
+ return is_array($data);
+ }
+
+ // }}}
+
+ // {{{ get_all()
+
+ /**
+ * get_all:Does the query and set_data calls boths arrays
+ *
+ * @uses GLM_TEMPLATE::set_data()
+ * @uses GLM_TEMPLATE::$data
+ * @uses GLM_TEMPLATE::$items
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return void
+ * @access public
+ **/
+ function get_all($type = NULL)
+ {
+ $catid = $this->catid;
+ if ($type == 1 || !$type) {
+ $cat_query = "
+ SELECT *
+ FROM bus_category
+ WHERE id = $catid
+ ORDER BY pos";
+ try {
+ $res = $this->set_data($this->dbh->query($cat_query)->fetchAll());
+ $this->data = $res[0];
+ } catch(PDOException $e) {
+ echo ''.print_r($e, true).' ';
+ die($e->getMessage());
+ }
+ }
+ //$this->img_size = MIDSIZED;
+ //$this->img_size = RESIZED;
+ if ($type == 2 || !$type) {
+ $item_query = "
+ SELECT b.*
+ FROM bus b
+ LEFT OUTER JOIN bus_category_bus bcb ON (bcb.busid = b.id)
+ WHERE bcb.catid = $catid
+ ORDER BY bcb.pos";
+ try {
+ $this->items = $this->set_data($this->dbh->query($item_query)->fetchAll());
+ } catch(PDOException $e) {
+ echo ''.print_r($e, true).' ';
+ die($e->getMessage());
+ }
+ $file_query = "
+ SELECT *
+ FROM files
+ WHERE bus_id IN ( SELECT bus_id FROM bus_category_bus
+ WHERE catid = ".$this->catid." )
+ ORDER BY bus_id,pos;";
+ try {
+ $file_data = $this->DB->db_auto_get_data($file_query);
+ } catch(PDOException $e) {
+ echo ''.print_r($e, true).' ';
+ die($e->getMessage());
+ }
+ if (is_array($file_data)) {
+ foreach ($file_data as $file_row) {
+ $this->item_files[$file_row['bus_id']][] = GLM_TEMPLATE::set_file( $file_row['filename'],$file_row['urltext'] );
+ }
+ }
+ }
+ }
+
+ // }}}
+ // {{{ get_ancestors()
+
+ /**
+ * get_ancestors:get the ancestors for this category
+ *
+ * @param integer $catid: catid
+ * @param integer $count: starting counter
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return array
+ * @access public
+ */
+ function get_ancestors($catid, $count)
+ {
+ if ($count == 0 ) {
+ unset ($this->ancestors);
+ }
+
+ if ($catid) {
+ $query = "
+ SELECT id,category,parent
+ FROM bus_category
+ WHERE id = ".$catid."
+ ".$this->active_query;
+
+ $res = $this->DB->db_auto_get_data($query);
+ $id = $res[0]['id'];
+ $parent = $res[0]['parent'];
+ $category = $res[0]['category'];
+ $this->ancestors[$count]['id'] = $id;
+ $this->ancestors[$count]['label'] = $category;
+
+ $url = $this->get_seo_url( $id );
+ $this->ancestors[$count]['link'] = $url;
+ GLM_TEMPLATE::get_ancestors($parent,$count+1);
+
+ return array_reverse($this->ancestors);
+ }
+ }
+
+ // }}}
+ // {{{ get_base_url()
+
+ /**
+ * get_base_url: generate the base of the url for the given category id
+ * @param integer $id :
+ *
+ * @return string
+ * @access public
+ */
+ function get_base_url($id)
+ {
+ if ($this->pages[$id]) {
+ $page = $this->pages[$id];
+ } else {
+ $page = $this->pages['default'];
+ }
+ if ($GLOBALS['GLM_SERVER_ID'] == 'ws1.gaslightmedia.com' &&
+ $this->catid == 1) {
+ $page = '';
+ }
+ return $page;
+ }
+
+ // }}}
+ // {{{ get_bottom_nav()
+
+ /**
+ * get_bottom_nav: generate a top level only bottom navigation for the pages.
+ *
+ * @param integer $parent=0:
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function get_bottom_nav($parent=0)
+ {
+ $out = '';
+ $query = "select id,category,intro from bus_category where id != 1 and parent = $parent ".$this->active_query." order by pos asc";
+ $row = $this->DB->db_auto_get_data( $query );
+ $url = $this->get_seo_url( HOME_ID );
+ $links[] = 'Home ';
+ if (!is_array( $row ) ) {
+ return false;
+ } else {
+ $out .= '';
+ for ($i = 0; $i < sizeof($row); $i++) {
+ $category = htmlentities(strip_tags($row[$i]['category']),ENT_QUOTES,'UTF-8');
+ $url = $this->get_seo_url( $row[$i]['id'] );
+ $links[] = '
'.$category." \n";
+ }
+ if (is_array($links)) {
+ $out .= implode(" | ",$links);
+ }
+ $out .= '
';
+ return $out;
+ }
+ }
+
+ // }}}
+ // {{{ get_bread_crumbs()
+
+ /**
+ * get_bread_crumbs
+ *
+ * @param mixed $catid
+ * @access public
+ * @return string
+ */
+ function get_bread_crumbs($catid)
+ {
+ $string = $this->get_ancestors($catid, 0);
+ $isMemberProfilePage = ( isset($_GET['member_id'])
+ && ctype_digit((string)$_GET['member_id']));
+ if (is_array($string)) {
+ // adjust end if we have a profile page so we can last search
+ // page as link.
+ $end = $isMemberProfilePage ? count($string) : count($string) - 1;
+ if ($this->catid != HOME_ID) {
+ $outarray[] = 'Home ';
+ }
+ for($i = 0; $i < $end; ++$i) {
+ $outarray[] = ''.$string[$i]["label"].' ';
+ }
+ if ( isset($_GET['photo_catid'])
+ && defined('PHOTO_GALLERY')
+ && PHOTO_GALLERY
+ && ctype_digit($_GET['photo_catid'])
+ ) {
+ // user is now in a photo gallery albumn.
+ // need to update the breadcrumbs for this.
+ $currPageUri = $this->get_seo_url($catid);
+ $currPageLabel = $this->get_catheader($catid, $this->DB);
+
+ $outarray[] = ''.$currPageLabel.' ';
+
+ $sql = "
+ SELECT category
+ FROM photo_category
+ WHERE id = :id";
+
+ $stmt = $this->dbh->prepare($sql);
+ $stmt->bindParam(':id', $_GET['photo_catid'], PDO::PARAM_INT);
+ $stmt->execute();
+ $stmt->bindColumn('category', $photoCategory);
+ $stmt->fetch();
+
+ $outarray[] = $photoCategory;
+ } else {
+ if (!$isMemberProfilePage) {
+ $outarray[] = $this->get_catheader($catid, $this->DB);
+ } else {
+ $memberBreadCrumbs = new Toolkit_Members_BreadCrumbs();
+ $memberData = $memberBreadCrumbs->getArray(
+ $this->dbh,
+ $_GET['member_id']
+ );
+
+ $outarray = array_merge($outarray, $memberData);
+ }
+ }
+ $out = '';
+ if (is_array($outarray) && count($outarray) > 1) {
+ $out .= implode(" > ", $outarray);
+ }
+ if ($out) {
+ $return = ''.$out.'
';
+ }
+ }
+ return $return;
+ }
+
+ // }}}
+ // {{{ get_category()
+
+ /**
+ * get_category: grab just category contents
+ * @param integer $catid: id of bus_category
+ * @param boolean $showimg=1: weather or not to show category image
+ * @uses DELUXE_TOOLBOX
+ * @uses HOME_PAGE_EVENTS
+ * @uses GLM_TEMPLATE::clean_text()
+ * @uses GLM_TEMPLATE::get_home_events()
+ *
+ * @return string $output
+ * @access public
+ **/
+ function get_category($showimg = 1, $showdiv = 1)
+ {
+ if ($pageContent = $this->cache->get('page-'.$this->catid, 'Toolbox')) {
+ $sql = "
+ SELECT intro
+ FROM bus_category
+ WHERE id = :id";
+ try {
+ $stmt = $this->dbh->prepare($sql);
+ $stmt->bindParam(":id", $this->catid, PDO::PARAM_INT);
+ $stmt->execute();
+ $this->data['intro'] = $this->set_header($stmt->fetchColumn());
+ } catch(PDOException $e) {
+ Toolkit_Common::handleError($e);
+ }
+ return $pageContent;
+ } else {
+ if (DELUXE_TOOLBOX) {
+ $this->get_template("cat");
+ }
+ if (!$this->data) {
+ $this->get_all(1);
+ }
+ $data = $this->data;
+ // Setup the section_links boolean var so section links only
+ // show up on correct pages.
+ $this->section_links = ($data['section_links'] == 't');
+ if ( !$data["image"]
+ && !$data["description"]
+ && !$data["intro"] &&
+ ($this->catid != 1 && HOME_PAGE_EVENTS != true)
+ ) {
+ return false;
+ }
+
+ $output = '';
+ if ($showdiv == 1) {
+ $output .= '';
+ }
+
+ if ($this->catid == 1 && HOME_PAGE_EVENTS ) {
+ $output .= $this->get_home_events();
+ }
+
+ if ($data["image"] || $data["description"] || $data["intro"]) {
+ // $output .= $data["intro"] . ' ';
+ if ($showimg == 1) {
+ $output .= $data["image"] . ' ';
+ }
+ $output .= $data["description"] . ' ';
+ }
+
+ if ($showdiv == 1) {
+ $output .= '
';
+ }
+ $output = GLM_TEMPLATE::clean_text($output);
+ $this->cache->save($output, 'page-'.$this->catid, 'Toolbox');
+ return $output;
+ }
+
+ }
+
+ // }}}
+ // {{{ get_category_name()
+
+ /**
+ * getCategoryName:
+ * used mostly for getting category name for search engine friendly url's
+ *
+ * @param integer $id:
+ * @param string $table:
+ * @param object &$DB :
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return void
+ * @access public
+ */
+ function get_category_name($id, $table, &$DB)
+ {
+ if (!is_numeric($id)) {
+ return false;
+ }
+ if ($table == "class_category") {
+ $category = "name";
+ } else {
+ $category = "category";
+ }
+ $query = "
+ SELECT {$category}
+ FROM {$table}
+ WHERE id = :id";
+ try {
+ $stmt = $this->dbh->prepare($query);
+ $stmt->bindParam(":id", $id, PDO::PARAM_INT);
+ $stmt->execute();
+ $data = $stmt->fetchAll();;
+ } catch(PDOException $e) {
+ echo ''.print_r($e, true).' ';
+ die($e->getMessage());
+ }
+ if (is_array($data)) {
+
+ $add = '-'.$id;
+ if ($data[0]['category']) {
+ $category = $data[0]['category'].$add;
+ } elseif ($data[0]['name']) {
+ $category = $data[0]['name'].$add;
+ } else {
+ $category = $add;
+ }
+ return htmlspecialchars($category);
+ }
+ }
+
+ // }}}
+ // {{{ get_catheader()
+
+ /**
+ * get_catheader:output the category name.
+ *
+ * @param integer $catid: The catid for the page
+ * @param object $DB: db obj
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return void
+ * @access public
+ */
+ function get_catheader($catid, &$DB)
+ {
+ $query = "SELECT category FROM bus_category WHERE id = $catid";
+ $data = $DB->db_auto_get_data($query);
+ if ($data[0]['category']!="") {
+ $header = strip_tags($data[0]['category']);
+ } else {
+ $header = '';
+ }
+ return $header;
+ }
+
+ // }}}
+ // {{{ get_catid()
+
+ /**
+ * get_catid: setting catid for class
+ *
+ * We should be using the $_POST or $_GET globals here
+ *
+ * @return int catid
+ * @access public
+ **/
+ function get_catid($catid)
+ {
+ if (is_numeric($_GET['catid'])) {
+ return $_GET['catid'];
+ } elseif (is_numeric($_POST['catid'])) {
+ return $_POST['catid'];
+ } else {
+ return $this->catid = $catid;
+ }
+ }
+
+ // }}}
+ // {{{ get_catintro()
+
+ /**
+ * get_catintro: return the category page name.
+ *
+ * @param integer $catid: The catid for the page
+ * @param object $DB: db obj
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return void
+ * @access public
+ */
+ function get_catintro($catid)
+ {
+ $query = "SELECT intro FROM bus_category WHERE id = $catid";
+ $data = $this->DB->db_auto_get_data($query);
+ if ($data[0]['intro']!="") {
+ $header = strip_tags($data[0]['intro']);
+ } else {
+ $header = '';
+ }
+ return $header;
+ }
+
+ // }}}
+ // {{{ get_distance_from_traverse()
+
+ function get_distance_from_traverse( $zipcode ){
+ if (is_numeric( $zipcode ) ){
+ // zipcode for search is 49684
+ $tlat = (float)44.77329;
+ $tlon = (float)-85.70123;
+ $zipDB = new GLM_DB();
+ $zipDB->host = 'ds1';
+ $zipDB->dbname = 'zip';
+ $zipDB->pgsql_select( "BEGIN WORK;" );
+ $query = "
+ SELECT lat, lon, city, state_name
+ FROM zip
+ WHERE zipcode = '$zipcode'
+ order by city_type desc limit 1 offset 0;";
+ if ($data = $zipDB->pgsql_select( $query ) ){
+ $lat = (float)$data[0]['lat'];
+ $lon = (float)$data[0]['lon'];
+ $city = $data[0]['city'];
+ $state = $data[0]['state_name'];
+ }
+
+ $temp = "(pow(sin( ( ( $tlat * pi()/180.0 ) - ( $lat * pi()/180.0 )) /2.0),2) + cos( ( $lat * pi()/180.0 )) * cos( ( $tlat * pi()/180.0 ) ) * pow(sin( ( ( $tlon * pi()/180.0 ) - ( $lon * pi()/180.0 )) /2.0),2))";
+ $query = "select ceil(3956 * 2 * atan2(sqrt($temp ),sqrt(1- ($temp) ))) as distance";
+ if ($zip_data = $zipDB->pgsql_select( $query ) ){
+ $zipDB->pgsql_select( "ABORT WORK;" );
+ $zdata['remote_addr'] = $_SERVER['REMOTE_ADDR'];
+ $zdata['zipcode'] = $zipcode;
+ $zdata['city'] = $city;
+ $zdata['state'] = $state;
+ $this->DB->pgsql_insert( 'zip_dist_form', $zdata, 'zip_dist_form_id', 'zip_dist_form_zip_dist_form_id_seq', true );
+ return $zip_data[0]['distance'];
+ }
+ }
+ }
+
+ // }}}
+ // {{{ get_event_date()
+
+ /**
+ * get_event_date: make the event date human readable
+ *
+ * @param string $sdate start date
+ * @param string $edate end date
+ * @param string $dateType dateType Postgres,etc
+ * @param boolean $microFormat use microformating on output
+ *
+ * @return string
+ * @access public
+ */
+ function get_event_date(
+ $sdate,
+ $edate,
+ $dateType,
+ $microFormat = false
+ ) {
+ switch($dateType) {
+ case "Postgres":
+ $postgresPattern = "/([0-9]{1,2})[/-]([0-9]{1,2})[/-]([0-9]{4})/";
+ if (preg_match($postgresPattern, $sdate, $spt)) {
+ $mon = $spt[1];
+ $day = $spt[2];
+ $yr = $spt[3];
+ }
+
+ if (preg_match($postgresPattern, $edate, $ept)) {
+ $mon2 = $ept[1];
+ $day2 = $ept[2];
+ $yr2 = $ept[3];
+ }
+ break;
+ case "eventstamp":
+ case "timestamp":
+ $mon = date("m",$sdate);
+ $day = date("d",$sdate);
+ $yr = date("Y",$sdate);
+ $mon2 = date("m",$edate);
+ $day2 = date("d",$edate);
+ $yr2 = date("Y",$edate);
+ break;
+ }
+
+ $start = mktime(0,0,0,$mon,$day,$yr);
+ $end = mktime(0,0,0,$mon2,$day2,$yr2);
+ if ($day == $day2 && $mon == $mon2 && $yr == $yr2) {
+ $dateparam = "M j, Y";
+ $dateBegin = date($dateparam, $start) ;
+ $dateEnd = "";
+ } elseif ($day == $day2 AND $mon == $mon2 AND $yr != $yr2) {
+ $dateparam1 = "M j, Y -";
+ $dateparam2 = "Y";
+ $dateBegin = date($dateparam1, $start);
+ $dateEnd = date($dateparam2, $end);
+ } elseif ($day != $day2 AND $mon == $mon2 AND $yr == $yr2) {
+ $dateparam1 = "M j -";
+ $dateparam2 = "j, Y";
+ $dateBegin = date($dateparam1, $start);
+ $dateEnd = date($dateparam2, $end);
+ } elseif ($day != $day2 AND $mon == $mon2 AND $yr != $yr2) {
+ $dateparam1 = "M j, Y -";
+ $dateparam2 = "M j, Y";
+ $dateBegin = date($dateparam1, $start);
+ $dateEnd = date($dateparam2, $end);
+ } elseif ($yr == $yr2) {
+ $dateparam1 = "M j -";
+ $dateparam2 = "M j, Y";
+ $dateBegin = date($dateparam1, $start);
+ $dateEnd = date($dateparam2, $end);
+ } else {
+ $dateparam1 = "M j, Y -";
+ $dateparam2 = "M j, Y";
+ $dateBegin = date($dateparam1, $start);
+ $dateEnd = date($dateparam2, $end);
+ }
+ if ($microFormat) {
+ $dateBegin = '
+ ' .
+ $dateBegin . '
+ ';
+ $dateEnd
+ = ($dateEnd)
+ ? '
+ ' .
+ $dateEnd . '
+ '
+ : '';
+ }
+ return $dateBegin." ".$dateEnd;
+ }
+
+ // }}}
+ // {{{ get_headlines()
+
+ function get_headlines()
+ {
+ $headlines = array();
+ $query = "
+ SELECT id,intro,feature_intro,description,image
+ FROM bus_category
+ WHERE featured = 't'
+ AND active = 't'
+ ORDER BY parent,pos;";
+ if( $data = $this->DB->pgsql_select( $query ) ){
+ foreach( $data as $row ){
+ $headlines[] = array(
+ 'href' => $this->get_seo_url($row['id']),
+ 'img' => ($row['image']) ? THUMB . $row['image']: '',
+ 'header' => $row['feature_intro'],
+ 'descr' => GLM_TOOLBOX::make_teaser($row['description'], 150, true));
+ }
+ }
+ return $headlines;
+ }// }}}
+ // {{{ get_home_events()
+ /**
+ * get_home_events: get events flaged as home events
+ *
+ * @uses GLM_TEMPLATE::get_event_date()
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return void
+ * @access public
+ **/
+ public function get_home_events($limit = 3)
+ {
+ $query = "
+ SELECT id, header, descr, bdate, edate, img,
+ to_char(bdate, 'Mon - DDth') AS sdate
+ FROM event
+ WHERE visable='t'
+ AND edate >= current_date
+ AND home='t'
+ ORDER BY bdate asc, edate asc";
+ $data = $this->DB->db_auto_get_data($query);
+ if(is_array($data)) {
+ foreach($data as $key => $value) {
+ $id = $value['id'];
+ $header = $value['header'];
+ $title = strip_tags(addslashes($header));
+ $descr = GLM_TOOLBOX::make_teaser($value['descr'], 250, true);
+ $sdate = strtotime($value['bdate']);
+ $edate = strtotime($value['edate']);
+ $month = date('n',$sdate);
+ $year = date('Y',$sdate);
+ $dates = GLM_TEMPLATE::get_event_date($sdate,$edate,"timestamp");
+ $href = BASE_URL.'index.php?catid='.EVENT_PAGE."&month={$month}&year={$year}&eventid={$id}";
+ $area_events[] = array(
+ 'href' => $href,
+ 'bdate' => $value['sdate'],
+ 'dates' => $dates,
+ 'header' => $header,
+ 'descr' => $descr,
+ );
+ }
+ return $area_events;
+ } else {
+ return null;
+ }
+ }// }}}
+ // {{{ get_hotspecials()
+
+ function get_hotspecials(){
+ $query = "
+ SELECT id, intro, feature_intro
+ FROM bus_category
+ WHERE featured = 't'
+ order by parent, pos;";
+ if ($data = $this->DB->pgsql_select( $query ) ){
+ $out = '
+
Hot specials ';
+ foreach ($data as $row) {
+ $intro = htmlspecialchars(strip_tags($row['intro']));
+ $intro_text = '
'.htmlspecialchars(strip_tags($row['feature_intro'] ) ).'
';
+ $out .= '
';
+ }
+ $out .= '
';
+ }
+ return $out;
+ }
+
+ // }}}
+ // {{{ get_main_nav()
+
+ function get_main_nav()
+ {
+ $query = "select id,category
+ from bus_category
+ where parent = 0
+ and id not in (".HOME_ID.",".MEMBERS_CATEGORY.",7,8,9)
+ and active = 't'
+ order by pos";
+ if ($data = $this->DB->pgsql_select( $query ) ){
+ $out = '';
+ }
+ return $out;
+ }
+
+ // }}}
+ // {{{ get_menu_array()
+
+
+ /**
+ * get_menu_array: like get_menu_string but returns an array
+ *
+ * @uses GLM_TEMPLATE::sort_childs()
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function get_menu_array()
+ {
+ $query = "
+ SELECT id, parent, category
+ FROM bus_category
+ WHERE id != 0 {$this->active_query}
+ order by parent, pos";
+ $data = $this->DB->db_auto_get_data($query);
+ $newdata = GLM_TEMPLATE::sort_childs($data);
+ return $newdata;
+ }
+
+ // }}}
+ // {{{ get_main_cats()
+
+ /**
+ * get_main_cats
+ *
+ * @access public
+ * @return string
+ */
+ function get_main_cats()
+ {
+ static $main_cats_array;
+ if (!is_array($main_cats_array)) {
+ $query = "
+ SELECT id, category
+ FROM bus_category
+ WHERE parent = 0
+ order by pos;";
+ if ($data = $this->DB->db_auto_get_data($query)) {
+ foreach ($data as $row) {
+ $main_cats_array[$row['id']] = htmlentities(strip_tags($row['category']),ENT_QUOTES,'UTF-8');
+ }
+ }
+ }
+ return $main_cats_array;
+ }
+
+ // }}}
+ // {{{ get_menu_string()
+
+ /**
+ * get_menu_string:get categories for the phplayermenu
+ *
+ * @uses GLM_TEMPLATE::sort_childs()
+ * @uses GLM_TEMPLATE::convert_to_thread()
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ **/
+ function get_menu_string()
+ {
+ $query = "
+ SELECT id, parent, category
+ FROM bus_category
+ WHERE id != 0 {$this->active_query}
+ ORDER BY parent, pos";
+ $data = $this->DB->db_auto_get_data($query);
+ $newdata = GLM_TEMPLATE::sort_childs($data);
+ $string = GLM_TEMPLATE::convert_to_thread($newdata,$newdata[0]);
+ return $string;
+ }
+
+ // }}}
+ // {{{ get_id_from_name()
+
+ /**
+ * getIdFromName:
+ *
+ * @param string $name:
+ * @param string $table:
+ * @param object $DB:
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @deprecated Don't use this! THIS IS A WARNING (this funcion will be gone next time)
+ * @return string
+ * @access public
+ */
+ function get_id_from_name( $name, $table, &$DB)
+ {
+ if ($name == "") {
+ return 0;
+ }
+ if (is_numeric($name)) {
+ return $name;
+ }
+ $pattern = "/(.*)/$/";
+ if (preg_match($pattern, $name, $tmp)) {
+ $name = $tmp[1];
+ }
+ $category = "category";
+ $pattern = "/-([0-9]*)$/";
+ if (preg_match($pattern, $name, $tmp)) {
+ $id = $tmp[1];
+ return $id;
+ }
+ // should already be returning id at this point
+ // putting the _id on the end of all url's as
+ // the other way is very inifiecent for the database.
+ $name = str_replace( "-"," ",$name );
+ $query = "select id from $table where trim(lower(replace(replace(replace(replace(replace(replace($category,'\'',''),'/',''),'-',' '),'#',''),'&',''),'?',''))) = '".trim(strtolower($name))."'";
+ $data = $DB->db_auto_get_data($query);
+ if (is_array($data)) {
+ foreach ($data as $key => $val) {
+ $catid = $val['id'];
+ }
+ return $catid;
+ } else {
+ return 0;
+ }
+ }
+
+ // }}}
+ // {{{ get_id_from_path_info()
+
+ /**
+ * get_id_from_path_info: takes the path_info and gets a catid from bus_category table
+ * NOTE: not used.
+ *
+ * @deprecated using .htaccess file for this when using seo url's
+ * @return int catid
+ * @access public
+ **/
+ function get_id_from_path_info()
+ {
+ return false;
+ }
+
+ // }}}
+ // {{{ get_image_path()
+
+ /**
+ * get_image_path: get image path from the size used
+ *
+ * @uses MIDSIZED_PATH
+ * @uses RESIZED_PATH
+ * @uses THUMB_PATH
+ *
+ * @return path for images
+ * @access public
+ **/
+ function get_image_path()
+ {
+ if (strstr($this->img_size, 'midsized/')) {
+ return MIDSIZED_PATH;
+ }
+ if (strstr($this->img_size,'resized/')) {
+ return RESIZED_PATH;
+ }
+ if (strstr($this->img_size,'thumb/')) {
+ return THUMB_PATH;
+ }
+ }
+
+ // }}}
+ // {{{ get_listings()
+
+ /**
+ * template_parser:This function creates data
+ * and items arrays and does the output for the page.
+ *
+ * @uses DELUXE_TOOLBOX
+ * @uses GLM_TEMPLATE::$items
+ * @uses GLM_TEMPLATE::get_template()
+ * @uses GLM_TEMPLATE::get_all()
+ * @uses GLM_TEMPLATE::load_static_page()
+ * @uses GLM_TEMPLATE::clean_text()
+ * @uses GLM_TEMPLATE::$item_files
+ *
+ * @return void
+ * @access public
+ */
+ function get_listings()
+ {
+ if ($paragraphContent = $this->cache->get('paragraphs-'.$this->catid, 'Toolbox')) {
+ return $paragraphContent;
+ } else {
+ // grab category and items into data and items respectfully
+ if (DELUXE_TOOLBOX ) {
+ $this->get_template( "list" );
+ }
+
+ if (!is_array($this->items)) {
+ $this->get_all(2);
+ }
+
+ $output = '';
+ // load any static category page from the static directory
+ // hard codded content would have $catid.phtml page for it
+ //$output .= $this->load_static_page();
+ if (is_array($this->items)) {
+ $anchors = array();
+ foreach($this->items as $key=>$val) {
+ // building array with links to each paragraph
+ $name = trim(strip_tags($val["name"]));
+ if ($name && $this->section_links) {
+ $anchors[] = ''.strip_tags($val["name"]).' ';
+ }
+ // items can be moved around as needed
+ $output .= ''."\n";
+ $output .= $val["name"];
+ $output .= $val["image"];
+ $output .= $val["address"];
+ $output .= $val["description"];
+ $output .= $val["contactname"];
+ $output .= $val["email"];
+ $output .= $val["phone"];
+ $output .= $val["fax"];
+ $output .= $val["url"];
+ if ( isset($this->item_files[$val['id']])
+ && is_array($this->item_files[$val['id']])
+ ) {
+ $output .= implode('', $this->item_files[$val['id']]);
+ }
+ if ($val['back_to_top'] == 't') {
+ $output .= '
Back to Top ';
+ }
+ $output .= "
"."\n";
+ }
+ // assign array of links to $this->sectionAnchors
+ $this->sectionAnchors = $anchors;
+ }
+ $output = GLM_TEMPLATE::clean_text($output);
+ $this->cache->save($output, 'paragraphs-'.$this->catid, 'Toolbox');
+ return $output;
+ }
+ }
+
+ // }}}
+ // {{{ get_page()
+
+ /**
+ * get_page: replacing template_parser with get_page function
+ *
+ * @uses GLM_TEMPLATE::get_category() For building the main page section
+ * @uses GLM_TEMPLATE::get_listings() For building out the paragraph sections
+ *
+ * @return string $out NEED to echo results of this function
+ * @access public
+ */
+ function get_page($showimg = 1, $showdiv = 1)
+ {
+ if (isset($_REQUEST['sitemap']) && $_REQUEST['sitemap'] == 1) {
+ return $this->get_sitemap();
+ } elseif ( isset($_REQUEST['zipcode'])
+ && is_numeric($_REQUEST['zipcode'])
+ ) {
+ $this->distance = ''.$this->get_distance_from_traverse($_REQUEST['zipcode']).' miles from '.$_REQUEST['zipcode'].'
';
+ }
+
+ if ($this->page_status != 'Good') {
+ return 'Sorry this page is Down! ';
+ }
+
+ if ( defined('GOOGLE_SEARCH')
+ && GOOGLE_SEARCH
+ && isset($_REQUEST['query'])
+ && $_REQUEST['query']
+ ) {
+ $out = '
';
+ } elseif ( isset($_REQUEST['member_id'])
+ && is_numeric($_REQUEST['member_id'])
+ && !$this->Member->memberSections[$this->catid]
+ ) {
+ $out = $this->load_static_page();
+ } elseif ( defined('MEMBERS_DB')
+ && MEMBERS_DB
+ && isset($this->Member->memberSections)
+ && $this->Member->memberSections[$this->catid]
+ ) {
+ $GLOBALS['bottomScripts'][]
+ = BASE_URL . 'Toolkit/Members/libjs/travel-list.js';
+ $out = $this->get_bread_crumbs($this->catid);
+ if ( !isset($_REQUEST['member_id'])
+ && !isset($_REQUEST['search'])
+ && !isset($_REQUEST['start'])
+ ) {
+ $out .= $this->get_category($showimg,0);
+ $pageHeader = $this->data['intro'];
+ $out .= '';
+ $out .= $pageHeader;
+ // $out .= $category;
+ $out .= '
';
+ }
+
+ // application configuration
+ $conf = new Config;
+ $root = $conf->parseConfig(
+ BASE . 'Toolkit/Members/config.ini',
+ 'IniFile'
+ );
+
+ if (isset($_GET['member_id']) && ctype_digit($_GET['member_id'])) {
+ try {
+ $profile = new Toolkit_Members_ProfilePage(
+ Toolkit_Database::getInstance(),
+ new Toolkit_Image_Server(),
+ $_GET['member_id']
+ );
+ $profile->setCatId($this->catid);
+ $profile->setConfig($root);
+ $flexy = new HTML_Template_Flexy(
+ Toolkit_Members::getFlexyOptions()
+ );
+ $cache = new Cache_Lite(Toolkit_Members::getCacheOptions());
+ $out .= $profile->toHtml($flexy, $cache, MEMBER_RESIZED);
+ } catch (PEAR_Exception $e) {
+ return Toolkit_Common::handleError($e);
+ }
+ } elseif ( isset($_GET['search'])
+ || $this->Member->hideUserSearchForm()
+ ) {
+ if ($this->Member->includeMemberMap()) {
+ $googleMap = new Toolkit_Members_Map();
+ $out .= $googleMap->toHtml();
+ }
+
+ $searchQuery = new Toolkit_Members_SearchQueryGenerator(
+ true,
+ $root
+ );
+ $sql = $searchQuery->getQuery($this->dbh);
+ $searchList = new Toolkit_Members_SearchList(
+ $this->dbh,
+ 50,
+ null,
+ null,
+ true
+ );
+
+ $searchList->setConfig($root);
+ $searchList->setQuery($sql);
+ $searchList->setDefaultSort(array('member_name' => 'ASC'));
+ // rendering engine to use
+ $rEngine = new Structures_DataGrid_Renderer_Flexy();
+ // template options to use for template engine
+ $tplOpts = Toolkit_Members::getFlexyOptions();
+ // templating engine to use
+ $tEngine = new HTML_Template_Flexy($tplOpts);
+ $rEngine->setContainer($tEngine);
+
+ $out .= $searchList->toHtml($rEngine);
+ } else {
+ if ($this->Member->includeMemberMap()) {
+ $googleMap = new Toolkit_Members_Map();
+ $out .= $googleMap->toHtml();
+ }
+
+ $action = BASE_URL . "index.php?catid={$this->catid}";
+ $form = new Toolkit_Members_UserSearchForm(
+ 'SearchForm',
+ 'get',
+ $action,
+ null,
+ null,
+ true
+ );
+ $res = $form->setCatId($this->catid);
+ if (!PEAR::isError($res)) {
+ $form->setPageMemberCategories($this->dbh);
+ $form->configureForm($this->dbh, $root);
+ $out .= $form->toHtml(Toolkit_Members::getFlexyOptions());
+ } else {
+ return Toolkit_Common::handleError($res);
+ }
+ }
+
+ if ( !isset($_REQUEST['member_id'])
+ && !isset($_REQUEST['search'])
+ && !isset($_REQUEST['start'])
+ ) {
+ $out .= $this->load_static_page();
+ $out .= $this->get_listings();
+ }
+
+ if (PHOTO_GALLERY) {
+ $out .= $this->photo_module();
+ }
+ } else {
+ $breadCrumbs = $this->get_bread_crumbs($this->catid);
+ $category = $this->get_category($showimg, 0);
+ $pageHeader = $this->data['intro'];
+ $static = $this->load_static_page();
+ $listings = $this->get_listings();
+ if (!$links = $this->cache->get('sectionLinks-'.$this->catid, 'Toolbox')) {
+ // generation of the section links to each paragraph
+ if (is_array($this->sectionAnchors)) {
+ $links = '';
+ foreach ($this->sectionAnchors as $anchors) {
+ $links .= ''.$anchors.' ';
+ }
+ $links .= ' ';
+ $this->cache->save($links, 'sectionLinks-'.$this->catid, 'Toolbox');
+ }
+ }
+ $out = $breadCrumbs;
+ $out .= '';
+ $out .= $pageHeader;
+ $out .= $links;
+ $out .= $category;
+ $out .= '
';
+ $out .= $static;
+ $out .= $listings;
+
+ if ($this->_hasCouponsAssignedToPage()) {
+ $out .= $this->_getCouponWidget();
+ }
+
+ if (PHOTO_GALLERY) {
+ $out .= $this->photo_module();
+ }
+ }
+ return $out;
+ }
+
+ // }}}
+ // {{{ get_page_header_image()
+
+ function get_page_header_image(){
+ $headers[5] = 'accommodations';
+ $headers[21] = 'arts';
+ $headers[22] = 'beaches';
+ $headers[16] = 'golf';
+ $headers[20] = 'guest';
+ $headers[4] = 'outdoor';
+ $headers[43] = 'reservations';
+ $headers[3] = 'things';
+ $headers[18] = 'winaries';
+ $headers[7] = 'meeting';
+ $headers[8] = 'tour';
+ $headers[9] = 'media';
+ $headers[33] = 'events';
+ $this->header_images = $headers;
+ $top_parent = $this->get_top_parent($this->catid);
+ if ($top_parent && $this->catid != HOME_ID) {
+ if ($_SERVER['HTTPS'] == "on") {
+ $base_url = BASE_SECURE_URL;
+ } else {
+ $base_url = BASE_URL;
+ }
+
+ if ($_SERVER['HTTPS'] != "on") {
+ return( '
+
+' );
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+
+ // }}}
+ // {{{ get_parent()
+
+ /**
+ * get_parent: get parent for this category
+ *
+ * @param integer $catid: id
+ * @param object $DB: database obj
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return int $parent
+ * @access public
+ **/
+ function get_parent($catid,&$DB)
+ {
+ $query = "
+ SELECT parent
+ FROM bus_category
+ WHERE id = $catid
+ ORDER BY pos";
+ $data = $DB->db_auto_get_data($query);
+ return $data[0]["parent"];
+ }
+
+ // }}}
+ // {{{ get_parent_id ()
+
+ function get_parent_id($id)
+ {
+ if (is_numeric($id)) {
+ $query = "select parent from bus_category where id = $id";
+ if ($data = $this->DB->pgsql_select($query)) {
+ return $data[0]['parent'];
+ }
+ }
+ }
+
+ // }}}
+ // {{{ get_seo_url()
+
+ /**
+ * get_seo_url:
+ * grab category part of the search engine friendly url
+ * looks at define for seo_url to see weather to use the seach engine friendly url's or not
+ *
+ * @param integer $id:
+ * @param boolean $slash = 1 : to put a slash on end or not
+ * @uses BASE_URL
+ * @uses SEO_URL
+ * @uses HOME_ID
+ * @uses GLM_TEMPLATE::$php_ext
+ * @uses GLM_TEMPLATE::set_name_url()
+ * @uses GLM_TEMPLATE::get_category_name()
+ * @uses GLM_TEMPLATE::get_base_url()
+ *
+ * @return string $url for page.
+ * @access public
+ **/
+ function get_seo_url($id, $slash = 1)
+ {
+ if ($id == HOME_ID &&
+ $GLOBALS['GLM_SERVER_ID'] != 'devsys.gaslightmedia.com') {
+ return BASE_URL;
+ } elseif ($id == HOME_ID &&
+ $GLOBALS['GLM_SERVER_ID'] == 'devsys.gaslightmedia.com') {
+ return BASE_URL.'index.php';
+ }
+ if ( isset($this->category_toolbox)
+ && is_array($this->category_toolbox)
+ && in_array($id, $this->category_toolbox)
+ ) {
+ $category_id = array_search($id, $this->category_toolbox);
+ $url = BASE_URL.'member.php?category_id='.$category_id;
+ return $url;
+ }
+ if (in_array($id, array(
+ MEMBERS_PROFILE_FORM_PAGE,
+ MEMBERS_COUPONS_PAGE,
+ MEMBERS_EVENTS_PAGE,
+ MEMBERS_REPORTS_PAGE
+ ))) {
+ switch ($id) {
+ case MEMBERS_PROFILE_FORM_PAGE :
+ return $baseurl . 'memberdb/index.php?Option=Member&Action=Edit';
+ break;
+ case MEMBERS_COUPONS_PAGE :
+ return $baseurl . 'memberdb/index.php?Option=Coupons&Action=List';
+ break;
+ case MEMBERS_EVENTS_PAGE :
+ return $baseurl . 'memberdb/index.php?Option=Events&Action=List';
+ break;
+ case MEMBERS_REPORTS_PAGE :
+ return $baseurl . 'memberdb/index.php?Option=Reports&Action=List';
+ break;
+ }
+ }
+ if (SEO_URL) {
+ if ($id == 142) {
+ $base_url = BASE_SECURE_URL;
+ } else {
+ $base_url = BASE_URL;
+ }
+ $url = $base_url;
+ if (defined("SHORT_URLS") && SHORT_URLS) {
+ static $ShortURL;
+ if (!$ShortURL) {
+ $ShortURL = new Toolkit_ShortURL($this->dbh);
+ }
+ $short_url = $ShortURL->getShortUrl($id);
+ if ($short_url) {
+ return $base_url.$short_url . '/';
+ }
+ }
+ $url .= GLM_TEMPLATE::set_name_url(GLM_TEMPLATE::get_category_name($id, "bus_category", $this->DB));
+ $url = htmlspecialchars(strip_tags($url));
+ if ($slash) {
+ $url .= '/';
+ }
+ } else {
+ $url = $this->get_base_url($id);
+ if ($url) {
+ if ($id == 142) {
+ $url = BASE_SECURE_URL.$url;
+ }else{
+ $url = BASE_URL.$url;
+ }
+ $url .= $this->php_ext.'?catid='.$id;
+ } else {
+ $url = BASE_URL;
+ }
+ }
+
+ return $url;
+ }
+
+ // }}}
+ // {{{ get_side_nav()
+
+ function get_side_nav($parent = 0)
+ {
+ if ($navContent = $this->cache->get($this->catid, 'Nav')) {
+ return $navContent;
+ } else {
+ $qs = "
+ SELECT id, category, intro
+ FROM bus_category
+ WHERE parent = :parent {$this->active_query}
+ ORDER BY pos";
+ try {
+ $stmt = $this->dbh->prepare($qs);
+ $stmt->bindParam(":parent", $parent, PDO::PARAM_INT);
+ $stmt->execute();
+ $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ } catch(PDOException $e) {
+ return Toolkit_Common::handleError($e);
+ }
+ if (!is_array($data)) {
+ return false;
+ } else {
+ $return = '';
+ foreach ($data as $key => $row) {
+ $url = $this->get_seo_url($row['id']);
+ $title = strip_tags(addslashes($row['intro']));
+ $return .= 'catid == $row['id']) {
+ $return .= ' id="current"';
+ }
+ $return .= '>' .
+ htmlentities($row['category'],ENT_QUOTES,'UTF-8')." ";
+ $hasSubs = $this->has_subs($row['id'], $this->DB);
+ $isSubId = $this->is_sub_id($this->catid, $row['id'], $this->DB);
+ $isPage = $this->catid == $row['id'];
+
+ if ($hasSubs && ($isSubId || $isPage)) {
+ $ret2 = $this->get_side_nav($row['id']);
+ $return .= $ret2;
+ }
+ $return .= ' ';
+ }
+ $main_cats = $this->get_main_cats();
+ if ($main_cats[$parent]) {
+ $return = ''.$this->get_catheader($parent, $this->DB).'
+ ';
+ $this->cache->save($return, $this->catid, 'Nav');
+ return $return;
+ } else {
+ $return = "\n\n";
+ return $return;
+ }
+ }
+ }
+ }
+
+ // }}}
+ // {{{ get_sitemap()
+
+ function get_sitemap(){
+ // sitemap.inc goes here
+ // maybe make a sitemap class
+ }
+
+ // }}}
+ // {{{ get_sub_nav()
+
+ /**
+ * get_sub_nav:
+ * @param integer $catid:
+ * @param object $DB:
+ *
+ * @uses GLM_TEMPLATE::get_parent()
+ * @uses GLM_TEMPLATE::get_seo_url()
+ * @uses GLM_TEMPLATE::is_sub_id()
+ * @uses GLM_TEMPLATE::get_sub_nav()
+ * @uses GLM_TEMPLATE::has_subs()
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ **/
+ function get_sub_nav($catid,&$DB)
+ {
+ $parentid = GLM_TEMPLATE::get_parent($catid, $DB);
+ //echo $parentid.' ';
+ $query = "SELECT id,category,intro FROM bus_category WHERE parent = $parentid ".$this->active_query." ORDER BY pos";
+ $data = $DB->db_auto_get_data($query);
+ if (is_array($data)) {
+ $output = '';
+ $counter = 1;
+ foreach($data as $key=>$val) {
+ $url = $this->get_seo_url( $val['id'] );
+ $title = strip_tags(addslashes($val['intro']));
+ if ( GLM_TEMPLATE::is_sub_id($catid, $parentid, $DB)
+ && ( GLM_TEMPLATE::is_sub_id($catid, $val['id'], $DB)
+ || $val['id'] == $catid)
+ ) {
+ $output .= '
';
+ } else {
+ $output .= ' ';
+ }
+ $output .= $val["category"];
+ $output .= ' ';
+ if ( GLM_TEMPLATE::is_sub_id($catid, $val['id'], $DB)
+ && GLM_TEMPLATE::has_subs($val['id'], $DB)
+ ) {
+ $output .= GLM_TEMPLATE::get_sub_nav(
+ $val["id"],
+ $DB,
+ $catid
+ );
+ }
+ }
+ $output .= '
';
+ $output = GLM_TEMPLATE::clean_text($output);
+ echo $output;
+ }
+ return false;
+ }
+
+ // }}}
+ // {{{ get_template()
+
+ /**
+ * get_template: get the template type of the bus_category
+ * @param mixed $type : 'cat' or 'list'
+ *
+ * @uses GLM_DB::db_auto_get_data()
+ * @uses GLM_TEMLATE::img_align()
+ * @uses GLM_TEMLATE::img_alternate()
+ * @uses GLM_TEMLATE::$template
+ *
+ * @return void
+ * @access public
+ */
+ function get_template($type)
+ {
+ $query = "select template from bus_category where id = ".$this->catid;
+ $data = $this->DB->db_auto_get_data($query);
+ switch ($type) {
+ case "cat" :
+ switch ($data[0]['template']) {
+ case "5" :
+ case "4" :
+ case "2" :
+ $this->img_align = "left";
+ break;
+
+ default:
+ $this->img_align = "right";
+ break;
+ }
+ break;
+
+ case "list" :
+ switch( $data[0]['template'] ) {
+ case "6" :
+ case "2" :
+ $this->img_align = "left";
+ $this->img_alternate = 0;
+ break;
+
+ case "5" :
+ case "1" :
+ $this->img_align = "right";
+ $this->img_alternate = 0;
+ break;
+
+ case "4" :
+ $this->img_align = "right";
+ $this->img_alternate = 1;
+ break;
+
+ case "3":
+ $this->img_align = "left";
+ $this->img_alternate = 1;
+ break;
+
+ default:
+ break;
+ }
+ break;
+ }
+ return $this->template = $data[0]['template'];
+ }
+
+ // }}}
+ // {{{ get_top_parent()
+
+ /**
+ * get_top_parent:Get the highest level parent id (not 0 )for the category.
+ *
+ * NOTICE: This is ment to get the top level parent not the parent of the id given.
+ *
+ * @param integer $id: The catid for the page.
+ * @param object $DB: obj
+ * @uses GLM_TEMPLATE::get_top_parent()
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return int $parent
+ * @access public
+ */
+ function get_top_parent($id)
+ {
+ if ($id == 0 ){
+ return 0;
+ }
+ $qs = "select parent from bus_category where id = $id";
+ $parentrow = $this->DB->db_auto_get_data( $qs );
+ if ($parentrow[0]['parent'] == 0 ){
+ return $id;
+ } else {
+ return $this->get_top_parent($parentrow[0]['parent']);
+ }
+ }
+
+ // }}}
+
+ // {{{ _getCouponWidget()
+
+ private function _getCouponWidget()
+ {
+ $page = new Toolkit_Coupons_PageWidget(
+ new Toolkit_Coupons_WebCouponFactory(),
+ new Toolkit_Coupons_Coupons()
+ );
+
+ $flexyOpts = Toolkit_Coupons_Controller::getFlexyOptions();
+ $tEngine = new HTML_Template_Flexy($flexyOpts);
+
+ $page->addPageCategories($this->dbh, $this->catid);
+
+ $searchForm = new Toolkit_Coupons_UserSearch(
+ 'coupon_search',
+ 'get',
+ BASE_URL . 'index.php'
+ );
+ $searchForm->configureForm($this->dbh, $this->catid);
+
+ $page->setSearchForm($searchForm);
+
+ $couponForm = new HTML_QuickForm(
+ 'coupon_form',
+ 'post',
+ BASE_URL . 'Toolkit/Coupons/print.php'
+ );
+ $renderer = $couponForm->defaultRenderer();
+ $renderer->clearAllTemplates();
+ return $page->toHtml($couponForm, $tEngine, 'coupons.html');
+ }
+
+ // }}}
+ // {{{ _hasCouponsAssignedToPage()
+
+ private function _hasCouponsAssignedToPage()
+ {
+ try {
+ $sql = "
+ SELECT count(*) AS total
+ FROM coupon_categories2toolbox_pages
+ WHERE toolbox_catid = :catid";
+
+ $stmt = $this->dbh->prepare($sql);
+ $stmt->bindParam(':catid', $this->catid, PDO::PARAM_INT);
+ $stmt->execute();
+
+ $row = $stmt->fetch();
+
+ return (bool) $row['total'];
+ } catch (PDOException $e) {
+ Toolkit_Logger::logException('DB Error', $e);
+ return false;
+ }
+ }
+
+ // }}}
+
+ // {{{ is_sub_id()
+
+ /**
+ * is_sub_id:Check to see if catid is sub of category
+ *
+ * @param integer $catid: the catid looking at
+ * @param integer $category: to see if it is in category
+ * @param object $DB: Db object reference
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return bool
+ * @access public
+ */
+ function is_sub_id($catid,$category,&$DB)
+ {
+ if (!is_numeric($catid)) {
+ return false;
+ }
+
+ if ($category == $catid)
+ {
+ return true;
+ }
+
+ $query = "select id,parent from bus_category where id = $catid";
+ $data = $DB->db_auto_get_data($query);
+ $parent = $data[0]['parent'];
+ if ($parent == 0) {
+ return false;
+ } else {
+ return GLM_TEMPLATE::is_sub_id($parent, $category, $DB);
+ }
+ }
+
+ // }}}
+
+ // {{{ keyword_replace()
+
+ /**
+ * keyword_replace:
+ *
+ * @param string $string:
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function keyword_replace($string)
+ {
+ //return $string;
+ if ($search = strstr($string,"{")) {
+ if (preg_match("/\{([A-Z0-9\&\-\,\'\" ]*)\}/i",$string,$needle)) {
+ if ($needle[0] != "") {
+ $qs = "
+ SELECT id, category
+ FROM bus_category
+ WHERE trim(keyword) = '".trim($needle[1])."'";
+
+ $keyres = $this->DB->db_auto_get_data($qs);
+ $parent = $this->get_top_parent($keyres[0]['id']);
+ $url = $this->get_seo_url( $keyres[0]['id'] );
+ $replacement = "".htmlspecialchars($keyres[0]['category'])." ";
+ $string = str_replace($needle[0],$replacement,$string);
+ }
+ } else {
+ return $string;
+ }
+ if ($search = strstr($string,"{")) {
+ return $this->keyword_replace($string);
+ }
+ }
+ return $string;
+ }
+
+ // }}}
+
+ // {{{ load_static_page()
+
+ /**
+ * load_static_page:using object buffer include the page $catid.phtml from static dir
+ and return it as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function load_static_page()
+ {
+ if (file_exists(BASE . "static/{$this->catid}.phtml")) {
+ ob_start();
+ include BASE . "static/{$this->catid}.phtml";
+ $text = ob_get_contents();
+ ob_end_clean();
+ return $text;
+ }
+ }
+
+ // }}}
+
+ // {{{ make_ul_menu()
+
+ /**
+ * make_ul_menu: create url list of categories
+ *
+ * @param integer $parent parent to start from
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function make_ul_menu($parent = 0)
+ {
+ $qs = "
+ SELECT id, category, intro
+ FROM bus_category
+ WHERE parent = $parent
+ AND id <> ".MEMBERS_ONLY_CATEGORY."
+ {$this->active_query}
+ order by pos";
+ $data = $this->DB->db_auto_get_data($qs);
+
+ if (!is_array($data)) {
+ return false;
+ } else {
+ $return = '';
+ foreach ( $data as $key => $row ) {
+ $url = $this->get_seo_url( $row['id'] );
+ $title = strip_tags(addslashes($row['intro']));
+ $return .= "\tcatid == $row['id']) {
+ $return .= ' id="current"';
+ }
+ $return .= '>' . htmlentities($row['category'], ENT_QUOTES, 'UTF-8') . ' ';
+ $hasSubs = $this->has_subs($row['id'], $this->DB);
+ $isSubId = $this->is_sub_id($this->catid, $row['id'], $this->DB);
+ $isPage = $this->catid == $row['id'];
+ if ($hasSubs && ($isSubId || $isPage)) {
+ $ret2 = $this->make_ul_menu($row['id']);
+ $return .= $ret2;
+ }
+ $return .= " \n";
+ }
+ $main_cats = $this->get_main_cats();
+ if ( (isset($parent) && $parent != 0)
+ || ( isset($main_cats)
+ && isset($main_cats[$parent])
+ && $main_cats[$parent]
+ )
+ ) {
+ return "\n";
+ } else {
+ return "\n";
+ }
+ }
+ }
+
+ // }}}
+ // {{{ meta_tags()
+
+ /**
+ * meta_tags: create the meta description content for this page.
+ * this is taken from the category description.
+ * this should be only done for all but the home page.
+ * $meta = ( $catid != 1 ) ? $toolbox->meta_tags() : '';
+ *
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function meta_tags()
+ {
+ $query = "
+ SELECT meta_descr,description
+ FROM bus_category
+ WHERE id = :id";
+ try {
+ $stmt = $this->dbh->prepare($query);
+ $stmt->bindParam(":id", $this->catid, PDO::PARAM_INT);
+ $stmt->execute();
+ $data = $stmt->fetch();;
+ } catch(PDOException $e) {
+ echo ''.print_r($e, true).' ';
+ die($e->getMessage());
+ }
+ if ($data['meta_descr']) {
+ $description = htmlentities(trim(strip_tags($data['meta_descr'])), ENT_QUOTES, 'UTF-8');
+ } else {
+ $description = htmlentities(substr(trim(strip_tags($data['description'])), 0, 250),ENT_QUOTES,'UTF-8');
+ }
+ return $description;
+ }
+
+ // }}}
+
+ // {{{ page_status()
+
+ /**
+ * page_status
+ *
+ * tell if page is active, deleted or inactive
+ * this will redirect to the index.php page if the
+ * id has been deleted or not active
+ * it will display message about page not found.
+ *
+ * @param mixed $id
+ * @access public
+ * @return string
+ */
+ function page_status($id) {
+ if ($id == 9999) {
+ $this->page_status = 'Good';
+ return true;
+ }
+
+ if (empty($id)) {
+ return false;
+ }
+ if ($id == HOME_ID) {
+ $this->page_status = 'Good';
+ }
+ $query = "
+ SELECT id, active
+ FROM bus_category
+ WHERE id = :id";
+ try {
+ $stmt = $this->dbh->prepare($query);
+ $stmt->bindParam(":id", $id, PDO::PARAM_INT);
+ $stmt->execute();
+ $data = $stmt->fetch();
+ //echo ''.print_r($data, true).' ';
+ } catch(PDOException $e) {
+ echo ''.print_r($e, true).' ';
+ die($e->getMessage());
+ }
+
+ if (is_array($data)) {
+ if (!$data['active'] &&
+ !strstr($_SERVER['HTTP_REFERER'], 'admin/')) {
+ // page was deleted and no longer avail.
+ // give 404 redirect and go back to index page
+ header('HTTP/1.1 404 Not Found');
+ $this->page_status = 'Bad';
+ } else {
+ $this->page_status = 'Good';
+ }
+ } else {
+ // page was deleted and no longer avail.
+ // give 301 redirect and go back to index page
+ header('HTTP/1.1 301 Moved Permanently');
+ header('Location: '.BASE_URL);
+ exit();
+ }
+ }
+
+ // }}}
+ // {{{ photo_module()
+
+ /**
+ * photo_module
+ * Load the photo gallery into page
+ *
+ * @access public
+ * @return string
+ */
+ function photo_module()
+ {
+ $query = "
+ SELECT photocat_id
+ FROM photo_category_bus
+ WHERE buscat_id = $this->catid;";
+ $out = '';
+ if ($pData = $this->DB->db_auto_get_data($query)) {
+ if (count($pData) > 1) {
+ foreach ($pData as $pKey => $pVal) {
+ $photocatid[] = $pVal['photocat_id'];
+ }
+ $SINGLE_GALLERY = false;
+ } else {
+ $SINGLE_GALLERY = true;
+ $photocatid = $pData[0]['photocat_id'];
+ }
+ if (is_numeric($photocatid) || is_array($photocatid)) {
+ if (!$_REQUEST['photo_catid']) {
+ $_REQUEST['photo_catid'] = $photocatid;
+ }
+ $photoApp = new Toolkit_Photos_Display();
+ $out = $photoApp->toHTML();
+ }
+ }
+ return $out;
+ }
+
+ // }}}
+ // {{{ print_ancestors()
+
+ /**
+ * print_ancestors:print out the ancestors
+ * @param integer $catid: the id to start at.
+ *
+ * @return string
+ * @access public
+ */
+ function print_ancestors($catid)
+ {
+ return $this->get_bread_crumbs($catid);
+ }
+
+ // }}}
+
+ // {{{ set_active_query()
+
+ /**
+ * set_active_query: some toolboxes have an active flag some do not
+ * so this is to allow both with and without a flag.
+ *
+ * @uses ACTIVE_FLAG
+ *
+ * @return void
+ * @access public
+ **/
+ function set_active_query()
+ {
+ if (ACTIVE_FLAG) {
+ $this->active_query = " and active = 't'";
+ }
+ return $this->active_query;
+ }
+
+ // }}}
+ // {{{ set_address()
+
+ /**
+ * set_address:set_address
+ * {$address} {$city},{$state} {$zip}
+ * @param array $data: data contain the address info for display.
+ *
+ * @return string $address
+ * @access public
+ **/
+ function set_address($data)
+ {
+ $address = "";
+ if ($data["address"]) {
+ $address .= $data["address"];
+ }
+ if ($data["city"] && $data["state"] && $data["zip"]) {
+ $address .= ' '.$data["city"].', '.$data["state"].' '.$data["zip"];
+ } elseif ($data["city"] && $data["state"]) {
+ $address .= ' '.$data["city"].', '.$data["state"];
+ } elseif ($data["city"]) {
+ $address .= ' '.$data["city"];
+ }
+
+ if ($address != "") {
+ return ''.$address.'
';
+ }
+ }
+
+ // }}}
+ // {{{ set_body_tag()
+
+ /**
+ * @deprecated
+ */
+ function set_body_tag()
+ {
+ if ($this->catid != HOME_ID) {
+ $this->body_tag = ' id="inside"';
+ }
+ if (isset($_REQUEST['query']) && $_REQUEST['query']) {
+ switch (GLM_HOST_ID) {
+ case "devsys.gaslightmedia.com":
+ case "DEVELOPMENT":
+ $apikey = "ABQIAAAA4LuqJozzD0jiTLPhI0tT7xQUAAYHl_Rab4aEI5hGyHxlqR-rKxQMGKAdHLOEIFLI9wcDJjjSkJ7qng";
+ break;
+
+ case "ws1.gaslightmedia.com":
+ case "PRODUCTION":
+ $apikey = "ABQIAAAAWqyv9sBAgUBdsdOdgo7LsRQRzeqzQXKdvmJb4FZzpdF0AtrabhSiNxG27kD8OcNt7Ae6sNRUH1VXCA";
+ break;
+
+ default :
+ break;
+ }
+ $this->body_tag .= ' onload="OnLoad();"';
+ $this->scripts .= '
+ ';
+ $this->scripts .= ' ';
+ $this->scripts .= '';
+ }
+ }
+
+ // }}}
+ // {{{ set_catid()
+
+ /**
+ * set_catid:Set the class catid var
+ * @param integer $catid: $catid
+ *
+ * @deprecated using get_catid
+ * @return void
+ * @access public
+ **/
+ function set_catid($catid)
+ {
+ if (is_numeric($catid)) {
+ $this->catid = $catid;
+ } else {
+ $this->catid = 1;
+ }
+ }
+
+ // }}}
+ // {{{ set_contact()
+
+ /**
+ * set_contact:Set the contact string
+ * Contact Name: {$text}
+ *
+ * @param string $text: The text as string
+ * @param string $email: email if givin
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_contact($text, $email)
+ {
+ if ($email != "") {
+ $text = "";
+ } else {
+ $text = 'Contact Name: '.$text.'
';
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ set_DB()
+
+ /**
+ * set_DB: set the DB up to be that of the global one if it exists
+ *
+ * @param object $DB : the DB object
+ * @uses GLM_DB
+ *
+ * @return void
+ * @access public
+ **/
+ function set_DB(&$DB) {
+ if (isset($DB)) {
+ $this->DB = $DB;
+ } else {
+ $this->DB = new GLM_DB();
+ }
+ }
+
+ // }}}
+ // {{{ set_data()
+
+ /**
+ * call all class methods to set tho data elements
+ *
+ * This is hightly dependant on the three tables of bus bus_category and bus_category_bus
+ * set_data:Calls each function of the class
+ * based on the key af the array $data[0][$key]
+ * @todo Really need to look at enhancing this function for different datasetups.
+ * @param array $data: The input array from db query
+ * @uses GLM_TEMPLATE::$img_size
+ * @uses GLM_TEMPLATE::$img_align
+ * @uses GLM_TEMPLATE::$img_alternate
+ * @uses GLM_TEMPLATE::set_text()
+ * @uses GLM_TEMPLATE::set_header()
+ * @uses GLM_TEMPLATE::set_subheader()
+ * @uses GLM_TEMPLATE::set_url()
+ * @uses GLM_TEMPLATE::set_address()
+ * @uses GLM_TEMPLATE::set_img()
+ * @uses GLM_TEMPLATE::set_email()
+ * @uses GLM_TEMPLATE::set_phone()
+ *
+ * @return array data The finished array
+ * @access public
+ **/
+ function set_data($data)
+ {
+ if (is_array($data)) {
+ foreach ($data as $k => $val) {
+ foreach ($val as $key => $value) {
+ if ( strstr($key, "image")
+ && !strstr($key, "name")
+ && $value != ""
+ ) {
+ $titletag = $data[$k]['category']
+ ? $data[$k]['category']
+ : $data[$k]['name'];
+ //$data[$k][$key."_name"] = $value;
+ $data[$k][$key] = $this->set_img(
+ $value,
+ $this->img_size,
+ $this->img_align,
+ $titletag,
+ $data[$k][$key."name"]
+ );
+
+ if (!strstr($key, "name")) {
+ if ( $this->img_align == "right"
+ && $this->img_alternate
+ ) {
+ $this->img_align = "left";
+ } elseif ($this->img_alternate) {
+ $this->img_align = "right";
+ }
+ }
+ } elseif ( strstr($key, "file")
+ && strstr($key, "name")
+ && $value != ""
+ ) {
+ } elseif ( strstr($key,"url")
+ && strstr($key,"name")
+ && $value != ""
+ ) {
+ } elseif (strstr($key,"descr") && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_text($value);
+ } elseif (isset($data[$k]['email'])
+ && $key == "contactname"
+ && $value != ""
+ ) {
+ $data[$k][$key] = GLM_TEMPLATE::set_contact(
+ $value,
+ $data[$k]['email']
+ );
+ } elseif ($key == "name" && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_subheader($value);
+ } elseif (strstr( $key, "header" ) && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_subheader($value);
+ } elseif ($key == "intro" && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_header($value);
+ } elseif ($key == "category" && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_header($value);
+ } elseif ($key == "url" && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_url(
+ $value,
+ $data[$k]["urlname"]
+ );
+ } elseif ($key == "email" && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_email(
+ $value,
+ $data[$k]["contactname"]
+ );
+ } elseif ($key == "phone" && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_phone($value);
+ } elseif ($key == "fax" && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_fax($value);
+ } elseif (strstr($key, "file") && $value != "") {
+ $data[$k][$key] = GLM_TEMPLATE::set_file(
+ $value,
+ $data[$k][$key.'name']
+ );
+ } elseif ($key == "address") {
+ $data[$k][$key] = GLM_TEMPLATE::set_address($data[$k]);
+ } elseif ($key == "id") {
+ $data[$k][$key] = $value;
+ } else {
+ $data[$k][$key] = GLM_TEMPLATE::set_text($value);
+ }
+ }
+ }
+ return $data;
+ }
+ return false;
+ }
+
+ // }}}
+ // {{{ set_email()
+
+ /**
+ * set_email:Set the email string
+ * Contact: {$text}
+ * @param string $email: The email as string
+ * @param string $contact: The contactname this is used as the link text
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_email($email, $contact)
+ {
+ if ($email != "") {
+ if ($contact != "") {
+ $email = 'Contact: '.htmlspecialchars($contact).'
';
+ } else {
+ $email = 'Email: '.htmlspecialchars($email).'
';
+ }
+ }
+ return $email;
+ }
+
+ // }}}
+ // {{{ set_fax()
+
+ /**
+ * set_fax:Set the fax string
+ * Fax: {$text}
+ * @param string $text: The text as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_fax($text)
+ {
+ if ($text != "") {
+ $text = 'Fax: '.htmlspecialchars($text).'
';
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ set_file()
+
+ /**
+ * set_file:Set the file string
+ * Contact Name: {$text}
+ * @param string $text: The text as string
+ * @param string $name: The file name displayed
+ * @uses MEDIA_BASE_URL
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_file($text, $name)
+ {
+ if ($text != "") {
+ $outtext = '';
+ if ($name) {
+ $outtext .= htmlspecialchars($name);
+ } else {
+ $outtext .= htmlspecialchars($text);
+ }
+ $outtext .= ' ';
+ if (preg_match("/[.]([A-Z0-9]{3}$)/i", $text, $tmp)) {
+ // don't output second link
+ //$outtext .= 'Click here to Download ';
+ }
+ $outtext .= '
';
+ }
+ return $outtext;
+ }
+
+ // }}}
+ // {{{ set_header()
+
+ /**
+ * set_header:Set the header string
+ * @param string $text: The text as string
+ * @uses GLM_TEMPLATE::header_begin()
+ * @uses GLM_TEMPLATE::header_end()
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_header($text)
+ {
+ if ($text != "") {
+ $text = $this->header_begin.htmlspecialchars($text).$this->header_end;
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ set_img()
+
+ /**
+ * set_img:Set the image string
+ *
+ *
+ *
+ *
+ *
+ * @param string $image: The image
+ * @param string $size: The path
+ * @param string $align: The alignment
+ * @param string $name: The image_name (displayed under image)
+ * @param string $alt_title text for use in alt and title tags
+ * @param string $caption Text for image caption if given
+ * @uses GLM_TEMPLATE::get_image_path()
+ *
+ * @return void
+ * @access public
+ **/
+ function set_img($image, $size, $align, $alt_title = NULL, $caption = NULL)
+ {
+ if ($image != "") {
+ if ($caption != '') {
+ $caption = str_replace('&','&',$caption);
+ $titletag = 'title="'.htmlspecialchars(strip_tags($caption)).'"';
+ $titletag .= ' alt="'.htmlspecialchars(strip_tags($image)).'"';
+ } elseif ($alt_title != '') {
+ $alt_title = str_replace('&','&',$alt_title);
+ $titletag = 'title="'.htmlspecialchars(strip_tags($alt_title)).'"';
+ $titletag .= ' alt="'.htmlspecialchars(strip_tags($image)).'"';
+ } else {
+ $titletag = 'title="'.htmlspecialchars(strip_tags($image)).'"';
+ $titletag .= ' alt="'.htmlspecialchars(strip_tags($image)).'"';
+ }
+
+ if ($align != "") {
+ $img_align = 'class="image'.$align.'"';
+ }
+ $path = $this->get_image_path();
+ if (is_file($path.$image)) {
+ $image_size = getimagesize($path.$image);
+ $img_attr = $image_size[3];
+ } else {
+ $imServer = new Toolkit_Image_Server();
+ $image_size = $imServer->getImageSize($size.$image);
+ //$image_size[0] = $ret['width'];
+ //$image_size[1] = $ret['height'];
+ }
+ $img = '';
+ $img .= '
';
+ if ($caption) {
+ $img .= '
'.$caption.'
';
+ }
+ $img .= '
';
+ return $img;
+ }
+ }
+
+ // }}}
+ // {{{ set_member()
+
+ /**
+ * set_member
+ *
+ * @access public
+ * @return string
+ */
+ function set_member()
+ {
+ if (MEMBERS_DB && $this->catid) {
+ $member = new Toolkit_Members_Display($this->dbh);
+ try {
+ $res = $member->setCatId($this->catid);
+ } catch (InvalidArgumentException $e) {
+ return Toolkit_Common::handleError($e);
+ }
+ $member->setMemberSections();
+ return $member;
+ }
+ }
+
+ // }}}
+ // {{{ set_name_url()
+
+ /**
+ * setNameUrl:
+ * @param string $name :
+ *
+ * @return string
+ * @access public
+ */
+ function set_name_url( $name )
+ {
+ $name = str_replace(" ","-",$name);
+ $name = preg_replace("/[\/#&?'\"]|amp;/", "", strip_tags(strtolower(trim($name))));
+ return htmlspecialchars( $name );
+ }
+
+ // }}}
+ // {{{ set_pages()
+
+ /**
+ * set_pages: grab the globals for the pages an use this for
+ * the pages array for the class
+ *
+ * @return void
+ * @access public
+ **/
+ function set_pages(&$pages)
+ {
+ $this->pages[1] = 'index';
+ }
+
+ // }}}
+ // {{{ set_phone()
+
+ /**
+ * set_phone:Set the phone string
+ * Phone: {$text}
+ * @param string $text: The text as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_phone($text)
+ {
+ if ($text != "") {
+ $text = 'Phone: '.$text.'
';
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ set_subheader()
+
+ /**
+ * set_subheader:Set the subheader string
+ * @param string $text: The text as string
+ * @uses GLM_TEMPLATE::subheader_begin()
+ * @uses GLM_TEMPLATE::subheader_end()
+ *
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_subheader($text)
+ {
+ if ($text != "") {
+ $text = $this->subheader_begin.htmlspecialchars($text).$this->subheader_end;
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ set_text()
+
+ /**
+ * set_text:Set the contact string
+ * {$text}
+ * @param string $text: The text as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_text($text)
+ {
+ if ("" == str_replace(" ", "", trim($text))) {
+ return false;
+ }
+ if ($text != "") {
+ $text = $this->keyword_replace($text);
+ $text = $text;
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ set_toolbox_to_category_array()
+
+ function set_toolbox_to_category_array(){
+ $category_toolbox[1] = 70;// Places to Stay
+ $category_toolbox[20] = 71;// Things to Do
+ $category_toolbox[19] = 72;// Food & Spirits
+ $category_toolbox[24] = 73;// Camping
+ $category_toolbox[40] = 74;// Travel Services
+ $category_toolbox[25] = 75;// Attractions
+ $category_toolbox[41] = 76;// Golf
+ $category_toolbox[42] = 77;// Real Estate
+ $category_toolbox[43] = 78;// Shopping
+ $category_toolbox[44] = 79;// Recreation
+ $this->category_toolbox = $category_toolbox;
+ }
+
+ // }}}
+ // {{{ set_url()
+
+ /**
+ * set_url:Set the url string
+ *
+ * {$text}
+ *
+ *
+ * @param string $url: The url
+ * @param string $text: The text as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_url($url, $text)
+ {
+ if ($url != "") {
+ if (!$text) {
+ $text = $url;
+ }
+ if (strtolower(substr($url, 0, 7) ) == "https://") {
+ $url = ''.htmlspecialchars($text).'
';
+ } else {
+ $url = ''.htmlspecialchars($text).'
';
+ }
+ }
+ return $url;
+ }
+
+ // }}}
+ // {{{ show_catheader()
+
+ /**
+ * show_catheader:
+ *
+ * @param integer $catid:
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ **/
+ function show_catheader($catid)
+ {
+ $query = "SELECT category FROM bus_category WHERE id = $catid";
+ $data = $this->DB->db_auto_get_data($query);
+ if ($data[0][category]!="") {
+ $header = $data[0][category];
+ } else {
+ $header = ' ';
+ }
+ echo $header;
+ }
+
+ // }}}
+ // {{{ show_catimg()
+
+ /**
+ * show_catimg:output the category image.
+ *
+ * @param integer $catid: The catid for the page.
+ * @uses GLM_TEMPLATE::MIDSIZED
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return void
+ * @access public
+ */
+ function show_catimg($catid)
+ {
+ $query = "SELECT image FROM bus_category WHERE id = $catid";
+ $data = $this->DB->db_auto_get_data($query);
+ if ($data[0]["image"]!="") {
+ $img = ' ';
+ } else {
+ $img = ' ';
+ }
+ echo $img;
+ echo ' ';
+ }
+
+ // }}}
+ // {{{ sort_childs()
+
+ /**
+ * sort_childs:
+ * @param array $threads:
+ *
+ * @return string
+ * @access public
+ */
+ function sort_childs($threads)
+ {
+ foreach($threads as $var=>$value) {
+ $childs[$value["parent"]][$value["id"]] = $value;
+ }
+ return $childs;
+ }
+
+ // }}}
+ // {{{ sub_nav()
+
+ /**
+ * sub_nav:Create a sub navigation 4 across
+ *
+ * @param integer $catid: The catid for the page
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return void
+ * @access public
+ */
+ function sub_nav($catid)
+ {
+ $newcatid = $this->get_parent_id($catid);
+ if ($newcatid != 0) {
+ $catid = $newcatid;
+ }
+ $query1 = "SELECT category FROM bus_category WHERE id = $catid";
+ $data1 = $this->DB->db_auto_get_data( $query1 );
+ $out = ' ';
+
+ $query = "SELECT id,category,intro FROM bus_category WHERE parent = $catid ".$this->active_query." ORDER BY pos";
+ $data = $this->DB->db_auto_get_data($query);
+ if (is_array($data)) {
+ $counter = 1;
+ foreach ($data as $key => $val) {
+ $url = $this->get_seo_url($val['id']);
+ $title = strip_tags(addslashes($val['intro']));
+ //GLM_TEMPLATE::set_name_url( GLM_TEMPLATE::get_category_Name( $val['id'],"bus_category",$this->DB ) );
+ $out .= '
';
+ $out .= $val["category"];
+ $out .= ' ';
+ }
+ }
+ $out .= '
';
+ return $out;
+ }
+
+ // }}}
+
+ // {{{ title()
+
+ /**
+ * title: create the title for the page.
+ * this should be only done for all but the home page.
+ * $title = ( $catid != 1 ) ? $toolbox->title() : '';
+ *
+ * @uses GLM_DB::db_auto_get_data()
+ *
+ * @return string
+ * @access public
+ */
+ function title()
+ {
+ $query = "
+ SELECT category,intro,title
+ FROM bus_category
+ WHERE id = :id";
+ try {
+ $stmt = $this->dbh->prepare($query);
+ $stmt->bindParam(":id", $this->catid, PDO::PARAM_INT);
+ $stmt->execute();
+ $data = $stmt->fetchAll();;
+ } catch(PDOException $e) {
+ echo ''.print_r($e, true).' ';
+ die($e->getMessage());
+ }
+
+ if ($data[0]['title']) {
+ $title = strip_tags($data[0]['title']);
+ } else if ($data[0]['intro']) {
+ $title = strip_tags($data[0]['intro']);
+ } else {
+ $title = strip_tags($data[0]['category']);
+ }
+ return htmlentities($title.' - ',ENT_QUOTES,'UTF-8');
+ }
+
+ // }}}
+
+ // {{{ valid_email()
+
+ /** valid email
+ *
+ * Checks for a valid format and good (mx check)
+ * email address.
+ * @deprecated using GLM_TOOLBOX::valid_email()
+ * @uses GLM_TOOLBOX::valid_email()
+ *
+ * @param string email the email address as string.
+ * @return boolean
+ */
+ function valid_email( $email )
+ {
+ return GLM_TOOLBOX::valid_email( $email );
+ }
+
+ // }}}
+}
+?>
diff --git a/classes/class_toolbox.inc b/classes/class_toolbox.inc
new file mode 100755
index 0000000..21c96e6
--- /dev/null
+++ b/classes/class_toolbox.inc
@@ -0,0 +1,1701 @@
+
+ * These classes and any code is not licensed for anyone but gaslight to use
+ *
+ *
+ * @category Toolbox
+ * @package GLM_TOOLBOX
+ * @author Steve Sutton
+ * @copyright 2005-2008 Gaslight Media
+ * @license http://app.gaslightmedia.com/license.php Gaslight Media
+ * @link http://www.gaslightmedia.com www.gaslightmedia.com
+ * @since $Date: 2010/07/25 17:22:09 $
+ */
+/**
+ * Toolbox Class :)
+ *
+ * NOTICE
+ * Im going to be moving all functions from the setup.phtml
+ * file and putting it into this
+ * class. This is so we can eventially move
+ * everything to one siteinfo.inc file.
+ * matrix@devsys Does this work?
+ *
+ * @todo move all functions from setup.phtml into here
+ */
+define('GLM_TOOLBOX', true);
+
+/**
+ * Short description for class
+ *
+ * Long description (if any) ...
+ *
+ * @category Toolbox
+ * @package GLM_TOOLBOX
+ * @author Steve Sutton
+ * @copyright 2005-2008 Gaslight Media
+ * @license http://app.gaslightmedia.com/license.php Gaslight Media
+ * @link http://www.gaslightmedia.com www.gaslightmedia.com
+ * @see References to other sections (if any)...
+ */
+class GLM_TOOLBOX
+{
+ /** @var array php_version */
+ var $php_version;
+ /** @var boolean true if php is version < 4.2 */
+ var $php_old_pg;
+ // {{{ __construct()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function __construct()
+ {
+ $this->php_version = $this->php_version_check();
+ $this->php_old_pg = $this->php_old_pg();
+ }// }}}
+ // {{{ CC_date_entry($month, $year, $month_name, $year_name)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $month Parameter description (if any) ...
+ * @param string $year Parameter description (if any) ...
+ * @param string $month_name Parameter description (if any) ...
+ * @param string $year_name Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function CC_date_entry($month, $year, $month_name, $year_name)
+ {
+ $cur_date = getdate();
+ if ($month == "") {
+ $month = $cur_date['mon'];
+ }
+ if ($year == "") {
+ $year = $cur_date['year'];
+ }
+ $date = '';
+ for ($i = 1; $i < 13; $i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ $date .= '';
+ for ($i = $year; $i < $year + 15; $i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ return $date;
+ } // }}}
+ // {{{ CreditVal($Num, $Name = '', $Accepted='')
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $Num Parameter description (if any) ...
+ * @param string $Name Parameter description (if any) ...
+ * @param string $Accepted Parameter description (if any) ...
+ *
+ * @return boolean Return description (if any) ...
+ * @access public
+ */
+ function CreditVal($Num, $Name = '', $Accepted='')
+ {
+ $Name = strtolower($Name);
+ $Accepted = strtolower($Accepted);
+ $GoodCard = 1;
+ $Num = preg_replace("/[^[:digit:]]/", "", $Num);
+ switch ($Name) {
+
+ case "mastercard" :
+ $GoodCard = preg_match("/^5[1-5].{14}$/", $Num);
+ break;
+
+ case "visa" :
+ $GoodCard = preg_match("/^4.{15}$|^4.{12}$/", $Num);
+ break;
+
+ case "americanexpress" :
+ $GoodCard = preg_match("/^3[47].{13}$/", $Num);
+ break;
+
+ case "discover" :
+ $GoodCard = preg_match("/^6011.{12}$/", $Num);
+ break;
+
+ case "dinerscard" :
+ $GoodCard = preg_match("/^30[0-5].{11}$|^3[68].{12}$/", $Num);
+ break;
+
+ default:
+ if (preg_match("/^5[1-5].{14}$/", $Num)) {
+ $Name = "mastercard";
+ }
+ if (preg_match("/^4.{15}$|^4.{12}$/", $Num)) {
+ $Name = "visa";
+ }
+ if (preg_match("/^3[47].{13}$/", $Num)) {
+ $Name = "americanexpress";
+ }
+ if (preg_match("/^6011.{12}$/", $Num)) {
+ $Name = "discover";
+ }
+ if (preg_match("/^30[0-5].{11}$|^3[68].{12}$/", $Num)) {
+ $Name ="dinerscard";
+ }
+ break;
+ }
+
+ // If there's a limit on card types we accept, check for it here.
+ if ($Accepted) {
+ $type_verified = false;
+ $brands = explode(",", $Accepted);
+ foreach ($brands as $brand) {
+ if ($Name == $brand) {
+ $type_verified = true;
+ }
+ }
+ if (!$type_verified) {
+ return false;
+ }
+ }
+ $Num = strrev($Num);
+ $Total = 0;
+ for ($x=0; $x $title) {
+ $out .= '
+ ';
+ }
+ return $out;
+ }// }}}
+ // {{{ build_picklist($fieldname, $data, $selected, $type = "standard",$auto = 0,$width = null)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $fieldname Parameter description (if any) ...
+ * @param array $data Parameter description (if any) ...
+ * @param unknown $selected Parameter description (if any) ...
+ * @param string $type Parameter description (if any) ...
+ * @param integer $auto Parameter description (if any) ...
+ * @param string $width Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function build_picklist($fieldname, $data, $selected, $type = "standard",$auto = 0,$width = null)
+ {
+ if (!is_array($selected)) {
+ $sel[0] = $selected;
+ } else {
+ $sel = $selected;
+ }
+ if ($auto == 1) {
+ $autosubmit = "onChange=\"form.submit()\"";
+ }
+ if ($width) {
+ $autosubmit .= "style=\"width:".$width."px;\"";
+ }
+ switch($type) {
+ case "multiple":
+ $str = "\n";
+ while (list($key, $val) = each($data)) {
+ if (in_array($key, $sel)) {
+ $select = " selected ";
+ } else {
+ $select = "";
+ }
+ $str .= " $val\n";
+ }
+ break;
+ case "simple":
+ $str = "\n";
+ for ($i = 0; $i < count($data); $i++) {
+ $select = (in_array($data[$i], $sel)) ? " selected ":"";
+ $str .= " ".$data[$i]."\n";
+ }
+ break;
+
+ case "standard":
+ default:
+ $str = "\n";
+ while (list($key, $val) = each($data)) {
+ $select = (in_array($key, $sel)) ? " selected ":"";
+ $str .= " $val\n";
+ }
+ break;
+ }
+ $str .= " \n";
+ return $str;
+ }// }}}
+ // {{{ build_radios($name, $data)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $name Parameter description (if any) ...
+ * @param array $data Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function build_radios($name, $data)
+ {
+ if (!is_array($selected)) {
+ $sel[0] = $selected;
+ } else {
+ $sel = $selected;
+ }
+ if (!is_array($data)) {
+ return false;
+ }
+ $count = 1;
+ foreach ($data as $field => $title) {
+ $out .= '
+ ';
+ $count++;
+ }
+ return $out;
+ }// }}}
+ // {{{ calendar_entry_input($name, $value, $icon_path)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $name Parameter description (if any) ...
+ * @param unknown $value Parameter description (if any) ...
+ * @param string $icon_path Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function calendar_entry_input($name, $value, $icon_path)
+ {
+ $out = '
+
+
+ ';
+ return $out;
+ }// }}}
+ // {{{ calendar_entry_javascript($name, $value)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $name Parameter description (if any) ...
+ * @param string $value Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function calendar_entry_javascript($name, $value)
+ {
+ $out .= '
+ ';
+ return $out;
+ }// }}}
+ // {{{ contact_date_entry($month,$day,$year,$month_name,$day_name,$year_name)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $month Month
+ * @param string $day Day
+ * @param string $year Year
+ * @param string $month_name id and name value of month
+ * @param string $day_name id and name value of day
+ * @param string $year_name id and name value of year
+ * @param string $onChange must be onChange="javzascript;"
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function contact_date_entry($month,$day,$year,$month_name,$day_name,$year_name,$onChange = null)
+ {
+ $cur_date = getdate();
+
+ if ($month == "") {
+ $month = $cur_date['mon'];
+ }
+ if ($day == "") {
+ $day = $cur_date['mday'];
+ }
+ if ($year == "") {
+ $year = $cur_date['year'];
+ }
+ $date = '';
+ for ($i=1;$i<13;$i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ $date .= '';
+ for ($i=1;$i<32;$i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ $date .= '';
+ $ystart = $cur_date['year'] - 10;
+ for ($i=$ystart;$i<=$year;$i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ return $date;
+ }// }}}
+ // {{{ cp1252_to_utf8($str)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $str Parameter description (if any) ...
+ *
+ * @return array Return description (if any) ...
+ * @access public
+ */
+ function cp1252_to_utf8($str)
+ {
+ $cp1252_map = array(
+ "\xc2\x80" => "\xe2\x82\xac", /* EURO SIGN */
+ "\xc2\x82" => "\xe2\x80\x9a", /* SINGLE LOW-9 QUOTATION MARK */
+ "\xc2\x83" => "\xc6\x92", /* LATIN SMALL LETTER F WITH HOOK */
+ "\xc2\x84" => "\xe2\x80\x9e", /* DOUBLE LOW-9 QUOTATION MARK */
+ "\xc2\x85" => "\xe2\x80\xa6", /* HORIZONTAL ELLIPSIS */
+ "\xc2\x86" => "\xe2\x80\xa0", /* DAGGER */
+ "\xc2\x87" => "\xe2\x80\xa1", /* DOUBLE DAGGER */
+ "\xc2\x88" => "\xcb\x86", /* MODIFIER LETTER CIRCUMFLEX ACCENT */
+ "\xc2\x89" => "\xe2\x80\xb0", /* PER MILLE SIGN */
+ "\xc2\x8a" => "\xc5\xa0", /* LATIN CAPITAL LETTER S WITH CARON */
+ "\xc2\x8b" => "\xe2\x80\xb9", /* SINGLE LEFT-POINTING ANGLE QUOTATION */
+ "\xc2\x8c" => "\xc5\x92", /* LATIN CAPITAL LIGATURE OE */
+ "\xc2\x8e" => "\xc5\xbd", /* LATIN CAPITAL LETTER Z WITH CARON */
+ "\xc2\x91" => "\xe2\x80\x98", /* LEFT SINGLE QUOTATION MARK */
+ "\xc2\x92" => "\xe2\x80\x99", /* RIGHT SINGLE QUOTATION MARK */
+ "\xc2\x93" => "\xe2\x80\x9c", /* LEFT DOUBLE QUOTATION MARK */
+ "\xc2\x94" => "\xe2\x80\x9d", /* RIGHT DOUBLE QUOTATION MARK */
+ "\xc2\x95" => "\xe2\x80\xa2", /* BULLET */
+ "\xc2\x96" => "\xe2\x80\x93", /* EN DASH */
+ "\xc2\x97" => "\xe2\x80\x94", /* EM DASH */
+
+ "\xc2\x98" => "\xcb\x9c", /* SMALL TILDE */
+ "\xc2\x99" => "\xe2\x84\xa2", /* TRADE MARK SIGN */
+ "\xc2\x9a" => "\xc5\xa1", /* LATIN SMALL LETTER S WITH CARON */
+ "\xc2\x9b" => "\xe2\x80\xba", /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
+ "\xc2\x9c" => "\xc5\x93", /* LATIN SMALL LIGATURE OE */
+ "\xc2\x9e" => "\xc5\xbe", /* LATIN SMALL LETTER Z WITH CARON */
+ "\xc2\x9f" => "\xc5\xb8" /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
+ );
+ return strtr(utf8_encode($str), $cp1252_map);
+ }// }}}
+ // {{{ create_href($options)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param array $options Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function create_href($options)
+ {
+ if (!is_array($options)) {
+ return false;
+ } else {
+ $id = ($options['id'] && $options['id'] != '')
+ ? ' id="'.$options["id"].'"': '';
+ $title = ($options['title'] && $options['title'] != '')
+ ? ' title="'.$options["title"].'"': '';
+ $class = ($options['class'] && $options['class'] != '')
+ ? ' class="'.$options["class"].'"': '';
+ $text = ($options['text'] && $options['text'] != '')
+ ? strip_tags($options["text"]) : '';
+ $onClick = ($options['onClick'] && $options['onClick'] != '')
+ ? ' onClick="'.$options["onClick"].'"': '';
+ $onMouseover = ($options['onMouseover'] && $options['onMouseover'] != '')
+ ? ' onMouseover="'.$options["onMouseover"].'"': '';
+ $onMouseout = ($options['onMouseout'] && $options['onMouseout'] != '')
+ ? ' onMouseout="'.$options["onMouseout"].'"': '';
+ $out = ''.$text.' ';
+ return $out;
+ }
+ }// }}}
+ // {{{ create_page_links($totalnum,$num,$start=0,$params,$page_length=ENTRIES_PER_PAGE)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param mixed $totalnum Parameter description (if any) ...
+ * @param unknown $num Parameter description (if any) ...
+ * @param number $start Parameter description (if any) ...
+ * @param unknown $params Parameter description (if any) ...
+ * @param number $page_length Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function create_page_links($totalnum,$num,$start=0,$params=null,
+ $page_length=ENTRIES_PER_PAGE)
+ {
+ // FIND out which page we're on.
+ if ($totalnum!=0) {
+ $total_pages = floor($totalnum / $page_length); // total pages = the total result divided by page length rounded down
+ $total_pages++; // then add one
+ if ($start == 0) { // if start is 0 then page is one {
+ $page = 1;
+ } else {
+ $page = ($start / $page_length) + 1;
+ }
+ }
+
+ if ($totalnum > $page_length && ($page != $totalpages)) {
+ $end = $page_length + $start;
+ } else {
+ $end = $totalnum;
+ }
+ $last = $start - $page_length;
+ if (($start - $page_length) < 0) {
+ $prev = "";
+ } else {
+ $prev = "[PREVIOUS PAGE ]";
+ }
+ if ($end < $totalnum) {
+ $next = "[NEXT PAGE ]";
+ } else {
+ $next = "";
+ }
+ $starting = $start + 1;
+ $last_c = $start + $num;
+ $links = 'Showing: '.$starting.' to '
+ .$last_c.' of '.$totalnum.'
'.$prev. ' '
+ .$next.'
';
+ return $links;
+ }// }}}
+ // {{{ create_sitemap()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function create_sitemap()
+ {
+ $page = new Toolkit_Page(new GLM_TEMPLATE(9999));
+ // 404 pages must not contain any links (including css)
+ //$page->createErrorDocument();
+ }// }}}
+ // {{{ date_entry($month,$day,$year,$month_name,$day_name,$year_name)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $month Month
+ * @param string $day Day
+ * @param string $year Year
+ * @param string $month_name id and name value of month
+ * @param string $day_name id and name value of day
+ * @param string $year_name id and name value of year
+ * @param string $onChange must be onChange="javzascript;"
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function date_entry($month,$day,$year,$month_name,$day_name,$year_name,$onChange = null)
+ {
+ $cur_date = getdate();
+ if ($month == "") {
+ $month = $cur_date['mon'];
+ }
+ if ($day == "") {
+ $day = $cur_date['mday'];
+ }
+ if ($year == "") {
+ $year = $cur_date['year'];
+ }
+ $date = '';
+ for ($i=1;$i<13;$i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ $date .= '';
+ for ($i=1;$i<32;$i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ $date .= '';
+ for ($i=2000;$i<2023;$i++) {
+ $date .= '';
+ }
+ $date .= ' ';
+ return $date;
+ } // }}}
+ // {{{ explode_template($template,$data)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param boolean $template Parameter description (if any) ...
+ * @param unknown $data Parameter description (if any) ...
+ *
+ * @return boolean Return description (if any) ...
+ * @access public
+ */
+ function explode_template($template,$data)
+ {
+ $template = GLM_TOOLBOX::template_read($template);
+ $output = GLM_TOOLBOX::template_replacement($template, $data);
+ return $output;
+
+ }// }}}
+ // {{{ file_upload($form_field, $file_name, $destination_path, $restricted = false)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $form_field Parameter description (if any) ...
+ * @param string $file_name Parameter description (if any) ...
+ * @param string $destination_path Parameter description (if any) ...
+ * @param boolean $restricted Parameter description (if any) ...
+ *
+ * @return array Return description (if any) ...
+ * @access public
+ */
+ function file_upload($form_field, $file_name, $destination_path, $restricted = false)
+ {
+ foreach ($_FILES as $fieldName => $file) {
+ if ($file['tmp_name'] == $form_field) {
+ $fs = new Toolkit_FileServer_FileAdapter();
+ try {
+ $res = $fs->upload($fieldName);
+ return $res['name'];
+ } catch(Toolkit_FileServer_Exception $e) {
+ Toolkit_Logger::logException('File Server', $e);
+ return false;
+ }
+ }
+ }
+ return false;
+
+ }// }}}
+ // {{{ footer()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function footer()
+ {
+ $bottomScripts = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+
+ echo "$bottomScripts