--- /dev/null
+<Files ~ "^\.ht">
+Order allow,deny
+Deny from all
+</Files>
+<Files ~ "^setup.phtml">
+Order allow,deny
+Deny from all
+</Files>
+<Files ~ "\.ini$">
+Order allow,deny
+Deny from all
+</Files>
+ErrorDocument 404 /404.html
+RewriteEngine On
+AddDefaultCharset utf-8
+
+RewriteBase /www.soolocks.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]
+
+############
+## 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 ^memberProfiles/.*-([0-9]*).html index\.php?catid=9999&member_id=$1 [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 ##
+###############
+
--- /dev/null
+<?php
+/**
+ * BaseControllerAbstract.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Toolkit_BaseControllerAbstract
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * BreadCrumbsFactory.php
+ *
+ * PHP Version 5.2
+ *
+ * @category Toolkit
+ * @package Members_MembersOnly
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license Gaslight Media
+ * @version SVN: $id$
+ * @link <>
+ */
+
+/**
+ * Toolkit_BreadCrumbsFactory
+ *
+ * Description of Toolkit_BreadCrumbsFactory
+ *
+ * @category Toolkit
+ * @package Members_MembersOnly
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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;
+ }
+}
+?>
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Connects the CKImage browser to the server for image manipulation
+ *
+ * PHP version 5
+ *
+ * @category CKImages
+ * @package Toolkit_CKImages
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @version Release: @package_version@
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_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 '<script type="text/javascript">';
+ try {
+ ob_start();
+ $image = $ia->upload('upload');
+ ob_end_clean();
+ } catch (RangeException $e) {
+ Toolkit_Logger::logException('Runtime Error', $e);
+ echo "window.parent.CKEDITOR.tools.callFunction($ckEditorFuncNum, '', 'Invalid Image Format');";
+ }
+
+ $dimensions = $ia->getImageSize(CKIMAGE . $image['name']);
+ list($i['oWidth'], $i['oHeight'],) = $dimensions;
+ $this->handleUpload($image['name'], $i);
+
+ // path to image we are going to use
+ $ip = CKIMAGE . $image['name'];
+ echo "window.parent.CKEDITOR.tools.callFunction($ckEditorFuncNum, '$ip', '');";
+ echo '</script>';
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_CKImages_database_Import
+{
+ // {{{ Class Properties
+ protected $dbh;
+ protected $pathToImages;
+ protected $is;
+ protected $urlPathToImages;
+
+ // }}}
+ // {{{ __construct()
+ function __construct(PDO $pdo)
+ {
+ $this->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 '<pre>'.print_r($files, true).'</pre>';
+ foreach ($files as $folderName => $file) {
+ if (is_array($file)) {
+ $fKey = key($file);
+ $folderToAdd = preg_replace("%/$%", "", $fKey);
+ //echo '<pre>'.print_r($folderToAdd, true).'</pre>';
+ $folder = $this->addFolderToDatabase($folderToAdd, $parent);
+ //echo '<pre>'.print_r($folder, true).'</pre>';
+ //var_dump($files[$folderName][$fKey]);
+ // echo '<pre>'.print_r($file[$folderName][$fKey], true).'</pre>';
+ $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 '<br />';
+ $d = dir($dirName);
+ while (false !== ($entry = $d->read())) {
+ if (!preg_match("%^\.|^CVS%", $entry)) {
+ $entryPath = $this->pathToImages . $path . $entry;
+ //var_dump($entryPath); echo '<br />';
+ 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 '<pre>'.print_r($files, true).'</pre>';
+ $processedFiles = $this->processFilesArray($files['']);
+// echo '<pre>'.print_r($processedFiles, true).'</pre>';
+ }
+ //}}}
+ // {{{ 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);
+ }
+ // }}}
+}
+?>
--- /dev/null
+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
--- /dev/null
+INSERT INTO ckimages.ckeditor_folders(id, name, parent) VALUES(1, 'Home', 0);
+SELECT setval('"ckimages".ckeditor_folders_id_seq', 2, false);
--- /dev/null
+<?php
+require_once '../../../setup.phtml';
+// set this to the real sites url
+// is0.gaslightmedia.com will only fetch the images if
+// it has access and it cannot do http auth
+define('HT_IMAGES_URL', 'http://www.petoskeyarea.com/images/ht_images/');
+$dbh = Toolkit_Database::getInstance();
+$import = new Toolkit_CKImages_Database_Import($dbh);
+$import->runImport();
+?>
--- /dev/null
+ALTER TABLE ckimages.ckeditor_images
+ ADD COLUMN original_image TEXT;
--- /dev/null
+--
+-- 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;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+<?php
+class Toolkit_CKImages_Exception extends Exception {}
+?>
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * CKImage Factory
+ *
+ * PHP version 5
+ *
+ * @category CKImages
+ * @package Toolkit_CKImages
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @version Release: @package_version@
+ * @link http://demo.gaslightmedia.com
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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];
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Handles create a UL list to simulate a folder hierarchy
+ *
+ * PHP version 5
+ *
+ * @category CKImages
+ * @package Toolkit_CKImages
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @version Release: @package_version@
+ * @link http://demo.gaslightmedia.com
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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</ul>";
+ }
+
+ // }}}
+ // {{{ closeNode()
+
+
+ /**
+ * Closes a node
+ *
+ * @return string closing li tag
+ * @access protected
+ */
+ protected function closeNode()
+ {
+ return "\n\t</li>";
+ }
+
+ // }}}
+ // {{{ createFolder()
+
+
+ /**
+ * Creates a folder level
+ *
+ * @return string opening ul tag
+ * @access protected
+ */
+ protected function createFolder()
+ {
+ return "\n<ul>";
+ }
+
+ // }}}
+ // {{{ 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 = '<a class="%s" href="'.MEDIA_BASE_URL.'Toolkit/CKImages/browser.php?CKEditor=%s&CKEditorFuncNum=%s&langCode=%s&folder=%s">%s</a>';
+
+ $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<li id=\"pred_{$row['id']}\">";
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_CKImages_ImageUpdater
+{
+ // {{{ properties
+
+ private $_imageData = array();
+ private $_dbh;
+
+ // }}}
+ // {{{ __construct()
+
+ public function __construct(PDO $dbh)
+ {
+ $this->_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']);
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * popup browser window
+ *
+ * This file creates the popup browser window to manage images
+ *
+ * PHP versions 4 and 5
+ *
+ * @category CKImages
+ * @package Toolkit_CKImages
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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);
+?>
--- /dev/null
+<?php
+
+/**
+ * Controller file
+ *
+ * PHP versions 4 and 5
+ *
+ * @category CKImages
+ * @package Toolkit_CKImages
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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;
+}
+?>
--- /dev/null
+<?php
+if (!ctype_digit($_GET['file'])) {
+ exit();
+}
+
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+
+try {
+ $sql = "
+ SELECT *
+ FROM ckeditor_images
+ WHERE id = :id";
+
+ $stmt = $dbh->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");
+?>
--- /dev/null
+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);
--- /dev/null
+body {\r
+ font-family: arial, sans-serif;\r
+ font-size: 11px;\r
+ background: url(assets/night-fate-stock2.jpg) no-repeat fixed;/* #E3E3C7; */\r
+ margin: 0;\r
+ padding: 0;\r
+}\r
+#wrapper {\r
+ width: 750px;\r
+ height: 1%;\r
+ overflow: hidden;\r
+ margin: 10px 0px 5px 10px;\r
+}\r
+h1 {\r
+ font-size: 24px;\r
+ margin: 0;\r
+ padding: 10px;\r
+ background: rgba(255, 255, 255, 0.8);\r
+ position: fixed;\r
+ }\r
+\r
+#toolbar {\r
+ background: #F1F1E3;\r
+ width: 140px;\r
+ border: 1px solid #D5D59D;\r
+ float: left;\r
+ padding: 8px;\r
+ margin-right: 20px;\r
+ margin-top: 60px;\r
+ position: fixed;\r
+ }\r
+#toolbar > ul {\r
+ border-bottom: 1px solid #333;\r
+ padding: 0 0 6px 0;\r
+ margin: 0 0 6px 0;\r
+ }\r
+#toolbar > ul, #toolbar > ul li {\r
+ list-style: none;\r
+ display: block;\r
+}\r
+#toolbar > ul li {\r
+ padding: 2px 2px 2px 26px;\r
+ line-height: 18px;\r
+ border: 1px solid #F1F1E3;\r
+ margin: 0;\r
+ background-position: 2px center;\r
+ background-repeat: no-repeat;\r
+ text-decoration: underline;\r
+ cursor: hand;\r
+ cursor: pointer;\r
+}\r
+#toolbar > ul li:hover {\r
+ border: 1px solid #D5D59D;\r
+ text-decoration: none;\r
+}\r
+#toolbar #upload {\r
+ background-image: url(//app.gaslightmedia.com/assets/icons/add.png);\r
+}\r
+#toolbar #folderNew {\r
+ background-image: url(//app.gaslightmedia.com/assets/icons/folder_add.png);\r
+}\r
+#toolbar #folderDelete {\r
+ background-image: url(//app.gaslightmedia.com/assets/icons/folder_delete.png);\r
+}\r
+.tree ul {\r
+ margin: 0;\r
+ padding-top: 1px;\r
+}\r
+.tree li a {\r
+ background-image: url(//app.gaslightmedia.com/assets/icons/folder.png);\r
+}\r
+.tree li.open {\r
+ background: none;\r
+ }\r
+#pred_1 {\r
+ padding-left: 3px;\r
+ padding-top: 3px;\r
+}\r
+.tree li li.open {\r
+ background: transparent url(//app.gaslightmedia.com/libjs/jsTree/source/images/li.gif) no-repeat scroll 7px 7px;\r
+}\r
+/* Main Section */\r
+#photo-gallery {\r
+ height: 1%;\r
+ overflow: hidden;\r
+ padding-top: 10px;\r
+ margin: 50px 0 0 180px;\r
+ }\r
+.thumb {\r
+ width: 120px;\r
+ height: 160px;\r
+ float: left;\r
+ margin: 0 20px 20px 0;\r
+ background: #F1F1E3;\r
+ background: rgba(241, 241, 227, 0.5);\r
+ font-size: 10px;\r
+ border-radius:5px;\r
+ -moz-border-radius:5px;\r
+ -webkit-border-radius:5px;\r
+ border: 1px solid #D5D59D;\r
+ }\r
+.rowTop {\r
+ height: 1%;\r
+ overflow: hidden;\r
+}\r
+.thumb img {\r
+ display: block;\r
+ margin: 0px 10px 2px 10px;\r
+ border: 1px dotted #ccc;\r
+ clear: left;\r
+}\r
+\r
+.CKImageFunctions {\r
+ margin: 10px 5px;\r
+ }\r
+.CKImageFunctions a,\r
+.CKImageFunctions span {\r
+ display: block;\r
+ line-height: 16px;\r
+ margin: 0 5px 0 5px;\r
+ text-decoration: underline;\r
+ width: 16px;\r
+ height: 16px;\r
+ text-indent: -9000px;\r
+ float: left;\r
+ }\r
+ \r
+/* cursor */\r
+.CKImageUse, .CKImageEdit, .CKImageDelete {\r
+ cursor: hand;\r
+ cursor: pointer;\r
+ }\r
+\r
+.CKImageUse {background: url(//app.gaslightmedia.com/assets/icons/accept.png) no-repeat; }\r
+.CKImageEdit {background: url(//app.gaslightmedia.com/assets/icons/image_edit.png) no-repeat; }\r
+.CKImageView {background: url(//app.gaslightmedia.com/assets/icons/image.png) no-repeat;}\r
+.CKImageDelete {background: url(//app.gaslightmedia.com/assets/icons/image_delete.png) no-repeat;}\r
+\r
+.CKImageName {\r
+ display: none;\r
+}\r
+\r
+\r
+.CKImageProperties {\r
+ margin: 3px auto;\r
+ text-align: center;\r
+}\r
+.CKImageDate {\r
+ display: none;\r
+}\r
+#menuFolder, #menuImage, #column {\r
+ display: none;\r
+}\r
--- /dev/null
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<title>Thumbnail Images</title>
+<meta http-equiv="content-type" content="text/html;charset=utf-8">
+<link rel="stylesheet" type="text/css" href="<?php echo MEDIA_APP_BASE_URL;?>libjs/jqueryui/1.8/css/smoothness/jquery-ui-1.8.custom.css">
+<link rel="stylesheet" type="text/css" href="<?php echo MEDIA_APP_BASE_URL;?>libjs/jsTree/source/tree_component.css">
+<link rel="stylesheet" type="text/css" href="<?php echo MEDIA_APP_BASE_URL;?>libjs/plugins/tipsy/0.1.7/tipsy.css">
+<link rel="stylesheet" type="text/css" href="styles.css">
+<script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jquery/jquery-1.4.2.min.js"></script>
+</head>
+<body>
+ <h1>GLM Image Browser</h1>
+ <div id="wrapper">
+ <div id="toolbar">
+ <ul>
+ <li id="upload">Upload New Image</li>
+ </ul>
+ <ul>
+ <li id="folderNew">Create New Folder</li>
+ <li id="folderDelete">Delete This Folder</li>
+ </ul>
+ <div id="folders" class="tree">
+ Folders
+ {folders:h}
+ </div>
+ </div><!-- /#toolbar -->
+ <div id="photo-gallery" class="galleryRow">
+ <div flexy:foreach="images,i" class="thumb">
+ <div class="CKImageProperties">{i[original_width]:h}x{i[original_height]:h}</div>
+ <img src="{imageManager}{i[name_on_disk]:h}" rel="{originalPath}{i[name_on_disk]:h}" title="{i[file_name]:h}" alt="{i[name_on_disk]:h}">
+ <div class="CKImageFunctions">
+ <span class="CKImageUse tLeft" title="Insert Image">Insert this image</span>
+ <a class="CKImageView tCenter" href="{originalPath}{i[name_on_disk]:h}" target="_blank" title="View Image">View Full Image</a>
+ <a href="{baseUrl:h}Toolkit/CKImages/imageFetch.php?file={i[id]}" class="CKImageEdit tRight" target="_blank" title="Edit Image">Edit this image</a>
+ <span class="CKImageDelete tDelete" title="Delete Image">Delete Image</span>
+ </div><!-- /#CKImageFunctions -->
+ <div class="CKImageName">{i[file_name]:h}</div>
+ <div class="CKImageDate">{i[create_date]:h}</div>
+ </div>
+ </div><!-- /#photo-gallery -->
+ </div><!-- /#wrapper -->
+ <!-- dialog box for adding new folders -->
+ <div id="folderDialog" class="dialog" style="display: none;" title="Create new folder">
+ <form id="newFolder">
+ <label for="folderName">Name</label>
+ <input type="text" name="folderName" id="folderName">
+ </form>
+ </div>
+ <!-- dialog box for adding new images -->
+ <div id="imageDialog" class="dialog" style="display: none;" title="Upload new image">
+ {quickUploadForm:h}
+ </div>
+
+ <!-- Function number -->
+ <span style="display: none;" id="CKEditorFuncNum">{CKEditorFuncNum}</span>
+
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.core.min.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.widget.min.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.position.min.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jqueryui/1.8/development-bundle/ui/minified/jquery.ui.dialog.min.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jsTree/libjs/css.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jquery.listen.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jquery.cookie.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/jsTree/source/tree_component.js"></script>
+ <script type="text/javascript" src="libjs/image_selector.js"></script>
+ <script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>libjs/plugins/tipsy/0.1.7/jquery.tipsy.js"></script>
+</body>
+</html>
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Common Toolkit application function repository
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Common
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 <server@gaslightmedia.com>';
+
+ // }}}
+
+ // {{{ 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
+ * <code>
+ * 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}<br>', $e);
+ * break;
+ *
+ * default :
+ * $renderer = null;
+ * break;
+ * }
+ *
+ * return $renderer;
+ * }
+ * </code>
+ *
+ * @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
+ *
+ * <code>
+ * Toolkit_Common::createSQLInsert('member', array('name', 'pos'));
+ * will create the sql statement
+ * INSERT INTO member (name, pos) VALUES(:name, :pos)
+ * </code>
+ *
+ * @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
+ *
+ * <code>
+ * 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
+ * </code>
+ *
+ * @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 . '<br>';
+ echo 'Error Caught. <br>';
+ echo 'Error: ' . $e->getMessage() . '<br>';
+ if ($moreInfo) {
+ echo 'Code: <pre>' . $e->getCode() . '</pre><br>';
+ echo 'Debug Info: <pre>' . $e->getDebugInfo() . '</pre><br>';
+ }
+ }
+ }
+
+ // }}}
+
+ // {{{ 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:
+ * <code>
+ * try {
+ if ($foo != $bar) {
+ throw new Exception ("Foo Doesn't equal Bar");
+ }
+ * } catch (Exception $e) {
+ * return Toolkit_Common::handleError($e);
+ * }
+ * </code>
+ *
+ * @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:
+ * <code>
+ * $e =& $this->getElement('elementName');
+ * if (PEAR::isError($e)) {
+ * return Toolkit_Common::handleError($e);
+ * }
+ * </code>
+ *
+ * @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:
+ * <code>
+ * 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);
+ * }
+ * </code>
+ *
+ * @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 = '<b>' . get_class($obj) . ' error: </b>';
+
+ $state .= '<br>$_SERVER[\'QUERY_STRING\']: ' . $_SERVER['QUERY_STRING']
+ . "\n";
+ $state .= '<br>$_SERVER[\'HTTP_REFERER\']: ' . $_SERVER['HTTP_REFERER']
+ . "\n";
+ $state .= '<br>$_SERVER[\'REDIRECT_QUERY_STRING\']: '
+ . $_SERVER['REDIRECT_QUERY_STRING'] . "\n";
+ $state .= '<br>$_SERVER[\'REQUEST_URI\']: ' . $_SERVER['REQUEST_URI']
+ . "\n";
+
+ $state .= '<br>$_GET: <pre>' . print_r($_GET, true) . '</pre>';
+ $state .= '<br>$_POST: <pre>' . print_r($_POST, true) . '</pre>';
+ $state .= '<br>$_SESSION: <pre>' . print_r($_SESSION, true) . '</pre>';
+
+ if (method_exists($obj, 'getMessage')) {
+ $state .= $obj->getMessage();
+ if (method_exists($obj, 'getDebugInfo')) {
+ $state .= '; ' . $obj->getDebugInfo();
+ }
+ }
+ if (method_exists($obj, 'getFile')) {
+ $state .= ' in <b>' . $obj->getFile() . '</b>';
+ }
+ if (method_exists($obj, 'getLine')) {
+ $state .= ' on line <b>' . $obj->getLine() . '</b>';
+ }
+ if (method_exists($obj, 'getBacktrace')) {
+ $backtrace = print_r($obj->getBacktrace(), true);
+
+ $state .= "<br><pre>$backtrace</pre>";
+ }
+
+ 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 = '<script type="text/javascript" src="%s"></script>';
+
+ $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 = '<link type="text/css" rel="stylesheet" href="%s">';
+
+ $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 '<p>The system has encountered an un-recoverable error!</p>';
+ }
+ }
+
+ // }}}
+
+ // {{{ 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 = '<p>' . self::getErrorInfo($e) . '</p>';
+
+ $htmlMsg = "<html><head></head><body>$msg</body></html>";
+ $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();
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Database Singleton
+ *
+ * PHP version 5
+ *
+ * @category Database
+ * @package Database
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Adapter class for linking to the file server
+ *
+ * Base abstract class used to connect and talk with file server
+ * can be subclassed for Files, Images, Video, Audio, etc...
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit
+ * @package FileServer
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+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('<?xml version="1.0"?' . '>', '', $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('<?xml version="1.0"?' . '>', '', $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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+class Toolkit_FileServer_Exception extends RuntimeException
+{
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * File Adapter
+ *
+ * Link to the file server and allow file storage and deletion
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package FileServer
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Image Adapter
+ *
+ * Link to the file server and allow image storage and deletion
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package FileServer
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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>(.*)<\/width>/';
+ preg_match($wPattern, $response, $matches);
+ $width = $matches[1];
+ $hPattern = '/<height>(.*)<\/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('<?xml version="1.0"?'. '>', '', $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'
+ );
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * 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
+ *
+ * PHP version 5
+ *
+ * @category FileServer
+ * @package Toolkit_FileServer
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Define how form objects should be built
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Form
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @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.
+ *
+ * <code>
+ * 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);
+ * }
+ * </code>
+ *
+ * @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.
+ *
+ * <code>
+ * 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);
+ * }
+ * </code>
+ *
+ * @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();
+
+ // }}}
+}
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * File Doc Comment
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package FormBuilder
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @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
+ = '<div id="form-warning-top">
+ Warning: The form was not sent, please review the errors below.
+ </div>';
+
+ /**
+ * What do you want the success msg to be if the form validates successfully
+ *
+ * @var string
+ * @access protected
+ */
+ protected $successMsg
+ = '<div id="form-success-top">
+ The information below has been successfully submitted.
+ </div>';
+
+ /**
+ * 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
+ * <code>
+ * $rules[] = array('element' => 'phone',
+ * 'message' => 'ERROR: Invalid Phone Format!',
+ * 'type' => 'phone',
+ * 'format' => null,
+ * 'validation' => $this->validationType,
+ * 'reset' => true,
+ * 'force' => false);
+ * </code>
+ *
+ * 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.
+ * <code>
+ * $rules[] = array('element' => 'zip',
+ * 'message' => 'ERROR: Invalid Zip!',
+ * 'type' => 'zip',
+ * 'format' => array('requireDBCheck' => true),
+ * 'validation' => $this->validationType,
+ * 'reset' => true,
+ * 'force' => false);
+ * </code>
+ *
+ * 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.
+ * <code>
+ * $rules[] = array('element' => 'state_id',
+ * 'message' => 'ERROR: Invalid State / Province!',
+ * 'type' => 'state',
+ * 'format' => array('requireDBCheck' => true),
+ * 'validation' => $this->validationType,
+ * 'reset' => true,
+ * 'force' => false);
+ * </code>
+ *
+ * @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 <form> 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.
+ * <code>
+ * 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
+ * }
+ * </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
+ * <code>
+ * 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
+ * }
+ * </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.
+ * <code>
+ * // Define the rules for each element in the group.
+ * $num_rule = array(
+ * 'ERROR: Must contain a valid decimal number!',
+ * 'numeric'
+ * );
+ * // Collect together the rules for each element.
+ * $lat_rules = array('lat' => array($num_rule));
+ * $lon_rules = array('lon' => array($num_rule));
+ * $r[] = array(
+ * 'element' => 'latitude',
+ * 'message' => 'ERROR:',
+ * 'type' => 'group',
+ * 'format' => $lat_rules,
+ * 'validation' => $this->validationType,
+ * 'reset' => false,
+ * 'force' => false
+ * );
+ * </code>
+ *
+ * To make a group required but not require every element in the group
+ * you can use the addGroupRule function again
+ * for example: say you have a group of checkboxes and you only only
+ * require 1 be checked. a simple group rule such as the following
+ * will handle this.
+ * N.B. notice the extra "howMany" index.
+ * <code>
+ * $r[] = array(
+ * 'element' => 'element_name',
+ * 'message' => 'ERROR: Error to display!',
+ * 'type' => 'required',
+ * 'format' => null,
+ * 'howMany' => 1,
+ * 'validation'=> $this->validationType,
+ * 'reset' => true,
+ * 'force' => false,
+ * );
+ * </code>
+ *
+ * @param array $rules Multi-Dimensional array of rules for form elements.
+ *
+ * @return void
+ * @access protected
+ */
+ protected function setupRules(array $rules = null)
+ {
+ $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
+ * <code>
+ * <tr>
+ * <td class="labelcell">
+ * <!-- BEGIN required -->
+ * <span class="required">*</span>
+ * <!-- END required -->
+ * <label> {label} </label>
+ * </td>
+ * <td class="fieldcell">
+ * <!-- BEGIN error -->
+ * <div class="req"> {error} </div>
+ * <!-- END error -->
+ * {element}
+ * </td>
+ *</tr>
+ * </code>
+ *
+ * # Form.tpl
+ * <code>
+ * <div id="contact">
+ * <form{attributes}>
+ * <table>
+ * {content}
+ * </table>
+ * </form>
+ * </div>
+ * </code>
+ *
+ * # GroupElement.tpl
+ * <code>
+ * <tr>
+ * <td>
+ * {element}
+ * <!-- BEGIN required -->
+ * <span class="req">*</span>
+ * <!-- END required -->
+ * {label}
+ * </td>
+ * </tr>
+ * </code>
+ *
+ * # Group.tpl
+ * <code>
+ * <table class="group">
+ * <tbody>
+ * {content}
+ * </tbody>
+ * </table>
+ * </code>
+ *
+ * # Header.tpl
+ * <code>
+ * <tr class="hdr">
+ * <td colspan="2">
+ * {header}
+ * </td>
+ * </tr>
+ * </code>
+ *
+ * # RequiredNote.tpl
+ * <code>
+ * <span class="req">*</span> Denotes required field
+ * </code>
+ *
+ * @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 = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+ $error = '<!-- BEGIN error --><div class="req">{error}</div><!-- END error -->';
+ $renderer->setElementTemplate(
+ '<tr>
+ <td class="labelcell"><label>{label}</label></td>
+ <td class="fieldcell captcha">{element}</td>
+ </tr>',
+ 'captcha_question'
+ );
+ $renderer->setElementTemplate(
+ '<tr>
+ <td class="labelcell">'.$required.'<label>{label}</label></td>
+ <td class="fieldcell">'.$error.'{element}
+ <span class="tooltip" title="Verification Code|To help us distinguish between information submitted by individuals and those automatically entered by software robots, please type the letters shown.">What is this?</span>
+ </td>
+ </tr>',
+ '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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+/**
+ * Date.php
+ *
+ * PHP version 5.2
+ *
+ * @category Toolkit
+ * @package Forms/Rules
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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'
+);
+?>
--- /dev/null
+<?php
+/**
+ * Image.php
+ *
+ * PHP version 5.2
+ *
+ * @category Toolkit
+ * @package Forms/Rules
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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
+ * <img src="%s"> 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' => '<img src="%s">',
+ * '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']
+ : '<img src="%s">';
+
+ $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'
+);
+?>
--- /dev/null
+<?php
+/**
+ * ShortUrl.php
+ *
+ * PHP version 5.2
+ *
+ * @category Toolkit
+ * @package Forms/Rules
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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'
+);
+?>
--- /dev/null
+<?php
+
+/**
+ * Url.php
+ *
+ * PHP version 5.2
+ *
+ * @category Toolkit
+ * @package Forms/Rules
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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'
+);
+?>
--- /dev/null
+<tr>
+ <td class="labelcell">
+ <!-- BEGIN required -->
+ <span class="req">*</span>
+ <!-- END required -->
+ <label>{label}</label>
+ </td>
+ <td class="fieldcell">
+ <!-- BEGIN error -->
+ <div class="req"> {error} </div>
+ <!-- END error -->
+ {element}
+ </td>
+</tr>
--- /dev/null
+<div class="webform">
+ <form{attributes}>
+ <div class="hiddenElements">
+ {hidden}
+ </div>
+ {requiredNote}
+ <table>
+ {content}
+ </table>
+ </form>
+</div>
\ No newline at end of file
--- /dev/null
+<table class="group">
+ <tbody>
+ {content}
+ </tbody>
+</table>
--- /dev/null
+<tr>
+ <td>
+ {element}
+ <!-- BEGIN required -->
+ <span class="req">*</span>
+ <!-- END required -->
+ {label}
+ </td>
+</tr>
--- /dev/null
+<tr class="hdr">
+ <td colspan="2">
+ {header}
+ </td>
+</tr>
--- /dev/null
+<div><span class="req">*</span> Denotes required field</div>
--- /dev/null
+<?php
+
+/**
+ * IController.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Controller
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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();
+}
--- /dev/null
+<?php
+/**
+ * IMapper.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Mapper
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link <>
+ */
+
+/**
+ * Toolkit_IMapper
+ *
+ * Interface for creation of mapper classes
+ *
+ * @category Toolkit
+ * @package Mapper
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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);
+}
+?>
--- /dev/null
+<?php
+/**
+ * INavigation.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Toolkit_INavigation
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license Gaslight Media
+ * @release Release: $id$
+ * @link <>
+ */
+
+/**
+ * Toolkit_INavigation
+ *
+ * Interface
+ *
+ * @category Toolkit
+ * @package Toolkit_INavigation
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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);
+}
+?>
--- /dev/null
+<?php
+/**
+ * iTable.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Table
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link <>
+ */
+
+/**
+ * Interface for Table objects
+ *
+ * @category Toolkit
+ * @package Table
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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);
+}
--- /dev/null
+<?php
+
+/**
+ * Converter.php
+ *
+ * Long description (if any) ...
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit
+ * @package Image
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 '<pre>'.print_r($values, true).'</pre>';
+ $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 '<pre>'
+ . print_r(
+ $values['original_url']
+ . '/' . $row[$values['img_field_name']],
+ true
+ ) . '</pre>';
+ $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;
+ }
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * Server.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Image
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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('<?xml version="1.0"?' . '>', '', $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('<?xml version="1.0"?' . '>', '', $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>(.*)<\/width>/";
+ preg_match($wPattern, $response, $matches);
+ $width = $matches[1];
+ $hPattern = "/<height>(.*)<\/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;
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Error handling logger for system
+ *
+ * PHP version 5
+ *
+ * @category Logger
+ * @package Toolkit_Logger
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @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;
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * NavigationAbstract.php
+ *
+ * PHP version 5.2
+ *
+ * @category Toolkit
+ * @package None
+ * @author Chuck Scott <cscott@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license Gaslight Media
+ * @version SVN: $id$
+ * @link <>
+ */
+
+/**
+ * Toolkit_NavigationAbstract
+ *
+ * Description of NavigationAbstract
+ *
+ * @category Toolkit
+ * @package None
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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();
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * NavigationFactoryAbstract.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Toolkit_NavigationFactoryAbstract
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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();
+}
+?>
--- /dev/null
+<?php\r
+ /**\r
+ * phpimageeditor.php\r
+ * \r
+ * PHP version 5.2\r
+ * \r
+ * @category Toolkit\r
+ * @package PHPImageEditor/Classes\r
+ * @author Jamie Kahgee <steve@gaslightmedia.com>\r
+ * @copyright 2012 Gaslight Media\r
+ * @license Gaslight Media\r
+ * @version SVN: $id$\r
+ * @link <>\r
+ */\r
+\r
+\r
+ /*\r
+ Copyright 2008, 2009, 2010 Patrik Hultgren\r
+\r
+ YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR.\r
+ OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT:\r
+ http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F\r
+\r
+ This file is part of PHP Image Editor.\r
+\r
+ PHP Image Editor is free software: you can redistribute it and/or modify\r
+ it under the terms of the GNU General Public License as published by\r
+ the Free Software Foundation, either version 3 of the License, or\r
+ (at your option) any later version.\r
+\r
+ PHP Image Editor is distributed in the hope that it will be useful,\r
+ but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ GNU General Public License for more details.\r
+\r
+ You should have received a copy of the GNU General Public License\r
+ along with PHP Image Editor. If not, see <http://www.gnu.org/licenses/>.\r
+ */\r
+\r
+\r
+ //Requires\r
+ //PHP: 4.3\r
+ //GD: 2.0.28\r
+\r
+ /*PHP FUNCTIONS REQUIRES THESE VERSIONS\r
+ getimagesize PHP 4\r
+ image_type_to_mime_type PHP 4.3\r
+ imagecopyresized PHP 4\r
+ file_exists PHP 4\r
+ copy PHP 4\r
+ imagecreatetruecolor PHP 4.0.6, GD 2.0.1\r
+ imagecopyresized PHP 4\r
+ imagecopy PHP 4\r
+ imagecreatefromjpeg PHP 4, GD 1.8\r
+ imagecreatefromgif PHP 4, GD 2.0.28\r
+ imagecreatefrompng PHP 4\r
+ imagefilter PHP 5, GD\r
+ imagejpeg PHP 4, GD-1.8\r
+ imagepng PHP 4\r
+ imagegif PHP 4\r
+ imagerotate PHP 4.3 GD\r
+ imagesx PHP 4\r
+ imagesy PHP 4\r
+ */\r
+\r
+ \r
+ /**\r
+ * Description of PHPImageEditor\r
+ * \r
+ * @category Toolkit\r
+ * @package PHPImageEditor/Classes\r
+ * @author Jamie Kahgee <steve@gaslightmedia.com>\r
+ * @copyright 2012 Gaslight Media\r
+ * @license Gaslight Media\r
+ * @release Release: $id$\r
+ * @link <>\r
+ */\r
+class PHPImageEditor\r
+{\r
+ public $srcEdit = "";\r
+ public $srcOriginal = "";\r
+ public $srcPng = "";\r
+ public $srcWorkWith = "";\r
+ public $resourceWorkWith = false;\r
+ public $mimeType = "";\r
+ public $actionSaveAndClose = "save";\r
+ public $actionRotateLeft = "rotate:90";\r
+ public $actionRotateRight = "rotate:-90";\r
+ public $actionGrayscale = "grayscale";\r
+ public $actionContrast = "contrast";\r
+ public $actionBrightness = "brightness";\r
+ public $actionUndo = "undo";\r
+ public $actionUpdate = "update";\r
+ public $actionRotateIsSelected = false;\r
+ public $actionRotate = "";\r
+ public $actionSeparatorSign = "#";\r
+ public $fieldNameKeepProportions = "keepproportions";\r
+ public $errorMessages = array();\r
+ public $formName = "phpimageeditor";\r
+ public $inputImageName = '';\r
+ public $inputWidth = -1;\r
+ public $inputHeight = -1;\r
+ public $inputCropLeft = 0;\r
+ public $inputCropRight = 0;\r
+ public $inputCropTop = 0;\r
+ public $inputCropBottom = 0;\r
+ public $inputKeepProportions = true;\r
+ public $inputCropKeepProportions = false;\r
+ public $inputCropKeepProportionsRatio = 1;\r
+ public $inputPanel = MENU_RESIZE;\r
+ public $inputLanguage = DEFUALT_LANGUAGE;\r
+ public $inputContrast = 0;\r
+ public $inputBrightness = 0;\r
+ public $inputContrastLast = 0;\r
+ public $inputBrightnessLast = 0;\r
+ public $inputGrayscale = false;\r
+ public $httpImageKey = "imagesrc";\r
+ public $texts = array();\r
+ public $actions = "";\r
+ public $isPostBack = false;\r
+ public $isAjaxPost = false;\r
+ public $finalWidth = -1;\r
+ public $finalHeight = -1;\r
+ public $widthKeepProportions = -1;\r
+ public $heightKeepProportions = -1;\r
+ public $userId = "";\r
+\r
+ public $contrastMax = 100;\r
+ public $brightnessMax = 255;\r
+\r
+\r
+ function PHPImageEditor()\r
+ {\r
+ $this->LoadLanguage();\r
+\r
+ if (version_compare(phpversion(), PHP_VERSION_MINIMUM, "<"))\r
+ {\r
+ $this->errorMessages[] = phpversion()." ".$this->texts["OLD PHP VERSION"]." ".PHP_VERSION_MINIMUM;\r
+ return;\r
+ }\r
+\r
+ $this->isPostBack = isset($_POST["actiontype"]);\r
+\r
+ $srcEdit = "";\r
+\r
+ if ($_GET[$this->httpImageKey] != NULL)\r
+ {\r
+ $srcEdit = $_GET[$this->httpImageKey];\r
+ }\r
+\r
+ if ($srcEdit == "")\r
+ {\r
+ $this->errorMessages[] = $this->texts["NO PROVIDED IMAGE"];\r
+ return;\r
+ }\r
+\r
+ $this->srcEdit = urldecode($srcEdit);\r
+ $this->inputImageName = urlencode($_GET['image_name']);\r
+\r
+ if (isset($_POST["userid"]))\r
+ $this->userId = $_POST["userid"];\r
+ else\r
+ $this->userId = "_".time()."_".str_replace(".", "_", $_SERVER['REMOTE_ADDR']);\r
+\r
+ $this->SetSrcOriginal();\r
+ $this->SetSrcPng();\r
+ $this->SetSrcWorkWith();\r
+\r
+ if (!file_exists($this->srcEdit))\r
+ {\r
+ $this->errorMessages[] = $this->texts["IMAGE DOES NOT EXIST"];\r
+ return;\r
+ }\r
+\r
+ $info = getimagesize($this->srcEdit);\r
+\r
+ if (!$info)\r
+ {\r
+ $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"];\r
+ return;\r
+ }\r
+\r
+ $this->mimeType = image_type_to_mime_type($info[2]);\r
+\r
+ 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))\r
+ {\r
+ if (!$this->isPostBack)\r
+ $this->SaveOriginal();\r
+\r
+ $this->resourceWorkWith = $this->CreateImage($this->srcOriginal);\r
+ $this->SavePng();\r
+ copy($this->srcPng, $this->srcWorkWith);\r
+\r
+ $this->resourceWorkWith = $this->CreateImage($this->srcPng);\r
+ }\r
+ else\r
+ {\r
+ $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"];\r
+ return;\r
+ }\r
+\r
+ $this->finalWidth = $this->GetWidth();\r
+ $this->finalHeight = $this->GetHeight();\r
+ $this->widthKeepProportions = $this->GetWidth();\r
+ $this->heightKeepProportions = $this->GetHeight();\r
+\r
+ $this->GrantAllAccess($this->srcOriginal);\r
+ $this->GrantAllAccess($this->srcPng);\r
+ $this->GrantAllAccess($this->srcWorkWith);\r
+\r
+ if ($this->isPostBack)\r
+ {\r
+ $this->actionRotateIsSelected = ($_POST["rotate"] != "-1");\r
+ $this->actionRotate = $_POST["rotate"];\r
+ $this->actions = $_POST["actions"];\r
+ $this->isAjaxPost = ($_POST["isajaxpost"] == "true");\r
+\r
+// $this->inputImageName = $_POST['image_name'];\r
+ $this->inputWidth = (int)$_POST["width"];\r
+ $this->inputHeight = (int)$_POST["height"];\r
+ $this->inputCropLeft = (int)$_POST["cropleft"];\r
+ $this->inputCropRight = (int)$_POST["cropright"];\r
+ $this->inputCropTop = (int)$_POST["croptop"];\r
+ $this->inputCropBottom = (int)$_POST["cropbottom"];\r
+ $this->inputPanel = (int)$_POST["panel"];\r
+ $this->inputLanguage = $_POST["language"];\r
+ $this->inputKeepProportions = ($_POST["keepproportionsval"] == "1");\r
+ $this->inputCropKeepProportions = ($_POST["cropkeepproportionsval"] == "1");\r
+ $this->inputCropKeepProportionsRatio = (float)$_POST["cropkeepproportionsratio"];\r
+ $this->inputGrayscale = ($_POST["grayscaleval"] == "1");\r
+ $this->inputBrightness = (int)$_POST["brightness"];\r
+ $this->inputContrast = (int)$_POST["contrast"];\r
+ $this->inputBrightnessLast = (int)$_POST["brightnesslast"];\r
+ $this->inputContrastLast = (int)$_POST["contrastlast"];\r
+\r
+ $this->Action($_POST["actiontype"]);\r
+ }\r
+ }\r
+\r
+ function LoadLanguage()\r
+ {\r
+ $language = "";\r
+\r
+ if (isset($_POST["language"]))\r
+ {\r
+ $this->inputLanguage = $_POST["language"];\r
+ $language = $this->inputLanguage;\r
+ }\r
+ else if (isset($_GET["language"]))\r
+ {\r
+ $this->inputLanguage = $_GET["language"];\r
+ $language = $this->inputLanguage;\r
+ }\r
+ else\r
+ $language = DEFUALT_LANGUAGE;\r
+\r
+ $tryLanguage = "language/".$language."/".$language.".com_admin.ini";\r
+ if (file_exists($tryLanguage))\r
+ $this->texts = PIE_GetTexts("language/".$language."/".$language.".com_admin.ini");\r
+ else\r
+ $this->texts = PIE_GetTexts("language/".DEFUALT_LANGUAGE."/".DEFUALT_LANGUAGE.".com_admin.ini");\r
+ }\r
+\r
+ function SetSrcOriginal()\r
+ {\r
+ $arr = explode("/", $this->srcEdit);\r
+ $this->srcOriginal = IMAGE_ORIGINAL_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]);\r
+ }\r
+\r
+ function SetSrcWorkWith()\r
+ {\r
+ $arr = explode("/", $this->srcEdit);\r
+ $srcWorkWith = IMAGE_WORK_WITH_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]);\r
+ $srcWorkWith = substr($srcWorkWith, 0, strripos($srcWorkWith, ".")).".png";\r
+ $this->srcWorkWith = $srcWorkWith;\r
+ }\r
+\r
+ function SetSrcPng()\r
+ {\r
+ $arr = explode("/", $this->srcEdit);\r
+ $srcPng = IMAGE_PNG_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]);\r
+ $srcPng = substr($srcPng, 0, strripos($srcPng, ".")).".png";\r
+ $this->srcPng = $srcPng;\r
+ }\r
+\r
+ function SaveOriginal()\r
+ {\r
+ copy($this->srcEdit, $this->srcOriginal);\r
+\r
+ //Resize to fit in max width/height.\r
+ $imageTmp = $this->CreateImage($this->srcOriginal);\r
+ $finalWidth = $this->GetWidthFromImage($imageTmp);\r
+ $finalHeight = $this->GetHeightFromImage($imageTmp);\r
+\r
+ $doSave = false;\r
+\r
+ if ($finalWidth > IMAGE_MAX_WIDTH)\r
+ {\r
+ $widthProp = IMAGE_MAX_WIDTH/$finalWidth;\r
+ $finalWidth = IMAGE_MAX_WIDTH;\r
+ $finalHeight = round($finalHeight*$widthProp);\r
+ $doSave = true;\r
+ }\r
+\r
+ if ($finalHeight > IMAGE_MAX_HEIGHT)\r
+ {\r
+ $heightProp = IMAGE_MAX_HEIGHT/$finalHeight;\r
+ $finalHeight = IMAGE_MAX_HEIGHT;\r
+ $finalWidth = round($finalWidth*$heightProp);\r
+ $doSave = true;\r
+ }\r
+\r
+ if ($doSave)\r
+ {\r
+ $imageTmp = $this->ActionResize($finalWidth, $finalHeight, $imageTmp);\r
+ $this->SaveImage($imageTmp, $this->srcOriginal);\r
+ }\r
+ }\r
+\r
+ function SavePng()\r
+ {\r
+ $this->SaveImage($this->resourceWorkWith, $this->srcPng, image_type_to_mime_type(IMAGETYPE_PNG));\r
+ }\r
+\r
+ function ErrorHasOccurred()\r
+ {\r
+ return (count($this->errorMessages) > 0);\r
+ }\r
+\r
+ function GetWidthFinal()\r
+ {\r
+ return $this->finalWidth;\r
+ }\r
+\r
+ function GetHeightFinal()\r
+ {\r
+ return $this->finalHeight;\r
+ }\r
+\r
+ function GetWidth()\r
+ {\r
+ return $this->GetWidthFromImage($this->resourceWorkWith);\r
+ }\r
+\r
+ function GetWidthLast()\r
+ {\r
+ if ($this->isPostBack)\r
+ return (int)$_POST["widthlast"];\r
+\r
+ return $this->GetWidth();\r
+ }\r
+\r
+ function GetHeight()\r
+ {\r
+ return $this->GetHeightFromImage($this->resourceWorkWith);\r
+ }\r
+\r
+ function GetHeightLast()\r
+ {\r
+ if ($this->isPostBack)\r
+ return (int)$_POST["heightlast"];\r
+\r
+ return $this->GetWidth();\r
+ }\r
+\r
+ function GetImageNameFinal()\r
+ {\r
+ if ($this->isPostBack)\r
+ return $_POST["image_name"];\r
+\r
+ return $this->inputImageName;\r
+ }\r
+\r
+ function getImageName()\r
+ {\r
+ return $this->inputImageName;\r
+ }\r
+\r
+ function GetWidthFromImage($image)\r
+ {\r
+ return imagesx($image);\r
+ }\r
+\r
+ function GetHeightFromImage($image)\r
+ {\r
+ return imagesy($image);\r
+ }\r
+\r
+ function Action($actionType)\r
+ {\r
+ $doSave = false;\r
+\r
+ if ($actionType == $this->actionUndo) {\r
+ $this->ActionUndo();\r
+ $doSave = true;\r
+ }\r
+\r
+ if ( $actionType == $this->actionUpdate\r
+ || $actionType == $this->actionSaveAndClose) {\r
+ if ( $this->inputWidth != $this->GetWidthLast()\r
+ || $this->inputHeight != $this->GetHeightLast()) {\r
+ $this->actions .= $this->GetActionSeparator()."resize:".$this->inputWidth.",".$this->inputHeight;\r
+ }\r
+\r
+ if ( $this->inputCropLeft != 0 || $this->inputCropRight != 0\r
+ || $this->inputCropTop != 0 || $this->inputCropBottom != 0) {\r
+ $this->actions\r
+ .= $this->GetActionSeparator()\r
+ ."crop:".$this->inputCropLeft.","\r
+ .$this->inputCropRight.","\r
+ .$this->inputCropTop.","\r
+ .$this->inputCropBottom;\r
+ }\r
+// var_dump($this->inputImageName);\r
+// var_dump($this->getImageNameFinal());\r
+// var_dump($_POST);\r
+// var_dump($_GET);\r
+// exit;\r
+ if (urldecode($this->inputImageName) != $this->GetImageNameFinal()) {\r
+ $this->actions .= $this->GetActionSeparator ()."imageName:".$this->GetImageNameFinal();\r
+ }\r
+ $doSave = true;\r
+ }\r
+\r
+ if ($actionType == $this->actionUpdate && $this->inputGrayscale) {\r
+ if (strpos($this->actions, $this->actionGrayscale) === false) {\r
+ $this->actions .= $this->GetActionSeparator().$this->actionGrayscale.":0";\r
+ $doSave = true;\r
+ }\r
+ } else if ($actionType == $this->actionUpdate && !$this->inputGrayscale) {\r
+ if (!(strpos($this->actions, $this->actionGrayscale) === false)) {\r
+ $this->actions = str_replace($this->actionGrayscale.":0".$this->GetActionSeparator(), "", $this->actions);\r
+ $this->actions = str_replace($this->GetActionSeparator().$this->actionGrayscale.":0", "", $this->actions);\r
+ $this->actions = str_replace($this->actionGrayscale.":0", "", $this->actions);\r
+ $doSave = true;\r
+ }\r
+ }\r
+\r
+ if ($this->inputContrast != $this->inputContrastLast) {\r
+ $this->actions .= $this->GetActionSeparator().$this->actionContrast.":".$this->inputContrast;\r
+ $doSave = true;\r
+ }\r
+\r
+ if ($this->inputBrightness != $this->inputBrightnessLast) {\r
+ $this->actions .= $this->GetActionSeparator().$this->actionBrightness.":".$this->inputBrightness;\r
+ $doSave = true;\r
+ }\r
+\r
+ if ($this->actionRotateIsSelected) {\r
+ if ($this->actionRotate == $this->actionRotateLeft) {\r
+ $this->actions .= $this->GetActionSeparator().$this->actionRotateLeft;\r
+ $doSave = true;\r
+ } else if ($this->actionRotate == $this->actionRotateRight) {\r
+ $this->actions .= $this->GetActionSeparator().$this->actionRotateRight;\r
+ $doSave = true;\r
+ }\r
+ }\r
+\r
+ $finalContrast = 0;\r
+ $finalBrightness = 0;\r
+ $finalContrastFound = false;\r
+ $finalBrightnessFound = false;\r
+ $finalGrayscale = false;\r
+\r
+ if ($doSave && $this->actions != "") {\r
+ $allActions = explode($this->actionSeparatorSign, $this->actions);\r
+\r
+ $finalRotate = 0;\r
+ $finalCropLeft = 0;\r
+ $finalCropRight = 0;\r
+ $finalCropTop = 0;\r
+ $finalCropBottom = 0;\r
+\r
+ $doSwitch = false;\r
+\r
+ foreach ($allActions as $loopAction) {\r
+ $actionDetail = explode(":", $loopAction);\r
+ $actionValues = explode(",", $actionDetail[1]);\r
+\r
+ if ($actionDetail[0] == "resize") {\r
+ $this->finalWidth = (int)$actionValues[0];\r
+ $this->finalHeight = (int)$actionValues[1];\r
+ } else if ($actionDetail[0] == "crop") {\r
+ $actionValueLeft = (int)$actionValues[0];\r
+ $actionValueRight = (int)$actionValues[1];\r
+ $actionValueTop = (int)$actionValues[2];\r
+ $actionValueBottom = (int)$actionValues[3];\r
+\r
+ $widthProp = 1;\r
+ $heightProp = 1;\r
+\r
+ if ($doSwitch) {\r
+ $widthProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalWidth);\r
+ $heightProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalHeight);\r
+ } else {\r
+ $widthProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalWidth);\r
+ $heightProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalHeight);\r
+ }\r
+\r
+ $cropLeft = $actionValueLeft * $widthProp;\r
+ $cropRight = $actionValueRight * $widthProp;\r
+ $cropTop = $actionValueTop * $heightProp;\r
+ $cropBottom = $actionValueBottom * $heightProp;\r
+\r
+ $cropValues = array();\r
+ $cropValues[] = $cropRight;\r
+ $cropValues[] = $cropBottom;\r
+ $cropValues[] = $cropLeft;\r
+ $cropValues[] = $cropTop;\r
+\r
+ if ($finalRotate != 0)\r
+ $cropValues = $this->RotateArray(($finalRotate/-90), $cropValues);\r
+\r
+ $finalCropRight += $cropValues[0];\r
+ $finalCropBottom += $cropValues[1];\r
+ $finalCropLeft += $cropValues[2];\r
+ $finalCropTop += $cropValues[3];\r
+\r
+ $this->finalWidth -= ($actionValueLeft + $actionValueRight);\r
+ $this->finalHeight -= ($actionValueTop + $actionValueBottom);\r
+ } else if ($actionDetail[0] == $this->actionGrayscale && $this->inputGrayscale) {\r
+ $finalGrayscale = true;\r
+ } else if ($actionDetail[0] == "contrast") {\r
+ $finalContrastFound = true;\r
+ $finalContrast = $actionValues[0];\r
+ } else if ($actionDetail[0] == "brightness") {\r
+ $finalBrightnessFound = true;\r
+ $finalBrightness = $actionValues[0];\r
+ } else if ($actionDetail[0] == "rotate") {\r
+ $finalRotate += (int)$actionValues[0];\r
+ $finalWidthTmp = $this->finalWidth;\r
+ $this->finalWidth = $this->finalHeight;\r
+ $this->finalHeight = $finalWidthTmp;\r
+ }\r
+\r
+ if ($finalRotate == -360 || $finalRotate == 360) {\r
+ $finalRotate = 0;\r
+ }\r
+\r
+ $doSwitch = ($finalRotate != 0 && ($finalRotate == 90 || $finalRotate == 270 || $finalRotate == -90 || $finalRotate == -270));\r
+ }\r
+\r
+ //1. All effects.\r
+ if ($finalGrayscale) {\r
+ $this->ActionGrayscale();\r
+ }\r
+\r
+ if ($finalBrightnessFound) {\r
+ $this->ActionBrightness($finalBrightness);\r
+ }\r
+\r
+ if ($finalContrastFound) {\r
+ $this->ActionContrast($finalContrast*-1);\r
+ }\r
+\r
+ //2. Do cropping.\r
+ $finalCropLeft = round($finalCropLeft);\r
+ $finalCropRight = round($finalCropRight);\r
+ $finalCropTop = round($finalCropTop);\r
+ $finalCropBottom = round($finalCropBottom);\r
+ if ($finalCropLeft != 0 || $finalCropRight != 0 || $finalCropTop != 0 || $finalCropBottom != 0) {\r
+ $this->ActionCrop($finalCropLeft, $finalCropRight, $finalCropTop, $finalCropBottom);\r
+ }\r
+\r
+ //3. Rotate\r
+ if ($finalRotate != 0) {\r
+ $this->ActionRotate($finalRotate);\r
+ }\r
+\r
+ //Calculate keep proportions values.\r
+ if (round($this->finalWidth/$this->finalHeight,1) == round($this->GetWidth()/$this->GetHeight(),1)) {\r
+ //It seems to have the same proportions as the original. Use the original proportions value.\r
+ $this->widthKeepProportions = $this->GetWidth();\r
+ $this->heightKeepProportions = $this->GetHeight();\r
+ } else {\r
+ //The proportions has been changed. Use the new width and height instead.\r
+ $this->widthKeepProportions = $this->finalWidth;\r
+ $this->heightKeepProportions = $this->finalHeight;\r
+ }\r
+\r
+ //4. Resize\r
+ if ($this->finalWidth > 0 && $this->finalHeight > 0)\r
+ $this->resourceWorkWith = $this->ActionResize($this->finalWidth, $this->finalHeight, $this->resourceWorkWith);\r
+\r
+ $this->SaveImage($this->resourceWorkWith, $this->srcWorkWith, image_type_to_mime_type(IMAGETYPE_PNG));\r
+ }\r
+\r
+ $this->inputBrightness = $finalBrightness;\r
+ $this->inputContrast = $finalContrast;\r
+ $this->inputGrayscale = $finalGrayscale;\r
+\r
+ if ($actionType == $this->actionSaveAndClose) {\r
+ $this->SaveImage($this->resourceWorkWith, $this->srcEdit, $this->mimeType);\r
+\r
+ /*** GLM stuff ***/\r
+ require_once '../../setup.phtml';\r
+ $CKUpdater = new Toolkit_CKImages_ImageUpdater(Toolkit_Database::getInstance());\r
+ $CKUpdater->load(basename($_GET['imagesrc']));\r
+ $CKUpdater->update(new Toolkit_FileServer_ImageAdapter());\r
+ /*****************/\r
+\r
+ unlink($this->srcOriginal);\r
+ unlink($this->srcPng);\r
+ unlink($this->srcWorkWith);\r
+ $this->DeleteOldImages(IMAGE_ORIGINAL_PATH);\r
+ $this->DeleteOldImages(IMAGE_PNG_PATH);\r
+ $this->DeleteOldImages(IMAGE_WORK_WITH_PATH);\r
+ $reloadParentBrowser = RELOAD_PARENT_BROWSER_ON_SAVE ? 'window.opener.location.reload();' : '';\r
+ PIE_Echo('<script language="javascript" type="text/javascript">'.$reloadParentBrowser.'window.open(\'\',\'_parent\',\'\');window.close();</script>');\r
+ }\r
+ }\r
+\r
+ function ActionResize($width, $height, $image)\r
+ {\r
+ $newImage = @imagecreatetruecolor($width, $height);\r
+ imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $this->GetWidthFromImage($image), $this->GetHeightFromImage($image));\r
+ return $newImage;\r
+ }\r
+\r
+ function ActionCrop($cropLeft, $cropRight, $cropTop, $cropBottom)\r
+ {\r
+ $cropWidth = $this->GetWidth() - $cropLeft - $cropRight;\r
+ $cropHeight = $this->GetHeight() - $cropTop - $cropBottom;\r
+\r
+ $newImageCropped = @imagecreatetruecolor($cropWidth, $cropHeight);\r
+ imagecopy($newImageCropped, $this->resourceWorkWith, 0, 0, $cropLeft, $cropTop, $cropWidth, $cropHeight);\r
+\r
+ $this->resourceWorkWith = $newImageCropped;\r
+ }\r
+\r
+ function ActionUndo()\r
+ {\r
+ $separatorPos = strrpos($this->actions, $this->actionSeparatorSign);\r
+ if (!($separatorPos === false))\r
+ {\r
+ $this->actions = substr($this->actions, 0, $separatorPos);\r
+ }\r
+ else\r
+ {\r
+ $this->actions = "";\r
+ }\r
+ }\r
+\r
+ function CreateImage($srcEdit)\r
+ {\r
+ $info = getimagesize($srcEdit);\r
+\r
+ if (!$info)\r
+ return NULL;\r
+\r
+ $mimeType = image_type_to_mime_type($info[2]);\r
+\r
+ if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG))\r
+ {\r
+ return imagecreatefromjpeg($srcEdit);\r
+ }\r
+ else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF))\r
+ {\r
+ return imagecreatefromgif($srcEdit);\r
+ }\r
+ else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG))\r
+ {\r
+ return imagecreatefrompng($srcEdit);\r
+ }\r
+\r
+ return NULL;\r
+ }\r
+\r
+ function ActionRotate($Degrees)\r
+ {\r
+ $this->resourceWorkWith = imagerotate($this->resourceWorkWith, $Degrees, 0);\r
+ }\r
+\r
+ function ActionGrayscale()\r
+ {\r
+ imagefilter($this->resourceWorkWith, IMG_FILTER_GRAYSCALE);\r
+ }\r
+\r
+ function ActionContrast($contrast)\r
+ {\r
+ //-100 = max contrast, 0 = no change, +100 = min contrast\r
+ imagefilter($this->resourceWorkWith, IMG_FILTER_CONTRAST, $contrast);\r
+ }\r
+\r
+ function ActionBrightness($light)\r
+ {\r
+ //-255 = min brightness, 0 = no change, +255 = max brightness\r
+ imagefilter($this->resourceWorkWith, IMG_FILTER_BRIGHTNESS, $light);\r
+ }\r
+\r
+ function GetErrorMessages()\r
+ {\r
+ if (count($this->errorMessages))\r
+ {\r
+ PIE_Echo('<div class="error">');\r
+ PIE_Echo('<ul>');\r
+\r
+ foreach ($this->errorMessages as $errorMessage)\r
+ PIE_Echo ('<li>'.$errorMessage.'</li>');\r
+\r
+ PIE_Echo("</ul>");\r
+ PIE_Echo('</div>');\r
+ }\r
+ }\r
+\r
+ function GetActions()\r
+ {\r
+ PIE_Echo($this->actions);\r
+ }\r
+\r
+ function GetActionSeparator()\r
+ {\r
+ if ($this->actions != "")\r
+ return $this->actionSeparatorSign;\r
+\r
+ return "";\r
+ }\r
+\r
+ function SaveImage($image, $toSrc, $mimeType = -1)\r
+ {\r
+ if ($mimeType == -1)\r
+ $mimeType = $this->mimeType;\r
+\r
+ if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG))\r
+ {\r
+ imagejpeg($image, $toSrc);\r
+ }\r
+ else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF))\r
+ {\r
+ imagegif($image, $toSrc);\r
+ }\r
+ else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG))\r
+ {\r
+ imagepng($image, $toSrc);\r
+ }\r
+ }\r
+\r
+ function CleanUp()\r
+ {\r
+ if ($this->resourceWorkWith)\r
+ imagedestroy($this->resourceWorkWith);\r
+ }\r
+\r
+ function RotateArray($numberOfSteps, $arr)\r
+ {\r
+ $finalArray = array();\r
+\r
+ //-3 to 3\r
+ $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 0)];\r
+ $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 1)];\r
+ $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 2)];\r
+ $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 3)];\r
+\r
+ return $finalArray;\r
+ }\r
+\r
+ function NumberOfStepsCalculator($sum)\r
+ {\r
+ $maxIndex = 3;\r
+ if ($sum > $maxIndex)\r
+ return ($sum-$maxIndex)-1;\r
+ else if ($sum < 0)\r
+ {\r
+ return ($sum+$maxIndex)+1;\r
+ }\r
+\r
+ return $sum;\r
+ }\r
+\r
+ function AddUserIdToImageSrc($imageSrc)\r
+ {\r
+ return str_replace(".", $this->userId.".", $imageSrc);\r
+ }\r
+\r
+ function IsPHP5OrHigher()\r
+ {\r
+ return version_compare(phpversion(), "5", ">=");\r
+ }\r
+\r
+ function GetFormAction()\r
+ {\r
+ return "index.php?"\r
+ . $this->httpImageKey . "=" . $this->srcEdit\r
+ . '&image_name=' . $this->inputImageName;\r
+ }\r
+\r
+ function GetWidthKeepProportions()\r
+ {\r
+ return $this->widthKeepProportions;\r
+ }\r
+\r
+ function GetHeightKeepProportions()\r
+ {\r
+ return $this->heightKeepProportions;\r
+ }\r
+\r
+ function DeleteOldImages($srcdir)\r
+ {\r
+ if($curdir = opendir($srcdir))\r
+ {\r
+ while($file = readdir($curdir))\r
+ {\r
+ if($file != '.' && $file != '..')\r
+ {\r
+ //$srcfile = $srcdir . '\\' . $file;\r
+ //$srcfile = $srcdir.'/'.$file;\r
+ $srcfile = $srcdir.$file;\r
+ $srcfileLower = strtolower($srcfile);\r
+\r
+ if (stripos($srcfile, ".svn") === false)\r
+ {\r
+ if(is_file($srcfile))\r
+ {\r
+ $doDelete = true;\r
+\r
+ 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))\r
+ $doDelete = false;\r
+\r
+ if ($doDelete)\r
+ {\r
+\r
+ $deleteTime = mktime(0, 0, 0, date("m"), date("d")-2, date("Y"));\r
+ if (fileatime($srcfile) < $deleteTime)\r
+ {\r
+ //Image is old and will be deleted. Or else the server space will be filled up with not needed images.\r
+ //echo "<h2>DELETE $srcfile".date("F d Y H:i:s.", fileatime($srcfile))."</h2>";\r
+ unlink($srcfile);\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+ closedir($curdir);\r
+ }\r
+ }\r
+\r
+ function GrantAllAccess($fileName)\r
+ {\r
+ chmod($fileName, 0777);\r
+ }\r
+ }\r
+?>\r
--- /dev/null
+<?php\r
+\r
+\r
+ /*\r
+ Copyright 2008, 2009, 2010 Patrik Hultgren\r
+\r
+ YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR.\r
+ OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT:\r
+ http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F\r
+\r
+ This file is part of PHP Image Editor.\r
+\r
+ PHP Image Editor is free software: you can redistribute it and/or modify\r
+ it under the terms of the GNU General Public License as published by\r
+ the Free Software Foundation, either version 3 of the License, or\r
+ (at your option) any later version.\r
+\r
+ PHP Image Editor is distributed in the hope that it will be useful,\r
+ but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ GNU General Public License for more details.\r
+\r
+ You should have received a copy of the GNU General Public License\r
+ along with PHP Image Editor. If not, see <http://www.gnu.org/licenses/>.\r
+ */\r
+\r
+\r
+ define("IMAGE_MAX_WIDTH", 700);\r
+ define("IMAGE_MAX_HEIGHT", 500);\r
+ define("DEFUALT_LANGUAGE", "en-GB");\r
+ define("RELOAD_PARENT_BROWSER_ON_SAVE", true);\r
+ define("AJAX_POST_TIMEOUT_MS", 20000);\r
+?>\r
--- /dev/null
+/* 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
--- /dev/null
+body\r
+{\r
+ margin: 0;\r
+ padding: 0;\r
+ font-family: Arial;\r
+ font-size: 80%;\r
+}\r
+\r
+form\r
+{\r
+ margin: 0;\r
+ padding: 0;\r
+ background-color: #ffffff;\r
+}\r
+\r
+label\r
+{\r
+ display: block;\r
+}\r
+\r
+label.checkbox\r
+{\r
+ display: inline;\r
+}\r
+\r
+div.field\r
+{\r
+ clear: both;\r
+ padding: 17px;\r
+}\r
+\r
+div.col-1,\r
+div.col-2\r
+{\r
+ float: left;\r
+}\r
+\r
+div.col-1\r
+{\r
+ margin-right: 10px;\r
+}\r
+\r
+input.checkbox\r
+{\r
+}\r
+\r
+input.input-number\r
+{\r
+ width: 70px;\r
+ margin-bottom: 10px;\r
+ border: 1px solid #cbcbcb;\r
+ background-color: #ffffff;\r
+}\r
+\r
+.main-actions\r
+{\r
+ background-color: #eaeaea;\r
+ border-top: 1px solid white;\r
+ border-bottom: 1px solid #d6d6d6;\r
+ padding: 0 10px 0 10px;\r
+ padding: 12px 10px 12px 10px;\r
+}\r
+\r
+#editimage\r
+{\r
+ margin: 0 10px 10px 10px;\r
+ position: relative;\r
+ top: 0px;\r
+ left: 0px;\r
+}\r
+\r
+div.error,\r
+div.info\r
+{\r
+ background-color: #ffc1c1;\r
+ padding: 5px;\r
+ margin: 0 10px 10px 10px;\r
+}\r
+\r
+div.error ul,\r
+div.info ul\r
+{\r
+ list-style-type: square;\r
+}\r
+\r
+div.error li,\r
+div.info li\r
+{\r
+ font-weight: bold;\r
+ margin-bottom: 5px;\r
+}\r
+\r
+div.croparea\r
+{\r
+ background-color: #ffffff;\r
+ filter:alpha(opacity=80);\r
+ -moz-opacity:.80;\r
+ opacity:.80;\r
+ overflow: hidden; \r
+}\r
+\r
+div#actionContainer\r
+{\r
+ background-color: #e1f3ff;\r
+ background-image: url('../images/tab_body.png');\r
+ background-repeat: repeat-x;\r
+}\r
+\r
+div#menu\r
+{\r
+ height: 30px;\r
+ overflow: hidden;\r
+ font-weight: bold;\r
+}\r
+\r
+.selected\r
+{\r
+ float: left;\r
+ color: #000000;\r
+ border-right: 1px solid #ffffff;\r
+ line-height: 30px;\r
+ padding: 0 20px 0 20px;\r
+ cursor: pointer;\r
+ height: 30px;\r
+ background-image: url('../images/tab_selected.png');\r
+ background-repeat: repeat-x;\r
+}\r
+\r
+.not-selected\r
+{\r
+ float: left;\r
+ color: #ffffff;\r
+ border-right: 1px solid #ffffff;\r
+ border-bottom: 1px solid #ffffff;\r
+ line-height: 30px;\r
+ padding: 0 20px 0 20px;\r
+ cursor: pointer;\r
+ height: 29px;\r
+ background-image: url('../images/tab_not_selected.png');\r
+ background-repeat: repeat-x;\r
+}\r
+\r
+.panel\r
+{\r
+ filter:alpha(opacity=0);\r
+ -moz-opacity:0;\r
+ opacity:0;\r
+ display: none; \r
+}\r
+\r
+.tabs\r
+{\r
+ margin: 10px;\r
+}\r
+\r
+.widthAndHeight\r
+{\r
+ height: 23px; \r
+ overflow: hidden;\r
+}\r
+\r
+#image\r
+{\r
+ position: absolute;\r
+ top: 0;\r
+ left: 0;\r
+}\r
+\r
+#loading\r
+{\r
+ border-top: 1px solid white;\r
+ background-color: #c7e7fc;\r
+ padding: 15px;\r
+ font-weight: bold;\r
+}\r
+\r
+#loading_bar\r
+{\r
+ margin-top: 3px;\r
+ background-color: #3d7ab0;\r
+ height: 3px;\r
+}\r
+\r
+#imageResizerKeepProportions,\r
+#imageResizerNoProportions\r
+{\r
+ background-color: #d6d6d6;\r
+ position: absolute; \r
+ left: 0px; \r
+ top: 0px;\r
+ filter:alpha(opacity=0);\r
+ -moz-opacity:.0;\r
+ opacity:.0; \r
+}\r
+\r
+.help\r
+{\r
+ background-color: #fffcd1;\r
+ line-height: 1.5em;\r
+ padding: 10px;\r
+ border: 1px solid #d8d8d8;\r
+}\r
+\r
+.help-header\r
+{\r
+ font-weight: bold;\r
+ text-transform: uppercase;\r
+}\r
+\r
+.help-content\r
+{\r
+}\r
+\r
+#crophelp\r
+{\r
+}\r
+\r
+.crop-settings\r
+{\r
+ background-color: #cde3f2;\r
+}\r
+\r
+.crop-top\r
+{\r
+ border-bottom: 1px solid #a8c6da;\r
+ padding-bottom: 8px;\r
+ margin-bottom: 8px;\r
+}
\ No newline at end of file
--- /dev/null
+/* 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
--- /dev/null
+/* 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; }
+\r
+ \r
+
+.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
--- /dev/null
+<?php\r
+ \r
+ /**\r
+ * constants.php\r
+ * \r
+ * PHP version 5.2\r
+ * \r
+ * @category Toolkit\r
+ * @package PHPImageEditor/includes\r
+ * @author Jamie Kahgee <steve@gaslightmedia.com>\r
+ * @copyright 2012 Gaslight Media\r
+ * @license Gaslight Media\r
+ * @version SVN: $id$\r
+ * @link <>\r
+ */\r
+ /*\r
+ Copyright 2008, 2009, 2010 Patrik Hultgren\r
+ \r
+ YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR.\r
+ OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT:\r
+ http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F\r
+ \r
+ This file is part of PHP Image Editor.\r
+\r
+ PHP Image Editor is free software: you can redistribute it and/or modify\r
+ it under the terms of the GNU General Public License as published by\r
+ the Free Software Foundation, either version 3 of the License, or\r
+ (at your option) any later version.\r
+\r
+ PHP Image Editor is distributed in the hope that it will be useful,\r
+ but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ GNU General Public License for more details.\r
+\r
+ You should have received a copy of the GNU General Public License\r
+ along with PHP Image Editor. If not, see <http://www.gnu.org/licenses/>.\r
+ */\r
+\r
+\r
+ define("PHP_VERSION_MINIMUM", "5");\r
+ define("GD_VERSION_MINIMUM", "2.0.28");\r
+ define("IMAGE_ORIGINAL_PATH", "editimagesoriginal/");\r
+ define("IMAGE_WORK_WITH_PATH", "editimagesworkwith/");\r
+ define("IMAGE_PNG_PATH", "editimagespng/");\r
+ define("MENU_RESIZE", "0");\r
+ define("MENU_ROTATE", "1");\r
+ define("MENU_CROP", "2");\r
+ define("MENU_EFFECTS", "3");\r
+?>
\ No newline at end of file
--- /dev/null
+<?php\r
+ \r
+ \r
+ /*\r
+ Copyright 2008, 2009, 2010 Patrik Hultgren\r
+ \r
+ YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR.\r
+ OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT:\r
+ http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F\r
+ \r
+ This file is part of PHP Image Editor.\r
+\r
+ PHP Image Editor is free software: you can redistribute it and/or modify\r
+ it under the terms of the GNU General Public License as published by\r
+ the Free Software Foundation, either version 3 of the License, or\r
+ (at your option) any later version.\r
+\r
+ PHP Image Editor is distributed in the hope that it will be useful,\r
+ but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ GNU General Public License for more details.\r
+\r
+ You should have received a copy of the GNU General Public License\r
+ along with PHP Image Editor. If not, see <http://www.gnu.org/licenses/>.\r
+ */\r
+\r
+\r
+ function PIE_GetTexts($filePath)\r
+ {\r
+ $texts = array();\r
+ $lines = file($filePath);\r
+ \r
+ foreach($lines as $line_num => $line)\r
+ {\r
+ if (substr_count($line, "#") == 0)\r
+ {\r
+ $keyAndText = explode("=", trim($line));\r
+ $texts[$keyAndText[0]] = $keyAndText[1];\r
+ }\r
+ }\r
+ \r
+ return $texts;\r
+ }\r
+ \r
+ function PIE_Echo($text)\r
+ {\r
+ echo $text;\r
+ //echo utf8_encode($text);\r
+ } \r
+?>
\ No newline at end of file
--- /dev/null
+<?php \r
+ \r
+ \r
+ /*\r
+ Copyright 2008, 2009, 2010 Patrik Hultgren\r
+ \r
+ YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR.\r
+ OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT:\r
+ http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F\r
+ \r
+ This file is part of PHP Image Editor.\r
+\r
+ PHP Image Editor is free software: you can redistribute it and/or modify\r
+ it under the terms of the GNU General Public License as published by\r
+ the Free Software Foundation, either version 3 of the License, or\r
+ (at your option) any later version.\r
+\r
+ PHP Image Editor is distributed in the hope that it will be useful,\r
+ but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ GNU General Public License for more details.\r
+\r
+ You should have received a copy of the GNU General Public License\r
+ along with PHP Image Editor. If not, see <http://www.gnu.org/licenses/>.\r
+ */\r
+\r
+ \r
+ \r
+ header("Cache-Control: no-store"); \r
+ header('content-type: text/html; charset: utf-8');\r
+ include 'includes/constants.php';\r
+ include 'config.php';\r
+ include 'includes/functions.php';\r
+ include 'classes/phpimageeditor.php';\r
+ global $objPHPImageEditor;\r
+ $objPHPImageEditor = new PHPImageEditor();\r
+?>\r
+<?php if (!$objPHPImageEditor->isAjaxPost) { ?>\r
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r
+<html xmlns="http://www.w3.org/1999/xhtml">\r
+ <head>\r
+ <title>PHP Image Editor</title>\r
+ <script type="text/javascript" src="javascript/jquery-1.3.2.min.js"></script>\r
+ <script type="text/javascript" src="javascript/jquery.jcrop.js"></script>\r
+ <script type="text/javascript" src="javascript/jquery.numeric.js"></script>\r
+ <script type="text/javascript" src="javascript/ui.core.js"></script>\r
+ <script type="text/javascript" src="javascript/ui.slider.js"></script>\r
+ <script type="text/javascript" src="javascript/ui.resizable.js"></script>\r
+ <script type="text/javascript" src="javascript/effects.core.js"></script>\r
+ <script type="text/javascript" src="javascript/phpimageeditor.js"></script>\r
+ \r
+ <link rel="stylesheet" type="text/css" href="css/style.css"/>\r
+ <link rel="stylesheet" type="text/css" href="css/ui.resizable.css"/>\r
+ <link rel="stylesheet" type="text/css" href="css/ui.slider.css"/>\r
+ <link rel="stylesheet" type="text/css" href="css/jquery.jcrop.css"/>\r
+ \r
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\r
+ \r
+ <script type="text/javascript">\r
+ var ImageMaxWidth = <?php PIE_Echo(IMAGE_MAX_WIDTH); ?>;\r
+ var ImageMaxHeight = <?php PIE_Echo(IMAGE_MAX_HEIGHT); ?>;\r
+ var ImageWidth = <?php PIE_Echo($objPHPImageEditor->GetWidthFinal()); ?>;\r
+ var ImageHeight = <?php PIE_Echo($objPHPImageEditor->GetHeightFinal()); ?>;\r
+ var TextIsRequired = "<?php PIE_Echo($objPHPImageEditor->texts["IS REQUIRED"]); ?>";\r
+ var TextMustBeNumeric = "<?php PIE_Echo($objPHPImageEditor->texts["MUST BE NUMERIC"]); ?>";\r
+ var TextWidth = "<?php PIE_Echo($objPHPImageEditor->texts["WIDTH"]); ?>";\r
+ var TextHeight = "<?php PIE_Echo($objPHPImageEditor->texts["HEIGHT"]); ?>";\r
+ var TextNotNegative = "<?php PIE_Echo($objPHPImageEditor->texts["NOT NEGATIVE"]); ?>";\r
+ var TextNotInRange = "<?php PIE_Echo($objPHPImageEditor->texts["NOT IN RANGE"]); ?>";\r
+ var TextCantBeLargerThen = "<?php PIE_Echo($objPHPImageEditor->texts["CANT BE LARGER THEN"]); ?>";\r
+ var TextAnUnexpectedError = "<?php PIE_Echo($objPHPImageEditor->texts["AN UNEXPECTED ERROR"]); ?>";\r
+ var Brightness = <?php PIE_Echo($objPHPImageEditor->inputBrightness); ?>;\r
+ var Contrast = <?php PIE_Echo($objPHPImageEditor->inputContrast); ?>;\r
+ var BrightnessMax = <?php PIE_Echo($objPHPImageEditor->brightnessMax); ?>;\r
+ var ContrastMax = <?php PIE_Echo($objPHPImageEditor->contrastMax); ?>;\r
+ var FormAction = "<?php PIE_Echo($objPHPImageEditor->GetFormAction()); ?>";\r
+ var FormId = "<?php PIE_Echo($objPHPImageEditor->formName); ?>";\r
+ var ActionUpdate = "<?php PIE_Echo($objPHPImageEditor->actionUpdate); ?>";\r
+ var ActionUndo = "<?php PIE_Echo($objPHPImageEditor->actionUndo); ?>";\r
+ var ActionSaveAndClose = "<?php PIE_Echo($objPHPImageEditor->actionSaveAndClose); ?>";\r
+ var ActionRotateLeft = "<?php PIE_Echo($objPHPImageEditor->actionRotateLeft); ?>";\r
+ var ActionRotateRight = "<?php PIE_Echo($objPHPImageEditor->actionRotateRight); ?>";\r
+ var ActionSaveAndClose = "<?php PIE_Echo($objPHPImageEditor->actionSaveAndClose); ?>";\r
+ var MenuResize = "<?php PIE_Echo(MENU_RESIZE); ?>";\r
+ var MenuRotate = "<?php PIE_Echo(MENU_ROTATE); ?>";\r
+ var MenuCrop = "<?php PIE_Echo(MENU_CROP); ?>";\r
+ var MenuEffects = "<?php PIE_Echo(MENU_EFFECTS); ?>";\r
+ var AjaxPostTimeoutMs = <?php PIE_Echo(AJAX_POST_TIMEOUT_MS); ?>; \r
+ </script>\r
+ </head>\r
+ <body>\r
+ <div id="phpImageEditor">\r
+<?php } ?>\r
+\r
+ <form id="<?php PIE_Echo($objPHPImageEditor->formName); ?>" name="<?php PIE_Echo($objPHPImageEditor->formName); ?>" method="post" action="<?php PIE_Echo($objPHPImageEditor->GetFormAction()); ?>">\r
+ <?php if (!$objPHPImageEditor->ErrorHasOccurred()) { ?>\r
+ \r
+ <div class="tabs">\r
+ \r
+ <div id="menu">\r
+ <div class="<?php PIE_Echo($objPHPImageEditor->inputPanel == MENU_RESIZE ? 'selected' : 'not-selected'); ?>" id="menuitem_<?php PIE_Echo(MENU_RESIZE); ?>">\r
+ <?php PIE_Echo($objPHPImageEditor->texts["RESIZE IMAGE"]); ?>\r
+ </div>\r
+ <!--\r
+ <div class="<?php PIE_Echo($objPHPImageEditor->inputPanel == MENU_ROTATE ? 'selected' : 'not-selected'); ?>" id="menuitem_<?php PIE_Echo(MENU_ROTATE); ?>">\r
+ <?php PIE_Echo($objPHPImageEditor->texts["ROTATE IMAGE"]); ?>\r
+ </div>\r
+ -->\r
+ <div class="<?php PIE_Echo($objPHPImageEditor->inputPanel == MENU_CROP ? 'selected' : 'not-selected'); ?>" id="menuitem_<?php PIE_Echo(MENU_CROP); ?>">\r
+ <?php PIE_Echo($objPHPImageEditor->texts["CROP IMAGE"]); ?>\r
+ </div>\r
+ <!--\r
+ <?php if ($objPHPImageEditor->IsPHP5OrHigher()) { ?>\r
+ <div class="<?php PIE_Echo($objPHPImageEditor->inputPanel == MENU_EFFECTS ? 'selected' : 'not-selected'); ?>" id="menuitem_<?php PIE_Echo(MENU_EFFECTS); ?>">\r
+ <?php PIE_Echo($objPHPImageEditor->texts["EFFECTS"]); ?>\r
+ </div>\r
+ <?php } ?>\r
+ -->\r
+ </div>\r
+ \r
+ <div id="actionContainer">\r
+ \r
+ <div id="panel_<?php PIE_Echo(MENU_RESIZE); ?>" class="panel">\r
+ <table cellpadding="0" cellspacing="0" border="0">\r
+ <tr>\r
+ <td>\r
+ <div class="field widthAndHeight">\r
+ <div class="col-1">\r
+ <label for="width"><?php PIE_Echo($objPHPImageEditor->texts["WIDTH"]); ?></label>\r
+ <input class="input-number" type="text" name="width" id="width" value="<?php PIE_Echo($objPHPImageEditor->GetWidthFinal()); ?>"/>\r
+ <input type="hidden" name="widthoriginal" id="widthoriginal" value="<?php PIE_Echo($objPHPImageEditor->GetWidth()); ?>"/>\r
+ </div>\r
+ <div class="col-2">\r
+ <label for="height"><?php PIE_Echo($objPHPImageEditor->texts["HEIGHT"]); ?></label>\r
+ <input class="input-number" type="text" name="height" id="height" value="<?php PIE_Echo($objPHPImageEditor->GetHeightFinal()); ?>"/>\r
+ <input type="hidden" name="heightoriginal" id="heightoriginal" value="<?php PIE_Echo($objPHPImageEditor->GetHeight()); ?>"/>\r
+ </div>\r
+ </div>\r
+ <div class="field">\r
+ <input class="checkbox" type="checkbox" name="<?php PIE_Echo($objPHPImageEditor->fieldNameKeepProportions); ?>" id="<?php PIE_Echo($objPHPImageEditor->fieldNameKeepProportions); ?>" <?php PIE_Echo($objPHPImageEditor->inputKeepProportions ? 'checked="checked"' : ''); ?>/>\r
+ <input type="hidden" name="keepproportionsval" id="keepproportionsval" value="<?php PIE_Echo($objPHPImageEditor->inputKeepProportions ? '1' : '0'); ?>"/>\r
+ <label for="<?php PIE_Echo($objPHPImageEditor->fieldNameKeepProportions); ?>" class="checkbox"><?php PIE_Echo($objPHPImageEditor->texts["KEEP PROPORTIONS"]); ?></label>\r
+ </div>\r
+ </td>\r
+ <td>\r
+ <div class="help" id="resizehelp">\r
+ <div class="help-header" id="resizehelpheader"><?php PIE_Echo($objPHPImageEditor->texts["INSTRUCTIONS"]); ?></div>\r
+ <div class="help-content" id="resizehelpcontent"><?php PIE_Echo($objPHPImageEditor->texts["RESIZE HELP"]); ?></div>\r
+ </div>\r
+ </td>\r
+ </tr>\r
+ </table>\r
+ </div>\r
+ \r
+ <div id="panel_<?php PIE_Echo(MENU_ROTATE); ?>" class="panel">\r
+ <div class="field">\r
+ <input id="btnRotateLeft" type="button" value="<?php PIE_Echo($objPHPImageEditor->texts["LEFT 90 DEGREES"]); ?>"/>\r
+ <input id="btnRotateRight" type="button" value="<?php PIE_Echo($objPHPImageEditor->texts["RIGHT 90 DEGREES"]); ?>"/>\r
+ <input type="hidden" name="rotate" id="rotate" value="-1"/>\r
+ </div>\r
+ </div>\r
+ \r
+ <div id="panel_<?php PIE_Echo(MENU_CROP); ?>" class="panel">\r
+ <div class="field">\r
+ <input class="input-number" type="hidden" name="croptop" id="croptop" value="0"/>\r
+ <input class="input-number" type="hidden" name="cropleft" id="cropleft" value="0"/>\r
+ <input class="input-number" type="hidden" name="cropright" id="cropright" value="0"/>\r
+ <input class="input-number" type="hidden" name="cropbottom" id="cropbottom" value="0"/>\r
+ <div class="help" id="crophelp">\r
+ <div class="help-header" id="crophelpheader"><?php PIE_Echo($objPHPImageEditor->texts["INSTRUCTIONS"]); ?></div>\r
+ <div class="help-content" id="crophelpcontent"><?php PIE_Echo($objPHPImageEditor->texts["CROP HELP"]); ?></div>\r
+ </div>\r
+ </div>\r
+ <div class="field crop-settings">\r
+ <div class="crop-top">\r
+ <?php PIE_Echo($objPHPImageEditor->texts["CROP WIDTH"]); ?>: <span id="cropwidth">0</span>\r
+ <?php PIE_Echo($objPHPImageEditor->texts["CROP HEIGHT"]); ?>: <span id="cropheight">0</span>\r
+ </div>\r
+ <input id="cropkeepproportions" class="checkbox" type="checkbox" name="cropkeepproportions" <?php PIE_Echo($objPHPImageEditor->inputCropKeepProportions ? 'checked="checked"' : ''); ?>/>\r
+ <label class="checkbox" for="cropkeepproportions"><?php PIE_Echo($objPHPImageEditor->texts["CROP KEEP PROPORTIONS"]); ?></label>\r
+ <input id="cropkeepproportionsval" type="hidden" name="cropkeepproportionsval" value="<?php PIE_Echo($objPHPImageEditor->inputCropKeepProportions ? '1' : '0'); ?>"/> \r
+ <input id="cropkeepproportionsratio" type="hidden" name="cropkeepproportionsratio" value="<?php PIE_Echo($objPHPImageEditor->inputCropKeepProportionsRatio); ?>"/> \r
+ </div>\r
+ </div>\r
+ <div id="panel_<?php PIE_Echo(MENU_EFFECTS); ?>" class="panel" style="display: <?php PIE_Echo($objPHPImageEditor->IsPHP5OrHigher() ? 'block' : 'none'); ?>;">\r
+ <div class="field">\r
+ <label for="brightness"><?php PIE_Echo($objPHPImageEditor->texts["BRIGHTNESS"]); ?></label>\r
+ <div id="brightness_slider_track"></div>\r
+ </div>\r
+ <input type="hidden" name="brightness" id="brightness" value="<?php PIE_Echo($objPHPImageEditor->inputBrightness); ?>"/>\r
+ <div class="field">\r
+ <label for="contrast"><?php PIE_Echo($objPHPImageEditor->texts["CONTRAST"]); ?></label>\r
+ <div id="contrast_slider_track"></div>\r
+ </div>\r
+ <input type="hidden" name="contrast" id="contrast" value="<?php PIE_Echo($objPHPImageEditor->inputContrast); ?>"/>\r
+ <div class="field">\r
+ <input class="checkbox" type="checkbox" name="<?php PIE_Echo($objPHPImageEditor->actionGrayscale); ?>" id="<?php PIE_Echo($objPHPImageEditor->actionGrayscale); ?>" <?php PIE_Echo($objPHPImageEditor->inputGrayscale ? 'checked="checked"' : ''); ?>/>\r
+ <label for="<?php PIE_Echo($objPHPImageEditor->actionGrayscale); ?>" class="checkbox"><?php PIE_Echo($objPHPImageEditor->texts["GRAYSCALE"]); ?></label>\r
+ <input type="hidden" name="grayscaleval" id="grayscaleval" value="<?php PIE_Echo($objPHPImageEditor->inputGrayscale ? '1' : '0'); ?>"/>\r
+ </div>\r
+ </div>\r
+ <div id="loading" style="display: none;"><?php PIE_Echo($objPHPImageEditor->texts["LOADING"]); ?>...<div id="loading_bar" style="width: 0px;"></div></div>\r
+ \r
+ </div>\r
+ \r
+ <div class="main-actions">\r
+ <input type="button" id="btnupdate" name="btnupdate" value="<?php PIE_Echo($objPHPImageEditor->texts["UPDATE"]); ?>"/>\r
+ <input type="button" <?php PIE_Echo($objPHPImageEditor->actions == "" ? 'disabled="disabled"' : ''); ?> id="btnsave" name="btnsave" value="<?php PIE_Echo($objPHPImageEditor->texts["SAVE AND CLOSE"]); ?>"/>\r
+ <input type="button" <?php PIE_Echo($objPHPImageEditor->actions == "" ? 'disabled="disabled"' : ''); ?> id="btnundo" name="btnundo" value="<?php PIE_Echo($objPHPImageEditor->texts["UNDO"]); ?>"/>\r
+ </div>\r
+ <div class="field">\r
+ <label><input type="text" id="image_name" name="image_name" value="<?php PIE_Echo(urldecode($objPHPImageEditor->GetImageNameFinal())); ?>" /></label>\r
+ </div>\r
+ \r
+ </div>\r
+ <input type="hidden" name="actiontype" id="actiontype" value="<?php PIE_Echo($objPHPImageEditor->actionUpdate); ?>"/>\r
+ <input type="hidden" name="panel" id="panel" value="<?php PIE_Echo($objPHPImageEditor->inputPanel); ?>"/>\r
+ <input type="hidden" name="language" id="language" value="<?php PIE_Echo($objPHPImageEditor->inputLanguage); ?>"/>\r
+ <input type="hidden" name="actions" id="actions" style="width: 1000px;" value="<?php $objPHPImageEditor->GetActions(); ?>"/>\r
+ <input type="hidden" name="imageNameLast" id="imageNameLast" value="<?php PIE_Echo($objPHPImageEditor->GetImageNameFinal()); ?>" />\r
+ <input type="hidden" name="widthlast" id="widthlast" value="<?php PIE_Echo($objPHPImageEditor->GetWidthFinal()); ?>"/>\r
+ <input type="hidden" name="heightlast" id="heightlast" value="<?php PIE_Echo($objPHPImageEditor->GetHeightFinal()); ?>"/>\r
+ <input type="hidden" name="widthlastbeforeresize" id="widthlastbeforeresize" value="<?php PIE_Echo($objPHPImageEditor->GetWidthKeepProportions()); ?>"/>\r
+ <input type="hidden" name="heightlastbeforeresize" id="heightlastbeforeresize" value="<?php PIE_Echo($objPHPImageEditor->GetHeightKeepProportions()); ?>"/>\r
+ <input type="hidden" name="userid" id="userid" value="<?php PIE_Echo($objPHPImageEditor->userId); ?>"/>\r
+ <input type="hidden" name="contrastlast" id="contrastlast" value="<?php PIE_Echo($objPHPImageEditor->inputContrast); ?>"/>\r
+ <input type="hidden" name="brightnesslast" id="brightnesslast" value="<?php PIE_Echo($objPHPImageEditor->inputBrightness); ?>"/>\r
+ <input type="hidden" name="isajaxpost" id="isajaxpost" value="false"/>\r
+ <?php } ?>\r
+ </form>\r
+ <?php $objPHPImageEditor->GetErrorMessages(); ?>\r
+ <div id="divJsErrors" class="error" style="display: none;">\r
+ <ul id="ulJsErrors" style="display: none;"><li></li></ul>\r
+ </div>\r
+ <div><img src="images/empty.gif" alt=""/></div>\r
+ <?php if (!$objPHPImageEditor->ErrorHasOccurred()) { ?>\r
+ <div id="editimage">\r
+ <img id="image" style="position: absolute; left: 0px; top: 0px; width: <?php PIE_Echo($objPHPImageEditor->GetWidthFinal()); ?>px; height: <?php PIE_Echo($objPHPImageEditor->GetHeightFinal()); ?>px;" alt="" src="<?php PIE_Echo($objPHPImageEditor->srcWorkWith); ?>?timestamp=<?php PIE_Echo(time()); ?>"/>\r
+ <div id="imageResizerKeepProportions" style="diplay: <?php PIE_Echo(($objPHPImageEditor->inputKeepProportions && $objPHPImageEditor->inputPanel == MENU_RESIZE) ? 'block' : 'none'); ?>; width: <?php PIE_Echo($objPHPImageEditor->GetWidthFinal()); ?>px; height: <?php PIE_Echo($objPHPImageEditor->GetHeightFinal()); ?>px;"></div>\r
+ <div id="imageResizerNoProportions" style="diplay: <?php PIE_Echo((!$objPHPImageEditor->inputKeepProportions && $objPHPImageEditor->inputPanel == MENU_RESIZE) ? 'block' : 'none'); ?>; width: <?php PIE_Echo($objPHPImageEditor->GetWidthFinal()); ?>px; height: <?php PIE_Echo($objPHPImageEditor->GetHeightFinal()); ?>px;"></div>\r
+ </div> \r
+ <?php } ?>\r
+\r
+<?php if (!$objPHPImageEditor->isAjaxPost) { ?>\r
+ </div>\r
+ </body>\r
+ </html>\r
+<?php } ?>\r
+\r
+<?php $objPHPImageEditor->CleanUp(); ?>
\ No newline at end of file
--- /dev/null
+/*
+ * 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('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');
+ 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);
--- /dev/null
+String.prototype.phpimageeditor_add_editlink_endswith = function(str) \r
+{\r
+ return (this.match(str+"$")==str);\r
+}\r
+\r
+function phpimageeditor_add_editlink(pathToEditor, pathToPlugin, hostPath, editImageText, language)\r
+{\r
+ var mediamanagerForm = document.getElementById("mediamanager-form");\r
+ if (mediamanagerForm != null)\r
+ {\r
+ var trs = mediamanagerForm.getElementsByTagName("tr");\r
+ var modeDetailed = (trs.length > 0);\r
+ \r
+ if (modeDetailed)\r
+ {\r
+ var isTableHeader = true;\r
+ \r
+ for(var i=0;i<trs.length;i++)\r
+ {\r
+ if (isTableHeader)\r
+ {\r
+ var th = document.createElement("th");\r
+ th.appendChild(document.createTextNode(editImageText));\r
+ trs[i].appendChild(th);\r
+ }\r
+ else \r
+ {\r
+ var td = document.createElement("td");\r
+ \r
+ var imageSrcDetailed = "";\r
+ var links = trs[i].getElementsByTagName("a");\r
+ var foundDetailedImage = false;\r
+\r
+ for(var c=0;c<links.length;c++)\r
+ {\r
+ if (links[c].className == 'img-preview')\r
+ {\r
+ imageSrcDetailed = phpimageeditor_urlencode(links[c].href.replace(hostPath,'../../../')); \r
+ \r
+ if (phpimageeditor_file_is_image(imageSrcDetailed))\r
+ {\r
+ if (trs[i].innerHTML.indexOf('folderup_16.png') == -1 && trs[i].innerHTML.indexOf('folder_sm.png') == -1)\r
+ {\r
+ td.innerHTML = '<div><a style="background-position: 5px 0; background-image: url('+pathToPlugin+'images/edit.gif); background-repeat: no-repeat; padding-bottom: 4px; padding-left: 22px;" href="'+pathToEditor+imageSrcDetailed+'&language='+language+'" target="_blank">'+editImageText+'</a></div>';\r
+ foundDetailedImage = true;\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ if (!foundDetailedImage)\r
+ td.innerHTML = " ";\r
+\r
+ trs[i].appendChild(td);\r
+ }\r
+ \r
+ isTableHeader = false; \r
+ }\r
+ }\r
+ else\r
+ {\r
+ var e = mediamanagerForm.getElementsByTagName("div");\r
+ \r
+ for(var i=0;i<e.length;i++)\r
+ {\r
+ if (e[i].className == 'imgOutline' && e[i].innerHTML.indexOf('folderup_32.png') == -1 && e[i].innerHTML.indexOf('folder.png') == -1)\r
+ {\r
+ var images = e[i].getElementsByTagName("img");\r
+ var imageSrc = "";\r
+ \r
+ if (images.length > 0)\r
+ {\r
+ imageSrc = phpimageeditor_urlencode(images[0].src.replace(hostPath,'../../../'));\r
+ \r
+ if (phpimageeditor_file_is_image(imageSrc))\r
+ e[i].innerHTML += '<a style="background-position: 5px 0; background-image: url('+pathToPlugin+'images/edit.gif); background-repeat: no-repeat; padding-bottom: 4px; padding-left: 22px; display: block;" href="'+pathToEditor+imageSrc+'&language='+language+'" target="_blank">'+editImageText+'</a>';\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+ else\r
+ {\r
+ var articledivs = document.getElementsByTagName("div");\r
+ var foundManager = false;\r
+ var foundItem = false;\r
+ for(var i=0;i<articledivs.length;i++)\r
+ {\r
+ if (articledivs[i].className == 'manager')\r
+ foundManager = true;\r
+ else if (articledivs[i].className == 'item')\r
+ foundItem = true;\r
+ \r
+ if (foundManager && foundItem)\r
+ break;\r
+ } \r
+ \r
+ if (foundManager && foundItem)\r
+ {\r
+ for(var i=0;i<articledivs.length;i++)\r
+ {\r
+ if (articledivs[i].className == 'item')\r
+ {\r
+ var imagesArticle = articledivs[i].getElementsByTagName("img");\r
+ var imageSrcArticle = "";\r
+ \r
+ if (imagesArticle.length > 0 && imagesArticle[0].src.indexOf('folder.gif') == -1 && phpimageeditor_file_is_image(imagesArticle[0].src))\r
+ {\r
+ imageSrcArticle = phpimageeditor_urlencode(imagesArticle[0].src.replace(hostPath,'../../../'));\r
+ articledivs[i].innerHTML = '<a style="position: absolute; top: 0; left: 0; background-color: #eeeeee; display: block; line-height: 15px; height: auto;" href="'+pathToEditor+imageSrcArticle+'&language='+language+'" target="_blank">'+editImageText+'</a>' + articledivs[i].innerHTML;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+}\r
+\r
+function phpimageeditor_urlencode(str) \r
+{\r
+ // http://kevin.vanzonneveld.net\r
+ // + original by: Philip Peterson\r
+ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\r
+ // + input by: AJ\r
+ // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\r
+ // % note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/\r
+ // * example 1: urlencode('Kevin van Zonneveld!');\r
+ // * returns 1: 'Kevin+van+Zonneveld%21'\r
+ // * example 2: urlencode('http://kevin.vanzonneveld.net/');\r
+ // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'\r
+ // * 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');\r
+ // * 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'\r
+ \r
+ var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];\r
+ var ret = str.toString();\r
+ \r
+ var replacer = function(search, replace, str) {\r
+ var tmp_arr = [];\r
+ tmp_arr = str.split(search);\r
+ return tmp_arr.join(replace);\r
+ };\r
+ \r
+ // The histogram is identical to the one in urldecode.\r
+ histogram['!'] = '%21';\r
+ histogram['%20'] = '+';\r
+ \r
+ // Begin with encodeURIComponent, which most resembles PHP's encoding functions\r
+ ret = encodeURIComponent(ret);\r
+ \r
+ for (search in histogram) {\r
+ replace = histogram[search];\r
+ ret = replacer(search, replace, ret) // Custom replace. No regexing\r
+ }\r
+ \r
+ // Uppercase for full PHP compatibility\r
+ return ret.replace('/(\%([a-z0-9]{2}))/g', function(full, m1, m2) {\r
+ return "%"+m2.toUpperCase();\r
+ });\r
+ \r
+ return ret;\r
+}\r
+\r
+function phpimageeditor_file_is_image(filePath)\r
+{\r
+ filePath = filePath.toLowerCase();\r
+ return (filePath.indexOf('com_media') == -1 && (filePath.phpimageeditor_add_editlink_endswith("jpg") || filePath.phpimageeditor_add_editlink_endswith("gif") || filePath.phpimageeditor_add_editlink_endswith("png")));\r
+}
\ No newline at end of file
--- /dev/null
+/*
+ * 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<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=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;G<E;G++){L.call(K(this[G],H),this.length>1||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<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-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("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!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;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?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<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":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<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=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 U<T[3]-0},gt:function(V,U,T){return U>T[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<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=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<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+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="<a href='#'></a>";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="<p class='TEST'></p>";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="<div class='test e'></div><div class='test'></div>";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;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){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;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';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("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
\ No newline at end of file
--- /dev/null
+/**
+ * jquery.Jcrop.js v0.9.8
+ * jQuery Image Cropping Plugin
+ * @author Kelly Hallman <khallman@gmail.com>
+ * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+
+ * }}}
+ */
+
+(function($) {
+
+$.Jcrop = function(obj,opt)
+{
+ // Initialization {{{
+
+ // Sanitize some options {{{
+ var obj = obj, opt = opt;
+
+ if (typeof(obj) !== 'object') obj = $(obj)[0];
+ if (typeof(opt) !== 'object') opt = { };
+
+ // Some on-the-fly fixes for MSIE...sigh
+ if (!('trackDocument' in opt))
+ {
+ opt.trackDocument = $.browser.msie ? false : true;
+ if ($.browser.msie && $.browser.version.split('.')[0] == '8')
+ opt.trackDocument = true;
+ }
+
+ if (!('keySupport' in opt))
+ opt.keySupport = $.browser.msie ? false : true;
+
+ // }}}
+ // Extend the default options {{{
+ var defaults = {
+
+ // Basic Settings
+ trackDocument: false,
+ baseClass: 'jcrop',
+ addClass: null,
+
+ // Styling Options
+ bgColor: 'black',
+ bgOpacity: .6,
+ borderOpacity: .4,
+ handleOpacity: .5,
+
+ handlePad: 5,
+ handleSize: 9,
+ handleOffset: 5,
+ edgeMargin: 14,
+
+ aspectRatio: 0,
+ keySupport: true,
+ cornerHandles: true,
+ sideHandles: true,
+ drawBorders: true,
+ dragEdges: true,
+
+ boxWidth: 0,
+ boxHeight: 0,
+
+ boundary: 8,
+ animationDelay: 20,
+ swingSpeed: 3,
+
+ allowSelect: true,
+ allowMove: true,
+ allowResize: true,
+
+ minSelect: [ 0, 0 ],
+ maxSize: [ 0, 0 ],
+ minSize: [ 0, 0 ],
+
+ // Callbacks / Event Handlers
+ onChange: function() { },
+ onSelect: function() { }
+
+ };
+ var options = defaults;
+ setOptions(opt);
+
+ // }}}
+ // Initialize some jQuery objects {{{
+
+ var $origimg = $(obj);
+ var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' });
+
+ $img.width($origimg.width());
+ $img.height($origimg.height());
+ $origimg.after($img).hide();
+
+ presize($img,options.boxWidth,options.boxHeight);
+
+ var boundx = $img.width(),
+ boundy = $img.height(),
+
+ $div = $('<div />')
+ .width(boundx).height(boundy)
+ .addClass(cssClass('holder'))
+ .css({
+ position: 'relative',
+ backgroundColor: options.bgColor
+ }).insertAfter($origimg).append($img);
+ ;
+
+ if (options.addClass) $div.addClass(options.addClass);
+ //$img.wrap($div);
+
+ var $img2 = $('<img />')/*{{{*/
+ .attr('src',$img.attr('src'))
+ .css('position','absolute')
+ .width(boundx).height(boundy)
+ ;/*}}}*/
+ var $img_holder = $('<div />')/*{{{*/
+ .width(pct(100)).height(pct(100))
+ .css({
+ zIndex: 310,
+ position: 'absolute',
+ overflow: 'hidden'
+ })
+ .append($img2)
+ ;/*}}}*/
+ var $hdl_holder = $('<div />')/*{{{*/
+ .width(pct(100)).height(pct(100))
+ .css('zIndex',320);
+ /*}}}*/
+ var $sel = $('<div />')/*{{{*/
+ .css({
+ position: 'absolute',
+ zIndex: 300
+ })
+ .insertBefore($img)
+ .append($img_holder,$hdl_holder)
+ ;/*}}}*/
+
+ var bound = options.boundary;
+ var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2))
+ .css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 })
+ .mousedown(newSelection);
+
+ /* }}} */
+ // Set more variables {{{
+
+ var xlimit, ylimit, xmin, ymin;
+ var xscale, yscale, enabled = true;
+ var docOffset = getPos($img),
+ // Internal states
+ btndown, lastcurs, dimmed, animating,
+ shift_down;
+
+ // }}}
+
+
+ // }}}
+ // Internal Modules {{{
+
+ var Coords = function()/*{{{*/
+ {
+ var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy;
+
+ function setPressed(pos)/*{{{*/
+ {
+ var pos = rebound(pos);
+ x2 = x1 = pos[0];
+ y2 = y1 = pos[1];
+ };
+ /*}}}*/
+ function setCurrent(pos)/*{{{*/
+ {
+ var pos = rebound(pos);
+ ox = pos[0] - x2;
+ oy = pos[1] - y2;
+ x2 = pos[0];
+ y2 = pos[1];
+ };
+ /*}}}*/
+ function getOffset()/*{{{*/
+ {
+ return [ ox, oy ];
+ };
+ /*}}}*/
+ function moveOffset(offset)/*{{{*/
+ {
+ var ox = offset[0], oy = offset[1];
+
+ if (0 > x1 + ox) ox -= ox + x1;
+ if (0 > y1 + oy) oy -= oy + y1;
+
+ if (boundy < y2 + oy) oy += boundy - (y2 + oy);
+ if (boundx < x2 + ox) ox += boundx - (x2 + ox);
+
+ x1 += ox;
+ x2 += ox;
+ y1 += oy;
+ y2 += oy;
+ };
+ /*}}}*/
+ function getCorner(ord)/*{{{*/
+ {
+ var c = getFixed();
+ switch(ord)
+ {
+ case 'ne': return [ c.x2, c.y ];
+ case 'nw': return [ c.x, c.y ];
+ case 'se': return [ c.x2, c.y2 ];
+ case 'sw': return [ c.x, c.y2 ];
+ }
+ };
+ /*}}}*/
+ function getFixed()/*{{{*/
+ {
+ if (!options.aspectRatio) return getRect();
+ // This function could use some optimization I think...
+ var aspect = options.aspectRatio,
+ min_x = options.minSize[0]/xscale,
+ min_y = options.minSize[1]/yscale,
+ max_x = options.maxSize[0]/xscale,
+ max_y = options.maxSize[1]/yscale,
+ rw = x2 - x1,
+ rh = y2 - y1,
+ rwa = Math.abs(rw),
+ rha = Math.abs(rh),
+ real_ratio = rwa / rha,
+ xx, yy
+ ;
+ if (max_x == 0) { max_x = boundx * 10 }
+ if (max_y == 0) { max_y = boundy * 10 }
+ if (real_ratio < aspect)
+ {
+ yy = y2;
+ w = rha * aspect;
+ xx = rw < 0 ? x1 - w : w + x1;
+
+ if (xx < 0)
+ {
+ xx = 0;
+ h = Math.abs((xx - x1) / aspect);
+ yy = rh < 0 ? y1 - h: h + y1;
+ }
+ else if (xx > boundx)
+ {
+ xx = boundx;
+ h = Math.abs((xx - x1) / aspect);
+ yy = rh < 0 ? y1 - h : h + y1;
+ }
+ }
+ else
+ {
+ xx = x2;
+ h = rwa / aspect;
+ yy = rh < 0 ? y1 - h : y1 + h;
+ if (yy < 0)
+ {
+ yy = 0;
+ w = Math.abs((yy - y1) * aspect);
+ xx = rw < 0 ? x1 - w : w + x1;
+ }
+ else if (yy > boundy)
+ {
+ yy = boundy;
+ w = Math.abs(yy - y1) * aspect;
+ xx = rw < 0 ? x1 - w : w + x1;
+ }
+ }
+
+ // Magic %-)
+ if(xx > x1) { // right side
+ if(xx - x1 < min_x) {
+ xx = x1 + min_x;
+ } else if (xx - x1 > max_x) {
+ xx = x1 + max_x;
+ }
+ if(yy > y1) {
+ yy = y1 + (xx - x1)/aspect;
+ } else {
+ yy = y1 - (xx - x1)/aspect;
+ }
+ } else if (xx < x1) { // left side
+ if(x1 - xx < min_x) {
+ xx = x1 - min_x
+ } else if (x1 - xx > max_x) {
+ xx = x1 - max_x;
+ }
+ if(yy > y1) {
+ yy = y1 + (x1 - xx)/aspect;
+ } else {
+ yy = y1 - (x1 - xx)/aspect;
+ }
+ }
+
+ if(xx < 0) {
+ x1 -= xx;
+ xx = 0;
+ } else if (xx > boundx) {
+ x1 -= xx - boundx;
+ xx = boundx;
+ }
+
+ if(yy < 0) {
+ y1 -= yy;
+ yy = 0;
+ } else if (yy > boundy) {
+ y1 -= yy - boundy;
+ yy = boundy;
+ }
+
+ return last = makeObj(flipCoords(x1,y1,xx,yy));
+ };
+ /*}}}*/
+ function rebound(p)/*{{{*/
+ {
+ if (p[0] < 0) p[0] = 0;
+ if (p[1] < 0) p[1] = 0;
+
+ if (p[0] > boundx) p[0] = boundx;
+ if (p[1] > boundy) p[1] = boundy;
+
+ return [ p[0], p[1] ];
+ };
+ /*}}}*/
+ function flipCoords(x1,y1,x2,y2)/*{{{*/
+ {
+ var xa = x1, xb = x2, ya = y1, yb = y2;
+ if (x2 < x1)
+ {
+ xa = x2;
+ xb = x1;
+ }
+ if (y2 < y1)
+ {
+ ya = y2;
+ yb = y1;
+ }
+ return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ];
+ };
+ /*}}}*/
+ function getRect()/*{{{*/
+ {
+ var xsize = x2 - x1;
+ var ysize = y2 - y1;
+
+ if (xlimit && (Math.abs(xsize) > xlimit))
+ x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
+ if (ylimit && (Math.abs(ysize) > ylimit))
+ y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);
+
+ if (ymin && (Math.abs(ysize) < ymin))
+ y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin);
+ if (xmin && (Math.abs(xsize) < xmin))
+ x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin);
+
+ if (x1 < 0) { x2 -= x1; x1 -= x1; }
+ if (y1 < 0) { y2 -= y1; y1 -= y1; }
+ if (x2 < 0) { x1 -= x2; x2 -= x2; }
+ if (y2 < 0) { y1 -= y2; y2 -= y2; }
+ if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; }
+ if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; }
+ if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; }
+ if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; }
+
+ return makeObj(flipCoords(x1,y1,x2,y2));
+ };
+ /*}}}*/
+ function makeObj(a)/*{{{*/
+ {
+ return { x: a[0], y: a[1], x2: a[2], y2: a[3],
+ w: a[2] - a[0], h: a[3] - a[1] };
+ };
+ /*}}}*/
+
+ return {
+ flipCoords: flipCoords,
+ setPressed: setPressed,
+ setCurrent: setCurrent,
+ getOffset: getOffset,
+ moveOffset: moveOffset,
+ getCorner: getCorner,
+ getFixed: getFixed
+ };
+ }();
+
+ /*}}}*/
+ var Selection = function()/*{{{*/
+ {
+ var start, end, dragmode, awake, hdep = 370;
+ var borders = { };
+ var handle = { };
+ var seehandles = false;
+ var hhs = options.handleOffset;
+
+ /* Insert draggable elements {{{*/
+
+ // Insert border divs for outline
+ if (options.drawBorders) {
+ borders = {
+ top: insertBorder('hline')
+ .css('top',$.browser.msie?px(-1):px(0)),
+ bottom: insertBorder('hline'),
+ left: insertBorder('vline'),
+ right: insertBorder('vline')
+ };
+ }
+
+ // Insert handles on edges
+ if (options.dragEdges) {
+ handle.t = insertDragbar('n');
+ handle.b = insertDragbar('s');
+ handle.r = insertDragbar('e');
+ handle.l = insertDragbar('w');
+ }
+
+ // Insert side handles
+ options.sideHandles &&
+ createHandles(['n','s','e','w']);
+
+ // Insert corner handles
+ options.cornerHandles &&
+ createHandles(['sw','nw','ne','se']);
+
+ /*}}}*/
+ // Private Methods
+ function insertBorder(type)/*{{{*/
+ {
+ var jq = $('<div />')
+ .css({position: 'absolute', opacity: options.borderOpacity })
+ .addClass(cssClass(type));
+ $img_holder.append(jq);
+ return jq;
+ };
+ /*}}}*/
+ function dragDiv(ord,zi)/*{{{*/
+ {
+ var jq = $('<div />')
+ .mousedown(createDragger(ord))
+ .css({
+ cursor: ord+'-resize',
+ position: 'absolute',
+ zIndex: zi
+ })
+ ;
+ $hdl_holder.append(jq);
+ return jq;
+ };
+ /*}}}*/
+ function insertHandle(ord)/*{{{*/
+ {
+ return dragDiv(ord,hdep++)
+ .css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity })
+ .addClass(cssClass('handle'));
+ };
+ /*}}}*/
+ function insertDragbar(ord)/*{{{*/
+ {
+ var s = options.handleSize,
+ o = hhs,
+ h = s, w = s,
+ t = o, l = o;
+
+ switch(ord)
+ {
+ case 'n': case 's': w = pct(100); break;
+ case 'e': case 'w': h = pct(100); break;
+ }
+
+ return dragDiv(ord,hdep++).width(w).height(h)
+ .css({ top: px(-t+1), left: px(-l+1)});
+ };
+ /*}}}*/
+ function createHandles(li)/*{{{*/
+ {
+ for(i in li) handle[li[i]] = insertHandle(li[i]);
+ };
+ /*}}}*/
+ function moveHandles(c)/*{{{*/
+ {
+ var midvert = Math.round((c.h / 2) - hhs),
+ midhoriz = Math.round((c.w / 2) - hhs),
+ north = west = -hhs+1,
+ east = c.w - hhs,
+ south = c.h - hhs,
+ x, y;
+
+ 'e' in handle &&
+ handle.e.css({ top: px(midvert), left: px(east) }) &&
+ handle.w.css({ top: px(midvert) }) &&
+ handle.s.css({ top: px(south), left: px(midhoriz) }) &&
+ handle.n.css({ left: px(midhoriz) });
+
+ 'ne' in handle &&
+ handle.ne.css({ left: px(east) }) &&
+ handle.se.css({ top: px(south), left: px(east) }) &&
+ handle.sw.css({ top: px(south) });
+
+ 'b' in handle &&
+ handle.b.css({ top: px(south) }) &&
+ handle.r.css({ left: px(east) });
+ };
+ /*}}}*/
+ function moveto(x,y)/*{{{*/
+ {
+ $img2.css({ top: px(-y), left: px(-x) });
+ $sel.css({ top: px(y), left: px(x) });
+ };
+ /*}}}*/
+ function resize(w,h)/*{{{*/
+ {
+ $sel.width(w).height(h);
+ };
+ /*}}}*/
+ function refresh()/*{{{*/
+ {
+ var c = Coords.getFixed();
+
+ Coords.setPressed([c.x,c.y]);
+ Coords.setCurrent([c.x2,c.y2]);
+
+ updateVisible();
+ };
+ /*}}}*/
+
+ // Internal Methods
+ function updateVisible()/*{{{*/
+ { if (awake) return update(); };
+ /*}}}*/
+ function update()/*{{{*/
+ {
+ var c = Coords.getFixed();
+
+ resize(c.w,c.h);
+ moveto(c.x,c.y);
+
+ options.drawBorders &&
+ borders['right'].css({ left: px(c.w-1) }) &&
+ borders['bottom'].css({ top: px(c.h-1) });
+
+ seehandles && moveHandles(c);
+ awake || show();
+
+ options.onChange(unscale(c));
+ };
+ /*}}}*/
+ function show()/*{{{*/
+ {
+ $sel.show();
+ $img.css('opacity',options.bgOpacity);
+ awake = true;
+ };
+ /*}}}*/
+ function release()/*{{{*/
+ {
+ disableHandles();
+ $sel.hide();
+ $img.css('opacity',1);
+ awake = false;
+ };
+ /*}}}*/
+ function showHandles()//{{{
+ {
+ if (seehandles)
+ {
+ moveHandles(Coords.getFixed());
+ $hdl_holder.show();
+ }
+ };
+ //}}}
+ function enableHandles()/*{{{*/
+ {
+ seehandles = true;
+ if (options.allowResize)
+ {
+ moveHandles(Coords.getFixed());
+ $hdl_holder.show();
+ return true;
+ }
+ };
+ /*}}}*/
+ function disableHandles()/*{{{*/
+ {
+ seehandles = false;
+ $hdl_holder.hide();
+ };
+ /*}}}*/
+ function animMode(v)/*{{{*/
+ {
+ (animating = v) ? disableHandles(): enableHandles();
+ };
+ /*}}}*/
+ function done()/*{{{*/
+ {
+ animMode(false);
+ refresh();
+ };
+ /*}}}*/
+
+ var $track = newTracker().mousedown(createDragger('move'))
+ .css({ cursor: 'move', position: 'absolute', zIndex: 360 })
+
+ $img_holder.append($track);
+ disableHandles();
+
+ return {
+ updateVisible: updateVisible,
+ update: update,
+ release: release,
+ refresh: refresh,
+ setCursor: function (cursor) { $track.css('cursor',cursor); },
+ enableHandles: enableHandles,
+ enableOnly: function() { seehandles = true; },
+ showHandles: showHandles,
+ disableHandles: disableHandles,
+ animMode: animMode,
+ done: done
+ };
+ }();
+ /*}}}*/
+ var Tracker = function()/*{{{*/
+ {
+ var onMove = function() { },
+ onDone = function() { },
+ trackDoc = options.trackDocument;
+
+ if (!trackDoc)
+ {
+ $trk
+ .mousemove(trackMove)
+ .mouseup(trackUp)
+ .mouseout(trackUp)
+ ;
+ }
+
+ function toFront()/*{{{*/
+ {
+ $trk.css({zIndex:450});
+ if (trackDoc)
+ {
+ $(document)
+ .mousemove(trackMove)
+ .mouseup(trackUp)
+ ;
+ }
+ }
+ /*}}}*/
+ function toBack()/*{{{*/
+ {
+ $trk.css({zIndex:290});
+ if (trackDoc)
+ {
+ $(document)
+ .unbind('mousemove',trackMove)
+ .unbind('mouseup',trackUp)
+ ;
+ }
+ }
+ /*}}}*/
+ function trackMove(e)/*{{{*/
+ {
+ onMove(mouseAbs(e));
+ };
+ /*}}}*/
+ function trackUp(e)/*{{{*/
+ {
+ e.preventDefault();
+ e.stopPropagation();
+
+ if (btndown)
+ {
+ btndown = false;
+
+ onDone(mouseAbs(e));
+ options.onSelect(unscale(Coords.getFixed()));
+ toBack();
+ onMove = function() { };
+ onDone = function() { };
+ }
+
+ return false;
+ };
+ /*}}}*/
+
+ function activateHandlers(move,done)/* {{{ */
+ {
+ btndown = true;
+ onMove = move;
+ onDone = done;
+ toFront();
+ return false;
+ };
+ /* }}} */
+
+ function setCursor(t) { $trk.css('cursor',t); };
+
+ $img.before($trk);
+ return {
+ activateHandlers: activateHandlers,
+ setCursor: setCursor
+ };
+ }();
+ /*}}}*/
+ var KeyManager = function()/*{{{*/
+ {
+ var $keymgr = $('<input type="radio" />')
+ .css({ position: 'absolute', left: '-30px' })
+ .keypress(parseKey)
+ .blur(onBlur),
+
+ $keywrap = $('<div />')
+ .css({
+ position: 'absolute',
+ overflow: 'hidden'
+ })
+ .append($keymgr)
+ ;
+
+ function watchKeys()/*{{{*/
+ {
+ if (options.keySupport)
+ {
+ $keymgr.show();
+ $keymgr.focus();
+ }
+ };
+ /*}}}*/
+ function onBlur(e)/*{{{*/
+ {
+ $keymgr.hide();
+ };
+ /*}}}*/
+ function doNudge(e,x,y)/*{{{*/
+ {
+ if (options.allowMove) {
+ Coords.moveOffset([x,y]);
+ Selection.updateVisible();
+ };
+ e.preventDefault();
+ e.stopPropagation();
+ };
+ /*}}}*/
+ function parseKey(e)/*{{{*/
+ {
+ if (e.ctrlKey) return true;
+ shift_down = e.shiftKey ? true : false;
+ var nudge = shift_down ? 10 : 1;
+ switch(e.keyCode)
+ {
+ case 37: doNudge(e,-nudge,0); break;
+ case 39: doNudge(e,nudge,0); break;
+ case 38: doNudge(e,0,-nudge); break;
+ case 40: doNudge(e,0,nudge); break;
+
+ case 27: Selection.release(); break;
+
+ case 9: return true;
+ }
+
+ return nothing(e);
+ };
+ /*}}}*/
+
+ if (options.keySupport) $keywrap.insertBefore($img);
+ return {
+ watchKeys: watchKeys
+ };
+ }();
+ /*}}}*/
+
+ // }}}
+ // Internal Methods {{{
+
+ function px(n) { return '' + parseInt(n) + 'px'; };
+ function pct(n) { return '' + parseInt(n) + '%'; };
+ function cssClass(cl) { return options.baseClass + '-' + cl; };
+ function getPos(obj)/*{{{*/
+ {
+ // Updated in v0.9.4 to use built-in dimensions plugin
+ var pos = $(obj).offset();
+ return [ pos.left, pos.top ];
+ };
+ /*}}}*/
+ function mouseAbs(e)/*{{{*/
+ {
+ return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ];
+ };
+ /*}}}*/
+ function myCursor(type)/*{{{*/
+ {
+ if (type != lastcurs)
+ {
+ Tracker.setCursor(type);
+ //Handles.xsetCursor(type);
+ lastcurs = type;
+ }
+ };
+ /*}}}*/
+ function startDragMode(mode,pos)/*{{{*/
+ {
+ docOffset = getPos($img);
+ Tracker.setCursor(mode=='move'?mode:mode+'-resize');
+
+ if (mode == 'move')
+ return Tracker.activateHandlers(createMover(pos), doneSelect);
+
+ var fc = Coords.getFixed();
+ var opp = oppLockCorner(mode);
+ var opc = Coords.getCorner(oppLockCorner(opp));
+
+ Coords.setPressed(Coords.getCorner(opp));
+ Coords.setCurrent(opc);
+
+ Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect);
+ };
+ /*}}}*/
+ function dragmodeHandler(mode,f)/*{{{*/
+ {
+ return function(pos) {
+ if (!options.aspectRatio) switch(mode)
+ {
+ case 'e': pos[1] = f.y2; break;
+ case 'w': pos[1] = f.y2; break;
+ case 'n': pos[0] = f.x2; break;
+ case 's': pos[0] = f.x2; break;
+ }
+ else switch(mode)
+ {
+ case 'e': pos[1] = f.y+1; break;
+ case 'w': pos[1] = f.y+1; break;
+ case 'n': pos[0] = f.x+1; break;
+ case 's': pos[0] = f.x+1; break;
+ }
+ Coords.setCurrent(pos);
+ Selection.update();
+ };
+ };
+ /*}}}*/
+ function createMover(pos)/*{{{*/
+ {
+ var lloc = pos;
+ KeyManager.watchKeys();
+
+ return function(pos)
+ {
+ Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
+ lloc = pos;
+
+ Selection.update();
+ };
+ };
+ /*}}}*/
+ function oppLockCorner(ord)/*{{{*/
+ {
+ switch(ord)
+ {
+ case 'n': return 'sw';
+ case 's': return 'nw';
+ case 'e': return 'nw';
+ case 'w': return 'ne';
+ case 'ne': return 'sw';
+ case 'nw': return 'se';
+ case 'se': return 'nw';
+ case 'sw': return 'ne';
+ };
+ };
+ /*}}}*/
+ function createDragger(ord)/*{{{*/
+ {
+ return function(e) {
+ if (options.disabled) return false;
+ if ((ord == 'move') && !options.allowMove) return false;
+ btndown = true;
+ startDragMode(ord,mouseAbs(e));
+ e.stopPropagation();
+ e.preventDefault();
+ return false;
+ };
+ };
+ /*}}}*/
+ function presize($obj,w,h)/*{{{*/
+ {
+ var nw = $obj.width(), nh = $obj.height();
+ if ((nw > w) && w > 0)
+ {
+ nw = w;
+ nh = (w/$obj.width()) * $obj.height();
+ }
+ if ((nh > h) && h > 0)
+ {
+ nh = h;
+ nw = (h/$obj.height()) * $obj.width();
+ }
+ xscale = $obj.width() / nw;
+ yscale = $obj.height() / nh;
+ $obj.width(nw).height(nh);
+ };
+ /*}}}*/
+ function unscale(c)/*{{{*/
+ {
+ return {
+ x: parseInt(c.x * xscale), y: parseInt(c.y * yscale),
+ x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale),
+ w: parseInt(c.w * xscale), h: parseInt(c.h * yscale)
+ };
+ };
+ /*}}}*/
+ function doneSelect(pos)/*{{{*/
+ {
+ var c = Coords.getFixed();
+ if (c.w > options.minSelect[0] && c.h > options.minSelect[1])
+ {
+ Selection.enableHandles();
+ Selection.done();
+ }
+ else
+ {
+ Selection.release();
+ }
+ Tracker.setCursor( options.allowSelect?'crosshair':'default' );
+ };
+ /*}}}*/
+ function newSelection(e)/*{{{*/
+ {
+ if (options.disabled) return false;
+ if (!options.allowSelect) return false;
+ btndown = true;
+ docOffset = getPos($img);
+ Selection.disableHandles();
+ myCursor('crosshair');
+ var pos = mouseAbs(e);
+ Coords.setPressed(pos);
+ Tracker.activateHandlers(selectDrag,doneSelect);
+ KeyManager.watchKeys();
+ Selection.update();
+
+ e.stopPropagation();
+ e.preventDefault();
+ return false;
+ };
+ /*}}}*/
+ function selectDrag(pos)/*{{{*/
+ {
+ Coords.setCurrent(pos);
+ Selection.update();
+ };
+ /*}}}*/
+ function newTracker()
+ {
+ var trk = $('<div></div>').addClass(cssClass('tracker'));
+ $.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' });
+ return trk;
+ };
+
+ // }}}
+ // API methods {{{
+
+ function animateTo(a)/*{{{*/
+ {
+ var x1 = a[0] / xscale,
+ y1 = a[1] / yscale,
+ x2 = a[2] / xscale,
+ y2 = a[3] / yscale;
+
+ if (animating) return;
+
+ var animto = Coords.flipCoords(x1,y1,x2,y2);
+ var c = Coords.getFixed();
+ var animat = initcr = [ c.x, c.y, c.x2, c.y2 ];
+ var interv = options.animationDelay;
+
+ var x = animat[0];
+ var y = animat[1];
+ var x2 = animat[2];
+ var y2 = animat[3];
+ var ix1 = animto[0] - initcr[0];
+ var iy1 = animto[1] - initcr[1];
+ var ix2 = animto[2] - initcr[2];
+ var iy2 = animto[3] - initcr[3];
+ var pcent = 0;
+ var velocity = options.swingSpeed;
+
+ Selection.animMode(true);
+
+ var animator = function()
+ {
+ return function()
+ {
+ pcent += (100 - pcent) / velocity;
+
+ animat[0] = x + ((pcent / 100) * ix1);
+ animat[1] = y + ((pcent / 100) * iy1);
+ animat[2] = x2 + ((pcent / 100) * ix2);
+ animat[3] = y2 + ((pcent / 100) * iy2);
+
+ if (pcent < 100) animateStart();
+ else Selection.done();
+
+ if (pcent >= 99.8) pcent = 100;
+
+ setSelectRaw(animat);
+ };
+ }();
+
+ function animateStart()
+ { window.setTimeout(animator,interv); };
+
+ animateStart();
+ };
+ /*}}}*/
+ function setSelect(rect)//{{{
+ {
+ setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]);
+ };
+ //}}}
+ function setSelectRaw(l) /*{{{*/
+ {
+ Coords.setPressed([l[0],l[1]]);
+ Coords.setCurrent([l[2],l[3]]);
+ Selection.update();
+ };
+ /*}}}*/
+ function setOptions(opt)/*{{{*/
+ {
+ if (typeof(opt) != 'object') opt = { };
+ options = $.extend(options,opt);
+
+ if (typeof(options.onChange)!=='function')
+ options.onChange = function() { };
+
+ if (typeof(options.onSelect)!=='function')
+ options.onSelect = function() { };
+
+ };
+ /*}}}*/
+ function tellSelect()/*{{{*/
+ {
+ return unscale(Coords.getFixed());
+ };
+ /*}}}*/
+ function tellScaled()/*{{{*/
+ {
+ return Coords.getFixed();
+ };
+ /*}}}*/
+ function setOptionsNew(opt)/*{{{*/
+ {
+ setOptions(opt);
+ interfaceUpdate();
+ };
+ /*}}}*/
+ function disableCrop()//{{{
+ {
+ options.disabled = true;
+ Selection.disableHandles();
+ Selection.setCursor('default');
+ Tracker.setCursor('default');
+ };
+ //}}}
+ function enableCrop()//{{{
+ {
+ options.disabled = false;
+ interfaceUpdate();
+ };
+ //}}}
+ function cancelCrop()//{{{
+ {
+ Selection.done();
+ Tracker.activateHandlers(null,null);
+ };
+ //}}}
+ function destroy()//{{{
+ {
+ $div.remove();
+ $origimg.show();
+ };
+ //}}}
+
+ function interfaceUpdate(alt)//{{{
+ // This method tweaks the interface based on options object.
+ // Called when options are changed and at end of initialization.
+ {
+ options.allowResize ?
+ alt?Selection.enableOnly():Selection.enableHandles():
+ Selection.disableHandles();
+
+ Tracker.setCursor( options.allowSelect? 'crosshair': 'default' );
+ Selection.setCursor( options.allowMove? 'move': 'default' );
+
+ $div.css('backgroundColor',options.bgColor);
+
+ if ('setSelect' in options) {
+ setSelect(opt.setSelect);
+ Selection.done();
+ delete(options.setSelect);
+ }
+
+ if ('trueSize' in options) {
+ xscale = options.trueSize[0] / boundx;
+ yscale = options.trueSize[1] / boundy;
+ }
+
+ xlimit = options.maxSize[0] || 0;
+ ylimit = options.maxSize[1] || 0;
+ xmin = options.minSize[0] || 0;
+ ymin = options.minSize[1] || 0;
+
+ if ('outerImage' in options)
+ {
+ $img.attr('src',options.outerImage);
+ delete(options.outerImage);
+ }
+
+ Selection.refresh();
+ };
+ //}}}
+
+ // }}}
+
+ $hdl_holder.hide();
+ interfaceUpdate(true);
+
+ var api = {
+ animateTo: animateTo,
+ setSelect: setSelect,
+ setOptions: setOptionsNew,
+ tellSelect: tellSelect,
+ tellScaled: tellScaled,
+
+ disable: disableCrop,
+ enable: enableCrop,
+ cancel: cancelCrop,
+
+ focus: KeyManager.watchKeys,
+
+ getBounds: function() { return [ boundx * xscale, boundy * yscale ]; },
+ getWidgetSize: function() { return [ boundx, boundy ]; },
+
+ release: Selection.release,
+ destroy: destroy
+
+ };
+
+ $origimg.data('Jcrop',api);
+ return api;
+};
+
+$.fn.Jcrop = function(options)/*{{{*/
+{
+ function attachWhenDone(from)/*{{{*/
+ {
+ var loadsrc = options.useImg || from.src;
+ var img = new Image();
+ img.onload = function() { $.Jcrop(from,options); };
+ img.src = loadsrc;
+ };
+ /*}}}*/
+ if (typeof(options) !== 'object') options = { };
+
+ // Iterate over each object, attach Jcrop
+ this.each(function()
+ {
+ // If we've already attached to this object
+ if ($(this).data('Jcrop'))
+ {
+ // The API can be requested this way (undocumented)
+ if (options == 'api') return $(this).data('Jcrop');
+ // Otherwise, we just reset the options...
+ else $(this).data('Jcrop').setOptions(options);
+ }
+ // If we haven't been attached, preload and attach
+ else attachWhenDone(this);
+ });
+
+ // Return "this" so we're chainable a la jQuery plugin-style!
+ return this;
+};
+/*}}}*/
+
+})(jQuery);
--- /dev/null
+/*\r
+ *\r
+ * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)\r
+ * Licensed under the MIT License:\r
+ * http://www.opensource.org/licenses/mit-license.php\r
+ * \r
+ * Version 1.0
+ * Demo: http://www.texotela.co.uk/code/jquery/numeric/
+ *
+ * $LastChangedDate: 2007-05-29 11:31:36 +0100 (Tue, 29 May 2007) $
+ * $Rev: 2005 $\r
+ */\r
+ \r
+/*\r
+ * Allows only valid characters to be entered into input boxes.\r
+ * Note: does not validate that the final text is a valid number\r
+ * (that could be done by another script, or server-side)\r
+ *\r
+ * @name numeric\r
+ * @param decimal Decimal separator (e.g. '.' or ',' - default is '.')\r
+ * @param callback A function that runs if the number is not valid (fires onblur)\r
+ * @author Sam Collett (http://www.texotela.co.uk)\r
+ * @example $(".numeric").numeric();\r
+ * @example $(".numeric").numeric(",");\r
+ * @example $(".numeric").numeric(null, callback);\r
+ *\r
+ */\r
+jQuery.fn.numeric = function(decimal, callback)\r
+{\r
+ decimal = decimal || ".";\r
+ callback = typeof callback == "function" ? callback : function(){};\r
+ this.keypress(\r
+ function(e)\r
+ {\r
+ var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;\r
+ // allow enter/return key (only when in an input box)\r
+ if(key == 13 && this.nodeName.toLowerCase() == "input")\r
+ {\r
+ return true;\r
+ }\r
+ else if(key == 13)\r
+ {\r
+ return false;\r
+ }\r
+ var allow = false;\r
+ // allow Ctrl+A\r
+ if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;\r
+ // allow Ctrl+X (cut)\r
+ if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;\r
+ // allow Ctrl+C (copy)\r
+ if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;\r
+ // allow Ctrl+Z (undo)\r
+ if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;\r
+ // allow or deny Ctrl+V (paste), Shift+Ins\r
+ if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */\r
+ || (e.shiftKey && key == 45)) return true;\r
+ // if a number was not pressed\r
+ if(key < 48 || key > 57)\r
+ {\r
+ /* '-' only allowed at start */\r
+ if(key == 45 && this.value.length == 0) return true;\r
+ /* only one decimal separator allowed */\r
+ if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)\r
+ {\r
+ allow = false;\r
+ }\r
+ // check for other keys that have special purposes\r
+ if(\r
+ key != 8 /* backspace */ &&\r
+ key != 9 /* tab */ &&\r
+ key != 13 /* enter */ &&\r
+ key != 35 /* end */ &&\r
+ key != 36 /* home */ &&\r
+ key != 37 /* left */ &&\r
+ key != 39 /* right */ &&\r
+ key != 46 /* del */\r
+ )\r
+ {\r
+ allow = false;\r
+ }\r
+ else\r
+ {\r
+ // for detecting special keys (listed above)\r
+ // IE does not support 'charCode' and ignores them in keypress anyway\r
+ if(typeof e.charCode != "undefined")\r
+ {\r
+ // special keys have 'keyCode' and 'which' the same (e.g. backspace)\r
+ if(e.keyCode == e.which && e.which != 0)\r
+ {\r
+ allow = true;\r
+ }\r
+ // or keyCode != 0 and 'charCode'/'which' = 0\r
+ else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)\r
+ {\r
+ allow = true;\r
+ }\r
+ }\r
+ }\r
+ // if key pressed is the decimal and it is not already in the field\r
+ if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1)\r
+ {\r
+ allow = true;\r
+ }\r
+ }\r
+ else\r
+ {\r
+ allow = true;\r
+ }\r
+ return allow;\r
+ }\r
+ )\r
+ .blur(\r
+ function()\r
+ {\r
+ var val = jQuery(this).val();\r
+ if(val != "")\r
+ {\r
+ var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");\r
+ if(!re.exec(val))\r
+ {\r
+ callback.apply(this);\r
+ }\r
+ }\r
+ }\r
+ );\r
+ return this;\r
+}
\ No newline at end of file
--- /dev/null
+var objCrop = null;\r
+\r
+function ajax_post()\r
+{\r
+ if ($('#loading').css('display') == 'none') {\r
+ $('#width').attr('disabled','disabled');\r
+ $('#height').attr('disabled','disabled');\r
+ $('#keepproportions').attr('disabled','disabled');\r
+ $('#btnRotateLeft').attr('disabled','disabled');\r
+ $('#btnRotateRight').attr('disabled','disabled');\r
+ $('#croptop').attr('disabled','disabled');\r
+ $('#cropbottom').attr('disabled','disabled');\r
+ $('#cropleft').attr('disabled','disabled');\r
+ $('#cropright').attr('disabled','disabled');\r
+ $('#grayscale').attr('disabled','disabled');\r
+ $('#btnupdate').attr('disabled','disabled');\r
+ $('#btnsave').attr('disabled','disabled');\r
+ $('#btnundo').attr('disabled','disabled');\r
+ $('#brightness_slider_track').slider('disable');\r
+ $('#contrast_slider_track').slider('disable');\r
+ \r
+ $('#loading').css('display','block');\r
+ $('#loading_bar').width(0);\r
+ $('#loading_bar').animate({width: document.getElementById('loading').offsetWidth-30}, document.getElementById('loading').offsetWidth*10);\r
+ \r
+ $.ajax({\r
+ timeout: AjaxPostTimeoutMs,\r
+ type: "POST",\r
+ url: FormAction,\r
+ data: "grayscaleval="+$('#grayscaleval').val()+\r
+ "&keepproportionsval="+$('#keepproportionsval').val()+\r
+ "&image_name="+$('#image_name').val()+\r
+ "&width="+$('#width').val()+\r
+ "&widthoriginal="+$('#widthoriginal').val()+\r
+ "&height="+$('#height').val()+\r
+ "&heightoriginal="+$('#heightoriginal').val()+\r
+ "&rotate="+$('#rotate').val()+\r
+ "&croptop="+$('#croptop').val()+\r
+ "&cropleft="+$('#cropleft').val()+\r
+ "&cropright="+$('#cropright').val()+\r
+ "&cropbottom="+$('#cropbottom').val()+\r
+ "&contrast="+$('#contrast').val()+\r
+ "&brightness="+$('#brightness').val()+\r
+ "&actiontype="+$('#actiontype').val()+\r
+ "&panel="+$('#panel').val()+\r
+ "&language="+$('#language').val()+\r
+ "&actions="+$('#actions').val()+\r
+ "&widthlast="+$('#widthlast').val()+\r
+ "&heightlast="+$('#heightlast').val()+\r
+ "&userid="+$('#userid').val()+\r
+ "&contrastlast="+$('#contrastlast').val()+\r
+ "&brightnesslast="+$('#brightnesslast').val()+\r
+ "&widthlastbeforeresize="+$('#widthlastbeforeresize').val()+\r
+ "&heightlastbeforeresize="+$('#heightlastbeforeresize').val()+\r
+ "&cropkeepproportionsval="+$('#cropkeepproportionsval').val()+\r
+ "&cropkeepproportionsratio="+$('#cropkeepproportionsratio').val()+\r
+ "&isajaxpost=true",\r
+ success: function(data)\r
+ { \r
+ $('#phpImageEditor').html(data);\r
+ activate_form();\r
+ phpimageeditor_crop_activator(parseInt($('#panel').val()));\r
+ phpimageeditor_init();\r
+ $('#loading_bar').stop();\r
+ $('#loading').css('display','none');\r
+ },\r
+ error: function(XMLHttpRequest, textStatus, errorThrown)\r
+ {\r
+ activate_form();\r
+ $('#ulJsErrors').html("");\r
+ adderror(TextAnUnexpectedError);\r
+ $('#divJsErrors').css('display','block');\r
+ $('#ulJsErrors').css('display','block');\r
+ phpimageeditor_crop_activator(parseInt($('#panel').val()));\r
+ $('#loading_bar').stop();\r
+ $('#loading').css('display','none');\r
+ }\r
+ });\r
+ \r
+ }\r
+}\r
+\r
+function isinteger(s)\r
+{\r
+ var i;\r
+\r
+ if (isempty(s))\r
+ if (isinteger.arguments.length == 1) return 0;\r
+ else return (isinteger.arguments[1] == true);\r
+\r
+ for (i = 0; i < s.length; i++)\r
+ {\r
+ var c = s.charAt(i);\r
+\r
+ if (!isdigit(c)) return false;\r
+ }\r
+\r
+ return true;\r
+}\r
+\r
+function focus_on_enter(element, event)\r
+{\r
+ if(event.keyCode == 13)\r
+ element.focus();\r
+}\r
+\r
+function reload_mouse_crop()\r
+{\r
+ objCrop.destroy();\r
+ objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("#cropkeepproportionsratio").val() : 0}); \r
+ $(".jcrop-holder").css("display", "none");\r
+ $("#image").css("display", "block"); \r
+}\r
+\r
+function update_width(InputWidth, EditForm)\r
+{\r
+ if (isinteger(InputWidth.val()))\r
+ {\r
+ var Width = parseInt($('#width').val());\r
+ var Height = parseInt($('#height').val());\r
+ \r
+ $('#image').css('width',Width+'px');\r
+ \r
+ if ($("input#keepproportions").attr('checked'))\r
+ {\r
+ $('#image').css('height', get_proportional_height(Width, EditForm) + "px");\r
+ $('#height').val(get_proportional_height(Width, EditForm));\r
+ }\r
+ \r
+ update_mouse_resizer();\r
+ reload_mouse_crop();\r
+ }\r
+}\r
+\r
+function update_mouse_resizer()\r
+{\r
+ $('#imageResizerKeepProportions').css('width',$('#width').val()+'px'); \r
+ $('#imageResizerKeepProportions').css('height',$('#height').val()+'px');\r
+ $('#imageResizerNoProportions').css('width',$('#width').val()+'px'); \r
+ $('#imageResizerNoProportions').css('height',$('#height').val()+'px');\r
+}\r
+\r
+function update_height(InputHeight, EditForm)\r
+{\r
+ if (isinteger(InputHeight.val()))\r
+ {\r
+ var Height = parseInt($('#height').val());\r
+ var Width = parseInt($('#width').val());\r
+ \r
+ $('#image').css('height',$('#height').val()+'px');\r
+ \r
+ if ($("input#keepproportions").attr('checked'))\r
+ {\r
+ $('#image').css('width',get_proportional_width(Height, EditForm)+'px');\r
+ $('#width').val(get_proportional_width(Height, EditForm));\r
+ }\r
+ \r
+ update_mouse_resizer();\r
+ reload_mouse_crop();\r
+ }\r
+}\r
+\r
+function isempty(s)\r
+{\r
+ return ((s == null) || (s.length == 0))\r
+}\r
+\r
+function isdigit (c)\r
+{\r
+ return ((c >= "0") && (c <= "9"))\r
+}\r
+\r
+function isintegerinrange(s, a, b)\r
+{ \r
+ if (isempty(s))\r
+ if (isintegerinrange.arguments.length == 1) return false;\r
+ else return (isintegerinrange.arguments[1] == true);\r
+\r
+ // Catch non-integer strings to avoid creating a NaN below,\r
+ // which isn't available on JavaScript 1.0 for Windows.\r
+ if (!isinteger(s, false)) return false;\r
+\r
+ // Now, explicitly change the type to integer via parseInt\r
+ // so that the comparison code below will work both on\r
+ // JavaScript 1.2 (which typechecks in equality comparisons)\r
+ // and JavaScript 1.1 and before (which doesn't).\r
+ var num = parseInt (s);\r
+ return ((num >= a) && (num <= b));\r
+}\r
+\r
+function validate_form()\r
+{\r
+ var sendForm = true;\r
+ \r
+ var width = $('#width').val();\r
+ var height = $('#height').val();\r
+ var cropleft = $('#cropleft').val();\r
+ var cropright = $('#cropright').val();\r
+ var croptop = $('#croptop').val();\r
+ var cropbottom = $('#cropbottom').val();\r
+ var imageName = $('#image_name').val();\r
+ \r
+ $('#divJsErrors').css('display','none');\r
+ $('#ulJsErrors').css('display','none');\r
+ \r
+ $('#ulJsErrors').html("");\r
+\r
+ if (imageName == "") {\r
+ adderror("\"Image Name\" is Required!" );\r
+ sendForm = false;\r
+ }\r
+\r
+ if (width == "")\r
+ {\r
+ adderror("\"" + TextWidth + "\" " + TextIsRequired)\r
+ sendForm = false;\r
+ }\r
+ \r
+ if (height == "")\r
+ {\r
+ adderror("\"" + TextHeight + "\" " + TextIsRequired)\r
+ sendForm = false;\r
+ }\r
+ \r
+ if (!sendForm)\r
+ {\r
+ $('#divJsErrors').css('display','block');\r
+ $('#ulJsErrors').css('display','block');\r
+\r
+ return sendForm;\r
+ }\r
+ \r
+ if (!isinteger(width))\r
+ {\r
+ adderror("\"" + TextWidth + "\" " + TextMustBeNumeric)\r
+ sendForm = false;\r
+ }\r
+ \r
+ if (!isinteger(height))\r
+ {\r
+ adderror("\"" + TextHeight + "\" " + TextMustBeNumeric)\r
+ sendForm = false;\r
+ }\r
+ \r
+ if (!sendForm)\r
+ {\r
+ $('#divJsErrors').css('display','block');\r
+ $('#ulJsErrors').css('display','block');\r
+ return sendForm;\r
+ }\r
+\r
+ width = parseInt(width);\r
+ height = parseInt(height);\r
+\r
+ if (!isintegerinrange(width, 1, ImageMaxWidth))\r
+ {\r
+ adderror("\"" + TextWidth + "\" " + TextNotInRange + ": 1 - " + ImageMaxWidth)\r
+ sendForm = false;\r
+ }\r
+ \r
+ if (!isintegerinrange(height, 1, ImageMaxHeight))\r
+ {\r
+ adderror("\"" + TextHeight + "\" " + TextNotInRange + ": 1 - " + ImageMaxHeight)\r
+ sendForm = false;\r
+ }\r
+ \r
+ if (!sendForm)\r
+ {\r
+ $('#divJsErrors').css('display','block');\r
+ $('#ulJsErrors').css('display','block');\r
+ }\r
+\r
+ return sendForm;\r
+}\r
+\r
+function adderror(ErrorText)\r
+{\r
+ $('#ulJsErrors').html($('#ulJsErrors').html()+'<li>'+ErrorText+'</li>');\r
+}\r
+\r
+function get_proportional_width(Height, EditForm)\r
+{\r
+ var HeightOriginal = parseInt($("#heightlastbeforeresize").val());\r
+ var WidthOriginal = parseInt($("#widthlastbeforeresize").val());\r
+ \r
+ return Math.round((WidthOriginal/HeightOriginal)*Height);\r
+}\r
+\r
+function get_proportional_height(Width, EditForm)\r
+{\r
+ var HeightOriginal = parseInt($("#heightlastbeforeresize").val());\r
+ var WidthOriginal = parseInt($("#widthlastbeforeresize").val());\r
+ \r
+ return Math.round((HeightOriginal/WidthOriginal)*Width);\r
+}\r
+\r
+function remove_px(Value)\r
+{\r
+ return Value.replace("px","");\r
+}\r
+\r
+function activate_form()\r
+{\r
+ $('#width').removeAttr('disabled');\r
+ $('#height').removeAttr('disabled');\r
+ $('#keepproportions').removeAttr('disabled');\r
+ $('#btnRotateLeft').removeAttr('disabled');\r
+ $('#btnRotateRight').removeAttr('disabled');\r
+ $('#croptop').removeAttr('disabled');\r
+ $('#cropbottom').removeAttr('disabled');\r
+ $('#cropleft').removeAttr('disabled');\r
+ $('#cropright').removeAttr('disabled');\r
+ $('#grayscale').removeAttr('disabled');\r
+ $('#btnupdate').removeAttr('disabled');\r
+ $('#btnsave').removeAttr('disabled');\r
+ $('#btnundo').removeAttr('disabled');\r
+ $('#brightness_slider_track').slider('enable');\r
+ $('#contrast_slider_track').slider('enable');\r
+ \r
+ if ($('#actions').val() == '')\r
+ {\r
+ $('#btnundo').attr('disabled','disabled');\r
+ $('#btnsave').attr('disabled','disabled');\r
+ }\r
+ else\r
+ {\r
+ $('#btnundo').removeAttr('disabled');\r
+ $('#btnsave').removeAttr('disabled');\r
+ } \r
+}\r
+\r
+\r
+function set_crop_values(c)\r
+{\r
+ if (isinteger($("#height").val()) && isinteger($("#width").val()))\r
+ {\r
+ $("#croptop").val(c.y);\r
+ $("#cropbottom").val(parseInt($("#height").val()) - (c.y + c.h));\r
+ $("#cropleft").val(c.x);\r
+ $("#cropright").val(parseInt($("#width").val()) - (c.x + c.w));\r
+ $("#cropwidth").html(c.w);\r
+ $("#cropheight").html(c.h);\r
+ }\r
+}\r
+\r
+function phpimageeditor_resize_activator(selectedIndex)\r
+{\r
+ if (selectedIndex == MenuResize)\r
+ {\r
+ if ($('#keepproportionsval').val() == "1")\r
+ {\r
+ $("#imageResizerKeepProportions").css("display", "block");\r
+ $("#imageResizerNoProportions").css("display", "none");\r
+ }\r
+ else\r
+ {\r
+ $("#imageResizerKeepProportions").css("display", "none");\r
+ $("#imageResizerNoProportions").css("display", "block");\r
+ }\r
+ }\r
+ else\r
+ {\r
+ $("#imageResizerKeepProportions").css("display", "none");\r
+ $("#imageResizerNoProportions").css("display", "none");\r
+ }\r
+}\r
+\r
+function phpimageeditor_panelfade(selectedIndex)\r
+{\r
+ for (i = 0; i < 4; i++)\r
+ {\r
+ if ($('#panel_'+i) != null)\r
+ {\r
+ $("#panel_"+i).css('opacity','0.0');\r
+ \r
+ if (i == selectedIndex)\r
+ {\r
+ $("#menuitem_"+i).removeClass("not-selected"); \r
+ $("#menuitem_"+i).addClass("selected");\r
+ $("#panel_"+i).css('display','block');\r
+ $("#panel_"+i).fadeTo("normal", 1.0);\r
+ }\r
+ else\r
+ {\r
+ $("#menuitem_"+i).removeClass("selected");\r
+ $("#menuitem_"+i).addClass("not-selected"); \r
+ $("#panel_"+i).css('display','none');\r
+ }\r
+ }\r
+ }\r
+ \r
+ if (selectedIndex != MenuCrop)\r
+ {\r
+ $("#cropleft").val("0");\r
+ $("#cropright").val("0");\r
+ $("#croptop").val("0");\r
+ $("#cropbottom").val("0");\r
+ $("#cropwidth").html("0");\r
+ $("#cropheight").html("0");\r
+ }\r
+ \r
+ phpimageeditor_resize_activator(selectedIndex);\r
+ phpimageeditor_crop_activator(selectedIndex);\r
+ \r
+ $("#panel").val(selectedIndex);\r
+}\r
+\r
+function phpimageeditor_crop_activator(selectedIndex)\r
+{\r
+ if (objCrop != null)\r
+ { \r
+ if (selectedIndex != MenuCrop)\r
+ {\r
+ objCrop.release();\r
+ objCrop.disable();\r
+ $(".jcrop-holder").css("display", "none");\r
+ $("#image").css("display", "block");\r
+ }\r
+ else\r
+ {\r
+ objCrop.release();\r
+ objCrop.enable();\r
+ $(".jcrop-holder").css("display", "block");\r
+ $("#image").css("display", "block");\r
+ }\r
+ }\r
+}\r
+\r
+function phpimageeditor_init()\r
+{\r
+ objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("input#cropkeepproportionsratio").val() : 0});\r
+\r
+ $("#imageResizerKeepProportions").resizable(\r
+ {\r
+ aspectRatio: parseFloat($("input#widthlastbeforeresize").val()) / parseFloat($("input#heightlastbeforeresize").val()),\r
+ stop: function(event,ui)\r
+ { \r
+ var resize_width = parseInt(remove_px($("#imageResizerKeepProportions").css("width")));\r
+ var resize_height = parseInt(remove_px($("#imageResizerKeepProportions").css("height")));\r
+ \r
+ $("#image").css("width", resize_width+"px");\r
+ $("#image").css("height", resize_height+"px");\r
+ $("#width").val(resize_width);\r
+ $("#height").val(resize_height);\r
+\r
+ update_mouse_resizer();\r
+\r
+ $("#imageResizerKeepProportions").css("opacity", "0.0");\r
+ \r
+ reload_mouse_crop();\r
+ },\r
+ start: function(event,ui)\r
+ { \r
+ $("#imageResizerKeepProportions").css("opacity", "0.5");\r
+ }\r
+ });\r
+ \r
+ $("#imageResizerNoProportions").resizable(\r
+ {\r
+ aspectRatio: false,\r
+ stop: function(event,ui)\r
+ { \r
+ var resize_width = parseInt(remove_px($("#imageResizerNoProportions").css("width")));\r
+ var resize_height = parseInt(remove_px($("#imageResizerNoProportions").css("height")));\r
+ \r
+ $("#image").css("width", resize_width+"px");\r
+ $("#image").css("height", resize_height+"px");\r
+ $("#width").val(resize_width);\r
+ $("#height").val(resize_height);\r
+ \r
+ update_mouse_resizer();\r
+\r
+ $("#widthlastbeforeresize").val(resize_width);\r
+ $("#heightlastbeforeresize").val(resize_height);\r
+ $("#imageResizerKeepProportions").resizable('option','aspectRatio',parseFloat($('#widthlastbeforeresize').val())/parseFloat($('#heightlastbeforeresize').val()));\r
+\r
+ $("#imageResizerNoProportions").css("opacity", "0.0");\r
+\r
+ reload_mouse_crop();\r
+ },\r
+ start: function(event,ui)\r
+ { \r
+ $("#imageResizerNoProportions").css("opacity", "0.5");\r
+ }\r
+ });\r
+ \r
+ $("#contrast_slider_track").slider({value: parseInt($("#contrast").val()) + ContrastMax, min: 1, max: ((ContrastMax*2)+1), step: 1,\r
+ stop: function(event,ui)\r
+ { \r
+ if (validate_form())\r
+ ajax_post();\r
+ },\r
+ slide: function(event, ui) \r
+ {\r
+ $("#contrast").val(parseInt(ui.value)-((ContrastMax)+1));\r
+ }\r
+ });\r
+ \r
+ $("#brightness_slider_track").slider({value: (parseInt($("input#brightness").val())+BrightnessMax),min: 1,max: ((BrightnessMax*2)+1),step: 1,\r
+ stop: function(event,ui)\r
+ { \r
+ if (validate_form())\r
+ ajax_post();\r
+ },\r
+ slide: function(event, ui) \r
+ {\r
+ $("#brightness").val(parseInt(ui.value)-(BrightnessMax+1));\r
+ }\r
+ });\r
+ \r
+ $("#grayscale").click(function()\r
+ {\r
+ if (validate_form())\r
+ {\r
+ $("#grayscale").attr('checked') ? $('#grayscaleval').val('1') : $('#grayscaleval').val('0');\r
+ ajax_post();\r
+ }\r
+ });\r
+ \r
+ $("#btnupdate").click(function()\r
+ {\r
+ if (validate_form())\r
+ {\r
+ $("#actiontype").val(ActionUpdate); \r
+ ajax_post();\r
+ }\r
+ });\r
+ \r
+ $("#btnundo").click(function()\r
+ {\r
+ if (validate_form())\r
+ {\r
+ $("#actiontype").val(ActionUndo); \r
+ ajax_post();\r
+ }\r
+ });\r
+\r
+ $("#btnsave").click(function()\r
+ {\r
+ if (validate_form())\r
+ {\r
+ $("#actiontype").val(ActionSaveAndClose); \r
+ ajax_post();\r
+ }\r
+ });\r
+\r
+ $("#btnRotateLeft").click(function()\r
+ {\r
+ if (validate_form())\r
+ {\r
+ $("#rotate").val(ActionRotateLeft);\r
+ ajax_post();\r
+ }\r
+ });\r
+\r
+ $("#btnRotateRight").click(function()\r
+ {\r
+ if (validate_form())\r
+ {\r
+ $("#rotate").val(ActionRotateRight);\r
+ ajax_post();\r
+ }\r
+ });\r
+ \r
+ $("form#" + FormId).submit(function()\r
+ {\r
+ if (validate_form())\r
+ {\r
+ $("#actiontype").val(ActionSaveAndClose);\r
+ return true;\r
+ }\r
+ return false;\r
+ });\r
+ \r
+ $("#width").keydown(function(event)\r
+ {\r
+ focus_on_enter($("input#btnupdate"), event);\r
+ });\r
+ \r
+ $("#width").keyup(function()\r
+ {\r
+ update_width($(this),$("form#" + FormId));\r
+ });\r
+ \r
+ $("#height").keydown(function(event)\r
+ {\r
+ focus_on_enter($("input#btnupdate"), event);\r
+ });\r
+ \r
+ $("#height").keyup(function()\r
+ {\r
+ update_height($(this),$("form#" + FormId));\r
+ });\r
+ \r
+ $("#keepproportions").click(function()\r
+ {\r
+ if ($(this).attr('checked'))\r
+ {\r
+ $('#keepproportionsval').val('1');\r
+ $('#imageResizerKeepProportions').css('display','block');\r
+ $('#imageResizerNoProportions').css('display','none'); \r
+ }\r
+ else\r
+ {\r
+ $('#keepproportionsval').val('0'); \r
+ $('#imageResizerKeepProportions').css('display','none');\r
+ $('#imageResizerNoProportions').css('display','block'); \r
+ }\r
+ });\r
+ \r
+\r
+ $("#cropkeepproportions").click(function()\r
+ {\r
+ if ($(this).attr('checked'))\r
+ {\r
+ $('#cropkeepproportionsval').val('1');\r
+ }\r
+ else\r
+ {\r
+ $('#cropkeepproportionsval').val('0'); \r
+ }\r
+ });\r
+ \r
+ $("#menuitem_" + MenuResize).click(function()\r
+ {\r
+ if ($('#panel').val() != MenuResize)\r
+ {\r
+ phpimageeditor_panelfade(MenuResize);\r
+ }\r
+ });\r
+ \r
+ $("#menuitem_" + MenuRotate).click(function()\r
+ {\r
+ if ($('#panel').val() != MenuRotate)\r
+ {\r
+ phpimageeditor_panelfade(MenuRotate);\r
+ }\r
+ });\r
+ \r
+ $("#menuitem_" + MenuCrop).click(function()\r
+ {\r
+ if ($('#panel').val() != MenuCrop)\r
+ {\r
+ phpimageeditor_panelfade(MenuCrop);\r
+ }\r
+ });\r
+ \r
+ if ($("#menuitem_" + MenuEffects) != null)\r
+ {\r
+ $("#menuitem_" + MenuEffects).click(function()\r
+ {\r
+ if ($('#panel').val() != MenuEffects)\r
+ {\r
+ phpimageeditor_panelfade(MenuEffects);\r
+ }\r
+ });\r
+ }\r
+\r
+ $('#cropkeepproportions').change(function(e) \r
+ {\r
+ if (objCrop != null)\r
+ {\r
+ if (this.checked && parseFloat($("#cropwidth").html()) != 0 && parseFloat($("#cropheight").html()) != 0)\r
+ { \r
+ var aspectRatio = parseFloat($("#cropwidth").html()) / parseFloat($("#cropheight").html());\r
+ objCrop.setOptions({ aspectRatio: aspectRatio });\r
+ $("#cropkeepproportionsratio").val(aspectRatio);\r
+ }\r
+ else if (this.checked && parseFloat($("#cropwidth").html()) == 0 && parseFloat($("#cropheight").html()) == 0)\r
+ {\r
+ objCrop.setOptions({ aspectRatio: $("#cropkeepproportionsratio").val() });\r
+ } \r
+ else\r
+ { \r
+ objCrop.setOptions({ aspectRatio: 0 });\r
+ }\r
+ }\r
+ });\r
+\r
+ $("input#width").numeric();\r
+ $("input#height").numeric();\r
+ \r
+ var selectedIndex = parseInt($('#panel').val());\r
+ for (i = 0; i < 4; i++)\r
+ {\r
+ if ($('#panel_'+i) != null)\r
+ {\r
+ if (i == selectedIndex)\r
+ {\r
+ $("#panel_"+i).css('opacity','1.0');\r
+ $("#panel_"+i).css('display','block');\r
+ }\r
+ else\r
+ {\r
+ $("#panel_"+i).css('opacity','0.0');\r
+ $("#panel_"+i).css('display','none');\r
+ }\r
+ }\r
+ } \r
+ \r
+ phpimageeditor_crop_activator(selectedIndex);\r
+ phpimageeditor_resize_activator(selectedIndex);\r
+}\r
+\r
+$(document).ready(function()\r
+{\r
+ phpimageeditor_init();\r
+});define('CKIMAGE_ORIGINAL', TOOLBOX_ORIGINAL);\r
+define('CKIMAGE_RESIZED', TOOLBOX_RESIZED);\r
+define('CKIMAGE_MIDSIZED', TOOLBOX_MIDSIZED);\r
+define('CKIMAGE_THUMB', TOOLBOX_THUMB);
\ No newline at end of file
--- /dev/null
+/*
+ * jQuery UI 1.7
+ *
+ * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * http://docs.jquery.com/UI
+ */
+;jQuery.ui || (function($) {
+
+var _remove = $.fn.remove,
+ isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);
+
+//Helper functions and ui object
+$.ui = {
+ version: "1.7",
+
+ // $.ui.plugin is deprecated. Use the proxy pattern instead.
+ plugin: {
+ add: function(module, option, set) {
+ var proto = $.ui[module].prototype;
+ for(var i in set) {
+ proto.plugins[i] = proto.plugins[i] || [];
+ proto.plugins[i].push([option, set[i]]);
+ }
+ },
+ call: function(instance, name, args) {
+ var set = instance.plugins[name];
+ if(!set || !instance.element[0].parentNode) { return; }
+
+ for (var i = 0; i < set.length; i++) {
+ if (instance.options[set[i][0]]) {
+ set[i][1].apply(instance.element, args);
+ }
+ }
+ }
+ },
+
+ contains: function(a, b) {
+ return document.compareDocumentPosition
+ ? a.compareDocumentPosition(b) & 16
+ : a !== b && a.contains(b);
+ },
+
+ hasScroll: function(el, a) {
+
+ //If overflow is hidden, the element might have extra content, but the user wants to hide it
+ if ($(el).css('overflow') == 'hidden') { return false; }
+
+ var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
+ has = false;
+
+ if (el[scroll] > 0) { return true; }
+
+ // TODO: determine which cases actually cause this to happen
+ // if the element doesn't have the scroll set, see if it's possible to
+ // set the scroll
+ el[scroll] = 1;
+ has = (el[scroll] > 0);
+ el[scroll] = 0;
+ return has;
+ },
+
+ isOverAxis: function(x, reference, size) {
+ //Determines when x coordinate is over "b" element axis
+ return (x > reference) && (x < (reference + size));
+ },
+
+ isOver: function(y, x, top, left, height, width) {
+ //Determines when x, y coordinates is over "b" element
+ return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
+ },
+
+ keyCode: {
+ BACKSPACE: 8,
+ CAPS_LOCK: 20,
+ COMMA: 188,
+ CONTROL: 17,
+ DELETE: 46,
+ DOWN: 40,
+ END: 35,
+ ENTER: 13,
+ ESCAPE: 27,
+ HOME: 36,
+ INSERT: 45,
+ LEFT: 37,
+ NUMPAD_ADD: 107,
+ NUMPAD_DECIMAL: 110,
+ NUMPAD_DIVIDE: 111,
+ NUMPAD_ENTER: 108,
+ NUMPAD_MULTIPLY: 106,
+ NUMPAD_SUBTRACT: 109,
+ PAGE_DOWN: 34,
+ PAGE_UP: 33,
+ PERIOD: 190,
+ RIGHT: 39,
+ SHIFT: 16,
+ SPACE: 32,
+ TAB: 9,
+ UP: 38
+ }
+};
+
+// WAI-ARIA normalization
+if (isFF2) {
+ var attr = $.attr,
+ removeAttr = $.fn.removeAttr,
+ ariaNS = "http://www.w3.org/2005/07/aaa",
+ ariaState = /^aria-/,
+ ariaRole = /^wairole:/;
+
+ $.attr = function(elem, name, value) {
+ var set = value !== undefined;
+
+ return (name == 'role'
+ ? (set
+ ? attr.call(this, elem, name, "wairole:" + value)
+ : (attr.apply(this, arguments) || "").replace(ariaRole, ""))
+ : (ariaState.test(name)
+ ? (set
+ ? elem.setAttributeNS(ariaNS,
+ name.replace(ariaState, "aaa:"), value)
+ : attr.call(this, elem, name.replace(ariaState, "aaa:")))
+ : attr.apply(this, arguments)));
+ };
+
+ $.fn.removeAttr = function(name) {
+ return (ariaState.test(name)
+ ? this.each(function() {
+ this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
+ }) : removeAttr.call(this, name));
+ };
+}
+
+//jQuery plugins
+$.fn.extend({
+ remove: function() {
+ // Safari has a native remove event which actually removes DOM elements,
+ // so we have to use triggerHandler instead of trigger (#3037).
+ $("*", this).add(this).each(function() {
+ $(this).triggerHandler("remove");
+ });
+ return _remove.apply(this, arguments );
+ },
+
+ enableSelection: function() {
+ return this
+ .attr('unselectable', 'off')
+ .css('MozUserSelect', '')
+ .unbind('selectstart.ui');
+ },
+
+ disableSelection: function() {
+ return this
+ .attr('unselectable', 'on')
+ .css('MozUserSelect', 'none')
+ .bind('selectstart.ui', function() { return false; });
+ },
+
+ scrollParent: function() {
+ var scrollParent;
+ if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
+ scrollParent = this.parents().filter(function() {
+ return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
+ }).eq(0);
+ } else {
+ scrollParent = this.parents().filter(function() {
+ return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
+ }).eq(0);
+ }
+
+ return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
+ }
+});
+
+
+//Additional selectors
+$.extend($.expr[':'], {
+ data: function(elem, i, match) {
+ return !!$.data(elem, match[3]);
+ },
+
+ focusable: function(element) {
+ var nodeName = element.nodeName.toLowerCase(),
+ tabIndex = $.attr(element, 'tabindex');
+ return (/input|select|textarea|button|object/.test(nodeName)
+ ? !element.disabled
+ : 'a' == nodeName || 'area' == nodeName
+ ? element.href || !isNaN(tabIndex)
+ : !isNaN(tabIndex))
+ // the element and all of its ancestors must be visible
+ // the browser may report that the area is hidden
+ && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
+ },
+
+ tabbable: function(element) {
+ var tabIndex = $.attr(element, 'tabindex');
+ return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
+ }
+});
+
+
+// $.widget is a factory to create jQuery plugins
+// taking some boilerplate code out of the plugin code
+function getter(namespace, plugin, method, args) {
+ function getMethods(type) {
+ var methods = $[namespace][plugin][type] || [];
+ return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
+ }
+
+ var methods = getMethods('getter');
+ if (args.length == 1 && typeof args[0] == 'string') {
+ methods = methods.concat(getMethods('getterSetter'));
+ }
+ return ($.inArray(method, methods) != -1);
+}
+
+$.widget = function(name, prototype) {
+ var namespace = name.split(".")[0];
+ name = name.split(".")[1];
+
+ // create plugin method
+ $.fn[name] = function(options) {
+ var isMethodCall = (typeof options == 'string'),
+ args = Array.prototype.slice.call(arguments, 1);
+
+ // prevent calls to internal methods
+ if (isMethodCall && options.substring(0, 1) == '_') {
+ return this;
+ }
+
+ // handle getter methods
+ if (isMethodCall && getter(namespace, name, options, args)) {
+ var instance = $.data(this[0], name);
+ return (instance ? instance[options].apply(instance, args)
+ : undefined);
+ }
+
+ // handle initialization and non-getter methods
+ return this.each(function() {
+ var instance = $.data(this, name);
+
+ // constructor
+ (!instance && !isMethodCall &&
+ $.data(this, name, new $[namespace][name](this, options))._init());
+
+ // method call
+ (instance && isMethodCall && $.isFunction(instance[options]) &&
+ instance[options].apply(instance, args));
+ });
+ };
+
+ // create widget constructor
+ $[namespace] = $[namespace] || {};
+ $[namespace][name] = function(element, options) {
+ var self = this;
+
+ this.namespace = namespace;
+ this.widgetName = name;
+ this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
+ this.widgetBaseClass = namespace + '-' + name;
+
+ this.options = $.extend({},
+ $.widget.defaults,
+ $[namespace][name].defaults,
+ $.metadata && $.metadata.get(element)[name],
+ options);
+
+ this.element = $(element)
+ .bind('setData.' + name, function(event, key, value) {
+ if (event.target == element) {
+ return self._setData(key, value);
+ }
+ })
+ .bind('getData.' + name, function(event, key) {
+ if (event.target == element) {
+ return self._getData(key);
+ }
+ })
+ .bind('remove', function() {
+ return self.destroy();
+ });
+ };
+
+ // add widget prototype
+ $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
+
+ // TODO: merge getter and getterSetter properties from widget prototype
+ // and plugin prototype
+ $[namespace][name].getterSetter = 'option';
+};
+
+$.widget.prototype = {
+ _init: function() {},
+ destroy: function() {
+ this.element.removeData(this.widgetName)
+ .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
+ .removeAttr('aria-disabled');
+ },
+
+ option: function(key, value) {
+ var options = key,
+ self = this;
+
+ if (typeof key == "string") {
+ if (value === undefined) {
+ return this._getData(key);
+ }
+ options = {};
+ options[key] = value;
+ }
+
+ $.each(options, function(key, value) {
+ self._setData(key, value);
+ });
+ },
+ _getData: function(key) {
+ return this.options[key];
+ },
+ _setData: function(key, value) {
+ this.options[key] = value;
+
+ if (key == 'disabled') {
+ this.element
+ [value ? 'addClass' : 'removeClass'](
+ this.widgetBaseClass + '-disabled' + ' ' +
+ this.namespace + '-state-disabled')
+ .attr("aria-disabled", value);
+ }
+ },
+
+ enable: function() {
+ this._setData('disabled', false);
+ },
+ disable: function() {
+ this._setData('disabled', true);
+ },
+
+ _trigger: function(type, event, data) {
+ var callback = this.options[type],
+ eventName = (type == this.widgetEventPrefix
+ ? type : this.widgetEventPrefix + type);
+
+ event = $.Event(event);
+ event.type = eventName;
+
+ // copy original event properties over to the new event
+ // this would happen if we could call $.event.fix instead of $.Event
+ // but we don't have a way to force an event to be fixed multiple times
+ if (event.originalEvent) {
+ for (var i = $.event.props.length, prop; i;) {
+ prop = $.event.props[--i];
+ event[prop] = event.originalEvent[prop];
+ }
+ }
+
+ this.element.trigger(event, data);
+
+ return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
+ || event.isDefaultPrevented());
+ }
+};
+
+$.widget.defaults = {
+ disabled: false
+};
+
+
+/** Mouse Interaction Plugin **/
+
+$.ui.mouse = {
+ _mouseInit: function() {
+ var self = this;
+
+ this.element
+ .bind('mousedown.'+this.widgetName, function(event) {
+ return self._mouseDown(event);
+ })
+ .bind('click.'+this.widgetName, function(event) {
+ if(self._preventClickEvent) {
+ self._preventClickEvent = false;
+ event.stopImmediatePropagation();
+ return false;
+ }
+ });
+
+ // Prevent text selection in IE
+ if ($.browser.msie) {
+ this._mouseUnselectable = this.element.attr('unselectable');
+ this.element.attr('unselectable', 'on');
+ }
+
+ this.started = false;
+ },
+
+ // TODO: make sure destroying one instance of mouse doesn't mess with
+ // other instances of mouse
+ _mouseDestroy: function() {
+ this.element.unbind('.'+this.widgetName);
+
+ // Restore text selection in IE
+ ($.browser.msie
+ && this.element.attr('unselectable', this._mouseUnselectable));
+ },
+
+ _mouseDown: function(event) {
+ // don't let more than one widget handle mouseStart
+ // TODO: figure out why we have to use originalEvent
+ event.originalEvent = event.originalEvent || {};
+ if (event.originalEvent.mouseHandled) { return; }
+
+ // we may have missed mouseup (out of window)
+ (this._mouseStarted && this._mouseUp(event));
+
+ this._mouseDownEvent = event;
+
+ var self = this,
+ btnIsLeft = (event.which == 1),
+ elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
+ if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
+ return true;
+ }
+
+ this.mouseDelayMet = !this.options.delay;
+ if (!this.mouseDelayMet) {
+ this._mouseDelayTimer = setTimeout(function() {
+ self.mouseDelayMet = true;
+ }, this.options.delay);
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted = (this._mouseStart(event) !== false);
+ if (!this._mouseStarted) {
+ event.preventDefault();
+ return true;
+ }
+ }
+
+ // these delegates are required to keep context
+ this._mouseMoveDelegate = function(event) {
+ return self._mouseMove(event);
+ };
+ this._mouseUpDelegate = function(event) {
+ return self._mouseUp(event);
+ };
+ $(document)
+ .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
+ .bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
+
+ // preventDefault() is used to prevent the selection of text here -
+ // however, in Safari, this causes select boxes not to be selectable
+ // anymore, so this fix is needed
+ ($.browser.safari || event.preventDefault());
+
+ event.originalEvent.mouseHandled = true;
+ return true;
+ },
+
+ _mouseMove: function(event) {
+ // IE mouseup check - mouseup happened when mouse was out of window
+ if ($.browser.msie && !event.button) {
+ return this._mouseUp(event);
+ }
+
+ if (this._mouseStarted) {
+ this._mouseDrag(event);
+ return event.preventDefault();
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted =
+ (this._mouseStart(this._mouseDownEvent, event) !== false);
+ (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
+ }
+
+ return !this._mouseStarted;
+ },
+
+ _mouseUp: function(event) {
+ $(document)
+ .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
+ .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
+
+ if (this._mouseStarted) {
+ this._mouseStarted = false;
+ this._preventClickEvent = (event.target == this._mouseDownEvent.target);
+ this._mouseStop(event);
+ }
+
+ return false;
+ },
+
+ _mouseDistanceMet: function(event) {
+ return (Math.max(
+ Math.abs(this._mouseDownEvent.pageX - event.pageX),
+ Math.abs(this._mouseDownEvent.pageY - event.pageY)
+ ) >= this.options.distance
+ );
+ },
+
+ _mouseDelayMet: function(event) {
+ return this.mouseDelayMet;
+ },
+
+ // These are placeholder methods, to be overriden by extending plugin
+ _mouseStart: function(event) {},
+ _mouseDrag: function(event) {},
+ _mouseStop: function(event) {},
+ _mouseCapture: function(event) { return true; }
+};
+
+$.ui.mouse.defaults = {
+ cancel: null,
+ distance: 1,
+ delay: 0
+};
+
+})(jQuery);
--- /dev/null
+/*
+ * jQuery UI Resizable 1.7
+ *
+ * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * http://docs.jquery.com/UI/Resizables
+ *
+ * Depends:
+ * ui.core.js
+ */
+(function($) {
+
+$.widget("ui.resizable", $.extend({}, $.ui.mouse, {
+
+ _init: function() {
+
+ var self = this, o = this.options;
+ this.element.addClass("ui-resizable");
+
+ $.extend(this, {
+ _aspectRatio: !!(o.aspectRatio),
+ aspectRatio: o.aspectRatio,
+ originalElement: this.element,
+ _proportionallyResizeElements: [],
+ _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null
+ });
+
+ //Wrap the element if it cannot hold child nodes
+ if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
+
+ //Opera fix for relative positioning
+ if (/relative/.test(this.element.css('position')) && $.browser.opera)
+ this.element.css({ position: 'relative', top: 'auto', left: 'auto' });
+
+ //Create a wrapper element and set the wrapper to the new current internal element
+ this.element.wrap(
+ $('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({
+ position: this.element.css('position'),
+ width: this.element.outerWidth(),
+ height: this.element.outerHeight(),
+ top: this.element.css('top'),
+ left: this.element.css('left')
+ })
+ );
+
+ //Overwrite the original this.element
+ this.element = this.element.parent().data(
+ "resizable", this.element.data('resizable')
+ );
+
+ this.elementIsWrapper = true;
+
+ //Move margins to the wrapper
+ this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
+ this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
+
+ //Prevent Safari textarea resize
+ this.originalResizeStyle = this.originalElement.css('resize');
+ this.originalElement.css('resize', 'none');
+
+ //Push the actual element to our proportionallyResize internal array
+ this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' }));
+
+ // avoid IE jump (hard set the margin)
+ this.originalElement.css({ margin: this.originalElement.css('margin') });
+
+ // fix handlers offset
+ this._proportionallyResize();
+
+ }
+
+ this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' });
+ if(this.handles.constructor == String) {
+
+ if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw';
+ var n = this.handles.split(","); this.handles = {};
+
+ for(var i = 0; i < n.length; i++) {
+
+ var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle;
+ var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>');
+
+ // increase zIndex of sw, se, ne, nw axis
+ //TODO : this modifies original option
+ if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex });
+
+ //TODO : What's going on here?
+ if ('se' == handle) {
+ axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se');
+ };
+
+ //Insert into internal handles object and append to element
+ this.handles[handle] = '.ui-resizable-'+handle;
+ this.element.append(axis);
+ }
+
+ }
+
+ this._renderAxis = function(target) {
+
+ target = target || this.element;
+
+ for(var i in this.handles) {
+
+ if(this.handles[i].constructor == String)
+ this.handles[i] = $(this.handles[i], this.element).show();
+
+ //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
+ if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
+
+ var axis = $(this.handles[i], this.element), padWrapper = 0;
+
+ //Checking the correct pad and border
+ padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
+
+ //The padding type i have to apply...
+ var padPos = [ 'padding',
+ /ne|nw|n/.test(i) ? 'Top' :
+ /se|sw|s/.test(i) ? 'Bottom' :
+ /^e$/.test(i) ? 'Right' : 'Left' ].join("");
+
+ target.css(padPos, padWrapper);
+
+ this._proportionallyResize();
+
+ }
+
+ //TODO: What's that good for? There's not anything to be executed left
+ if(!$(this.handles[i]).length)
+ continue;
+
+ }
+ };
+
+ //TODO: make renderAxis a prototype function
+ this._renderAxis(this.element);
+
+ this._handles = $('.ui-resizable-handle', this.element)
+ .disableSelection();
+
+ //Matching axis name
+ this._handles.mouseover(function() {
+ if (!self.resizing) {
+ if (this.className)
+ var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
+ //Axis, default = se
+ self.axis = axis && axis[1] ? axis[1] : 'se';
+ }
+ });
+
+ //If we want to auto hide the elements
+ if (o.autoHide) {
+ this._handles.hide();
+ $(this.element)
+ .addClass("ui-resizable-autohide")
+ .hover(function() {
+ $(this).removeClass("ui-resizable-autohide");
+ self._handles.show();
+ },
+ function(){
+ if (!self.resizing) {
+ $(this).addClass("ui-resizable-autohide");
+ self._handles.hide();
+ }
+ });
+ }
+
+ //Initialize the mouse interaction
+ this._mouseInit();
+
+ },
+
+ destroy: function() {
+
+ this._mouseDestroy();
+
+ var _destroy = function(exp) {
+ $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
+ .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
+ };
+
+ //TODO: Unwrap at same DOM position
+ if (this.elementIsWrapper) {
+ _destroy(this.element);
+ var wrapper = this.element;
+ wrapper.parent().append(
+ this.originalElement.css({
+ position: wrapper.css('position'),
+ width: wrapper.outerWidth(),
+ height: wrapper.outerHeight(),
+ top: wrapper.css('top'),
+ left: wrapper.css('left')
+ })
+ ).end().remove();
+ }
+
+ this.originalElement.css('resize', this.originalResizeStyle);
+ _destroy(this.originalElement);
+
+ },
+
+ _mouseCapture: function(event) {
+
+ var handle = false;
+ for(var i in this.handles) {
+ if($(this.handles[i])[0] == event.target) handle = true;
+ }
+
+ return this.options.disabled || !!handle;
+
+ },
+
+ _mouseStart: function(event) {
+
+ var o = this.options, iniPos = this.element.position(), el = this.element;
+
+ this.resizing = true;
+ this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };
+
+ // bugfix for http://dev.jquery.com/ticket/1749
+ if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {
+ el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left });
+ }
+
+ //Opera fixing relative position
+ if ($.browser.opera && (/relative/).test(el.css('position')))
+ el.css({ position: 'relative', top: 'auto', left: 'auto' });
+
+ this._renderProxy();
+
+ var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));
+
+ if (o.containment) {
+ curleft += $(o.containment).scrollLeft() || 0;
+ curtop += $(o.containment).scrollTop() || 0;
+ }
+
+ //Store needed variables
+ this.offset = this.helper.offset();
+ this.position = { left: curleft, top: curtop };
+ this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
+ this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
+ this.originalPosition = { left: curleft, top: curtop };
+ this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
+ this.originalMousePosition = { left: event.pageX, top: event.pageY };
+
+ //Aspect Ratio
+ this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
+
+ var cursor = $('.ui-resizable-' + this.axis).css('cursor');
+ $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor);
+
+ el.addClass("ui-resizable-resizing");
+ this._propagate("start", event);
+ return true;
+ },
+
+ _mouseDrag: function(event) {
+
+ //Increase performance, avoid regex
+ var el = this.helper, o = this.options, props = {},
+ self = this, smp = this.originalMousePosition, a = this.axis;
+
+ var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0;
+ var trigger = this._change[a];
+ if (!trigger) return false;
+
+ // Calculate the attrs that will be change
+ var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;
+
+ if (this._aspectRatio || event.shiftKey)
+ data = this._updateRatio(data, event);
+
+ data = this._respectSize(data, event);
+
+ // plugins callbacks need to be called first
+ this._propagate("resize", event);
+
+ el.css({
+ top: this.position.top + "px", left: this.position.left + "px",
+ width: this.size.width + "px", height: this.size.height + "px"
+ });
+
+ if (!this._helper && this._proportionallyResizeElements.length)
+ this._proportionallyResize();
+
+ this._updateCache(data);
+
+ // calling the user callback at the end
+ this._trigger('resize', event, this.ui());
+
+ return false;
+ },
+
+ _mouseStop: function(event) {
+
+ this.resizing = false;
+ var o = this.options, self = this;
+
+ if(this._helper) {
+ var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
+ soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
+ soffsetw = ista ? 0 : self.sizeDiff.width;
+
+ var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
+ left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
+ top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;
+
+ if (!o.animate)
+ this.element.css($.extend(s, { top: top, left: left }));
+
+ self.helper.height(self.size.height);
+ self.helper.width(self.size.width);
+
+ if (this._helper && !o.animate) this._proportionallyResize();
+ }
+
+ $('body').css('cursor', 'auto');
+
+ this.element.removeClass("ui-resizable-resizing");
+
+ this._propagate("stop", event);
+
+ if (this._helper) this.helper.remove();
+ return false;
+
+ },
+
+ _updateCache: function(data) {
+ var o = this.options;
+ this.offset = this.helper.offset();
+ if (isNumber(data.left)) this.position.left = data.left;
+ if (isNumber(data.top)) this.position.top = data.top;
+ if (isNumber(data.height)) this.size.height = data.height;
+ if (isNumber(data.width)) this.size.width = data.width;
+ },
+
+ _updateRatio: function(data, event) {
+
+ var o = this.options, cpos = this.position, csize = this.size, a = this.axis;
+
+ if (data.height) data.width = (csize.height * this.aspectRatio);
+ else if (data.width) data.height = (csize.width / this.aspectRatio);
+
+ if (a == 'sw') {
+ data.left = cpos.left + (csize.width - data.width);
+ data.top = null;
+ }
+ if (a == 'nw') {
+ data.top = cpos.top + (csize.height - data.height);
+ data.left = cpos.left + (csize.width - data.width);
+ }
+
+ return data;
+ },
+
+ _respectSize: function(data, event) {
+
+ var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis,
+ ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
+ isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height);
+
+ if (isminw) data.width = o.minWidth;
+ if (isminh) data.height = o.minHeight;
+ if (ismaxw) data.width = o.maxWidth;
+ if (ismaxh) data.height = o.maxHeight;
+
+ var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
+ var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
+
+ if (isminw && cw) data.left = dw - o.minWidth;
+ if (ismaxw && cw) data.left = dw - o.maxWidth;
+ if (isminh && ch) data.top = dh - o.minHeight;
+ if (ismaxh && ch) data.top = dh - o.maxHeight;
+
+ // fixing jump error on top/left - bug #2330
+ var isNotwh = !data.width && !data.height;
+ if (isNotwh && !data.left && data.top) data.top = null;
+ else if (isNotwh && !data.top && data.left) data.left = null;
+
+ return data;
+ },
+
+ _proportionallyResize: function() {
+
+ var o = this.options;
+ if (!this._proportionallyResizeElements.length) return;
+ var element = this.helper || this.element;
+
+ for (var i=0; i < this._proportionallyResizeElements.length; i++) {
+
+ var prel = this._proportionallyResizeElements[i];
+
+ if (!this.borderDif) {
+ var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
+ p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];
+
+ this.borderDif = $.map(b, function(v, i) {
+ var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
+ return border + padding;
+ });
+ }
+
+ if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length)))
+ continue;
+
+ prel.css({
+ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
+ width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
+ });
+
+ };
+
+ },
+
+ _renderProxy: function() {
+
+ var el = this.element, o = this.options;
+ this.elementOffset = el.offset();
+
+ if(this._helper) {
+
+ this.helper = this.helper || $('<div style="overflow:hidden;"></div>');
+
+ // fix ie6 offset TODO: This seems broken
+ var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
+ pxyoffset = ( ie6 ? 2 : -1 );
+
+ this.helper.addClass(this._helper).css({
+ width: this.element.outerWidth() + pxyoffset,
+ height: this.element.outerHeight() + pxyoffset,
+ position: 'absolute',
+ left: this.elementOffset.left - ie6offset +'px',
+ top: this.elementOffset.top - ie6offset +'px',
+ zIndex: ++o.zIndex //TODO: Don't modify option
+ });
+
+ this.helper
+ .appendTo("body")
+ .disableSelection();
+
+ } else {
+ this.helper = this.element;
+ }
+
+ },
+
+ _change: {
+ e: function(event, dx, dy) {
+ return { width: this.originalSize.width + dx };
+ },
+ w: function(event, dx, dy) {
+ var o = this.options, cs = this.originalSize, sp = this.originalPosition;
+ return { left: sp.left + dx, width: cs.width - dx };
+ },
+ n: function(event, dx, dy) {
+ var o = this.options, cs = this.originalSize, sp = this.originalPosition;
+ return { top: sp.top + dy, height: cs.height - dy };
+ },
+ s: function(event, dx, dy) {
+ return { height: this.originalSize.height + dy };
+ },
+ se: function(event, dx, dy) {
+ return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
+ },
+ sw: function(event, dx, dy) {
+ return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
+ },
+ ne: function(event, dx, dy) {
+ return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
+ },
+ nw: function(event, dx, dy) {
+ return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
+ }
+ },
+
+ _propagate: function(n, event) {
+ $.ui.plugin.call(this, n, [event, this.ui()]);
+ (n != "resize" && this._trigger(n, event, this.ui()));
+ },
+
+ plugins: {},
+
+ ui: function() {
+ return {
+ originalElement: this.originalElement,
+ element: this.element,
+ helper: this.helper,
+ position: this.position,
+ size: this.size,
+ originalSize: this.originalSize,
+ originalPosition: this.originalPosition
+ };
+ }
+
+}));
+
+$.extend($.ui.resizable, {
+ version: "1.7",
+ eventPrefix: "resize",
+ defaults: {
+ alsoResize: false,
+ animate: false,
+ animateDuration: "slow",
+ animateEasing: "swing",
+ aspectRatio: false,
+ autoHide: false,
+ cancel: ":input,option",
+ containment: false,
+ delay: 0,
+ distance: 1,
+ ghost: false,
+ grid: false,
+ handles: "e,s,se",
+ helper: false,
+ maxHeight: null,
+ maxWidth: null,
+ minHeight: 10,
+ minWidth: 10,
+ zIndex: 1000
+ }
+});
+
+/*
+ * Resizable Extensions
+ */
+
+$.ui.plugin.add("resizable", "alsoResize", {
+
+ start: function(event, ui) {
+
+ var self = $(this).data("resizable"), o = self.options;
+
+ _store = function(exp) {
+ $(exp).each(function() {
+ $(this).data("resizable-alsoresize", {
+ width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10),
+ left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10)
+ });
+ });
+ };
+
+ if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
+ if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
+ else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); }
+ }else{
+ _store(o.alsoResize);
+ }
+ },
+
+ resize: function(event, ui){
+ var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition;
+
+ var delta = {
+ height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
+ top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
+ },
+
+ _alsoResize = function(exp, c) {
+ $(exp).each(function() {
+ var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];
+
+ $.each(css || ['width', 'height', 'top', 'left'], function(i, prop) {
+ var sum = (start[prop]||0) + (delta[prop]||0);
+ if (sum && sum >= 0)
+ style[prop] = sum || null;
+ });
+
+ //Opera fixing relative position
+ if (/relative/.test(el.css('position')) && $.browser.opera) {
+ self._revertToRelativePosition = true;
+ el.css({ position: 'absolute', top: 'auto', left: 'auto' });
+ }
+
+ el.css(style);
+ });
+ };
+
+ if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) {
+ $.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); });
+ }else{
+ _alsoResize(o.alsoResize);
+ }
+ },
+
+ stop: function(event, ui){
+ var self = $(this).data("resizable");
+
+ //Opera fixing relative position
+ if (self._revertToRelativePosition && $.browser.opera) {
+ self._revertToRelativePosition = false;
+ el.css({ position: 'relative' });
+ }
+
+ $(this).removeData("resizable-alsoresize-start");
+ }
+});
+
+$.ui.plugin.add("resizable", "animate", {
+
+ stop: function(event, ui) {
+ var self = $(this).data("resizable"), o = self.options;
+
+ var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
+ soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
+ soffsetw = ista ? 0 : self.sizeDiff.width;
+
+ var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
+ left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
+ top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;
+
+ self.element.animate(
+ $.extend(style, top && left ? { top: top, left: left } : {}), {
+ duration: o.animateDuration,
+ easing: o.animateEasing,
+ step: function() {
+
+ var data = {
+ width: parseInt(self.element.css('width'), 10),
+ height: parseInt(self.element.css('height'), 10),
+ top: parseInt(self.element.css('top'), 10),
+ left: parseInt(self.element.css('left'), 10)
+ };
+
+ if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height });
+
+ // propagating resize, and updating values for each animation step
+ self._updateCache(data);
+ self._propagate("resize", event);
+
+ }
+ }
+ );
+ }
+
+});
+
+$.ui.plugin.add("resizable", "containment", {
+
+ start: function(event, ui) {
+ var self = $(this).data("resizable"), o = self.options, el = self.element;
+ var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
+ if (!ce) return;
+
+ self.containerElement = $(ce);
+
+ if (/document/.test(oc) || oc == document) {
+ self.containerOffset = { left: 0, top: 0 };
+ self.containerPosition = { left: 0, top: 0 };
+
+ self.parentData = {
+ element: $(document), left: 0, top: 0,
+ width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
+ };
+ }
+
+ // i'm a node, so compute top, left, right, bottom
+ else {
+ var element = $(ce), p = [];
+ $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });
+
+ self.containerOffset = element.offset();
+ self.containerPosition = element.position();
+ self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };
+
+ var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width,
+ width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
+
+ self.parentData = {
+ element: ce, left: co.left, top: co.top, width: width, height: height
+ };
+ }
+ },
+
+ resize: function(event, ui) {
+ var self = $(this).data("resizable"), o = self.options,
+ ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
+ pRatio = o._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;
+
+ if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co;
+
+ if (cp.left < (self._helper ? co.left : 0)) {
+ self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left));
+ if (pRatio) self.size.height = self.size.width / o.aspectRatio;
+ self.position.left = o.helper ? co.left : 0;
+ }
+
+ if (cp.top < (self._helper ? co.top : 0)) {
+ self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top);
+ if (pRatio) self.size.width = self.size.height * o.aspectRatio;
+ self.position.top = self._helper ? co.top : 0;
+ }
+
+ self.offset.left = self.parentData.left+self.position.left;
+ self.offset.top = self.parentData.top+self.position.top;
+
+ var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ),
+ hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height );
+
+ var isParent = self.containerElement.get(0) == self.element.parent().get(0),
+ isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position'));
+
+ if(isParent && isOffsetRelative) woset -= self.parentData.left;
+
+ if (woset + self.size.width >= self.parentData.width) {
+ self.size.width = self.parentData.width - woset;
+ if (pRatio) self.size.height = self.size.width / o.aspectRatio;
+ }
+
+ if (hoset + self.size.height >= self.parentData.height) {
+ self.size.height = self.parentData.height - hoset;
+ if (pRatio) self.size.width = self.size.height * o.aspectRatio;
+ }
+ },
+
+ stop: function(event, ui){
+ var self = $(this).data("resizable"), o = self.options, cp = self.position,
+ co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;
+
+ var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height;
+
+ if (self._helper && !o.animate && (/relative/).test(ce.css('position')))
+ $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
+
+ if (self._helper && !o.animate && (/static/).test(ce.css('position')))
+ $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
+
+ }
+});
+
+$.ui.plugin.add("resizable", "ghost", {
+
+ start: function(event, ui) {
+
+ var self = $(this).data("resizable"), o = self.options, cs = self.size;
+
+ self.ghost = self.originalElement.clone();
+ self.ghost
+ .css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
+ .addClass('ui-resizable-ghost')
+ .addClass(typeof o.ghost == 'string' ? o.ghost : '');
+
+ self.ghost.appendTo(self.helper);
+
+ },
+
+ resize: function(event, ui){
+ var self = $(this).data("resizable"), o = self.options;
+ if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });
+ },
+
+ stop: function(event, ui){
+ var self = $(this).data("resizable"), o = self.options;
+ if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
+ }
+
+});
+
+$.ui.plugin.add("resizable", "grid", {
+
+ resize: function(event, ui) {
+ var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey;
+ o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
+ var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);
+
+ if (/^(se|s|e)$/.test(a)) {
+ self.size.width = os.width + ox;
+ self.size.height = os.height + oy;
+ }
+ else if (/^(ne)$/.test(a)) {
+ self.size.width = os.width + ox;
+ self.size.height = os.height + oy;
+ self.position.top = op.top - oy;
+ }
+ else if (/^(sw)$/.test(a)) {
+ self.size.width = os.width + ox;
+ self.size.height = os.height + oy;
+ self.position.left = op.left - ox;
+ }
+ else {
+ self.size.width = os.width + ox;
+ self.size.height = os.height + oy;
+ self.position.top = op.top - oy;
+ self.position.left = op.left - ox;
+ }
+ }
+
+});
+
+var num = function(v) {
+ return parseInt(v, 10) || 0;
+};
+
+var isNumber = function(value) {
+ return !isNaN(parseInt(value, 10));
+};
+
+})(jQuery);
--- /dev/null
+/*
+ * jQuery UI Slider 1.7
+ *
+ * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * http://docs.jquery.com/UI/Slider
+ *
+ * Depends:
+ * ui.core.js
+ */
+
+(function($) {
+
+$.widget("ui.slider", $.extend({}, $.ui.mouse, {
+
+ _init: function() {
+
+ var self = this, o = this.options;
+ this._keySliding = false;
+ this._handleIndex = null;
+ this._detectOrientation();
+ this._mouseInit();
+
+ this.element
+ .addClass("ui-slider"
+ + " ui-slider-" + this.orientation
+ + " ui-widget"
+ + " ui-widget-content"
+ + " ui-corner-all");
+
+ this.range = $([]);
+
+ if (o.range) {
+
+ if (o.range === true) {
+ this.range = $('<div></div>');
+ if (!o.values) o.values = [this._valueMin(), this._valueMin()];
+ if (o.values.length && o.values.length != 2) {
+ o.values = [o.values[0], o.values[0]];
+ }
+ } else {
+ this.range = $('<div></div>');
+ }
+
+ this.range
+ .appendTo(this.element)
+ .addClass("ui-slider-range");
+
+ if (o.range == "min" || o.range == "max") {
+ this.range.addClass("ui-slider-range-" + o.range);
+ }
+
+ // note: this isn't the most fittingly semantic framework class for this element,
+ // but worked best visually with a variety of themes
+ this.range.addClass("ui-widget-header");
+
+ }
+
+ if ($(".ui-slider-handle", this.element).length == 0)
+ $('<a href="#"></a>')
+ .appendTo(this.element)
+ .addClass("ui-slider-handle");
+
+ if (o.values && o.values.length) {
+ while ($(".ui-slider-handle", this.element).length < o.values.length)
+ $('<a href="#"></a>')
+ .appendTo(this.element)
+ .addClass("ui-slider-handle");
+ }
+
+ this.handles = $(".ui-slider-handle", this.element)
+ .addClass("ui-state-default"
+ + " ui-corner-all");
+
+ this.handle = this.handles.eq(0);
+
+ this.handles.add(this.range).filter("a")
+ .click(function(event) { event.preventDefault(); })
+ .hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
+ .focus(function() { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); })
+ .blur(function() { $(this).removeClass('ui-state-focus'); });
+
+ this.handles.each(function(i) {
+ $(this).data("index.ui-slider-handle", i);
+ });
+
+ this.handles.keydown(function(event) {
+
+ var ret = true;
+
+ var index = $(this).data("index.ui-slider-handle");
+
+ if (self.options.disabled)
+ return;
+
+ switch (event.keyCode) {
+ case $.ui.keyCode.HOME:
+ case $.ui.keyCode.END:
+ case $.ui.keyCode.UP:
+ case $.ui.keyCode.RIGHT:
+ case $.ui.keyCode.DOWN:
+ case $.ui.keyCode.LEFT:
+ ret = false;
+ if (!self._keySliding) {
+ self._keySliding = true;
+ $(this).addClass("ui-state-active");
+ self._start(event, index);
+ }
+ break;
+ }
+
+ var curVal, newVal, step = self._step();
+ if (self.options.values && self.options.values.length) {
+ curVal = newVal = self.values(index);
+ } else {
+ curVal = newVal = self.value();
+ }
+
+ switch (event.keyCode) {
+ case $.ui.keyCode.HOME:
+ newVal = self._valueMin();
+ break;
+ case $.ui.keyCode.END:
+ newVal = self._valueMax();
+ break;
+ case $.ui.keyCode.UP:
+ case $.ui.keyCode.RIGHT:
+ if(curVal == self._valueMax()) return;
+ newVal = curVal + step;
+ break;
+ case $.ui.keyCode.DOWN:
+ case $.ui.keyCode.LEFT:
+ if(curVal == self._valueMin()) return;
+ newVal = curVal - step;
+ break;
+ }
+
+ self._slide(event, index, newVal);
+
+ return ret;
+
+ }).keyup(function(event) {
+
+ var index = $(this).data("index.ui-slider-handle");
+
+ if (self._keySliding) {
+ self._stop(event, index);
+ self._change(event, index);
+ self._keySliding = false;
+ $(this).removeClass("ui-state-active");
+ }
+
+ });
+
+ this._refreshValue();
+
+ },
+
+ destroy: function() {
+
+ this.handles.remove();
+
+ this.element
+ .removeClass("ui-slider"
+ + " ui-slider-horizontal"
+ + " ui-slider-vertical"
+ + " ui-slider-disabled"
+ + " ui-widget"
+ + " ui-widget-content"
+ + " ui-corner-all")
+ .removeData("slider")
+ .unbind(".slider");
+
+ this._mouseDestroy();
+
+ },
+
+ _mouseCapture: function(event) {
+
+ var o = this.options;
+
+ if (o.disabled)
+ return false;
+
+ this.elementSize = {
+ width: this.element.outerWidth(),
+ height: this.element.outerHeight()
+ };
+ this.elementOffset = this.element.offset();
+
+ var position = { x: event.pageX, y: event.pageY };
+ var normValue = this._normValueFromMouse(position);
+
+ var distance = this._valueMax() + 1, closestHandle;
+ var self = this, index;
+ this.handles.each(function(i) {
+ var thisDistance = Math.abs(normValue - self.values(i));
+ if (distance > thisDistance) {
+ distance = thisDistance;
+ closestHandle = $(this);
+ index = i;
+ }
+ });
+
+ // workaround for bug #3736 (if both handles of a range are at 0,
+ // the first is always used as the one with least distance,
+ // and moving it is obviously prevented by preventing negative ranges)
+ if(o.range == true && this.values(1) == o.min) {
+ closestHandle = $(this.handles[++index]);
+ }
+
+ this._start(event, index);
+
+ self._handleIndex = index;
+
+ closestHandle
+ .addClass("ui-state-active")
+ .focus();
+
+ var offset = closestHandle.offset();
+ var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle');
+ this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
+ left: event.pageX - offset.left - (closestHandle.width() / 2),
+ top: event.pageY - offset.top
+ - (closestHandle.height() / 2)
+ - (parseInt(closestHandle.css('borderTopWidth'),10) || 0)
+ - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0)
+ + (parseInt(closestHandle.css('marginTop'),10) || 0)
+ };
+
+ normValue = this._normValueFromMouse(position);
+ this._slide(event, index, normValue);
+ return true;
+
+ },
+
+ _mouseStart: function(event) {
+ return true;
+ },
+
+ _mouseDrag: function(event) {
+
+ var position = { x: event.pageX, y: event.pageY };
+ var normValue = this._normValueFromMouse(position);
+
+ this._slide(event, this._handleIndex, normValue);
+
+ return false;
+
+ },
+
+ _mouseStop: function(event) {
+
+ this.handles.removeClass("ui-state-active");
+ this._stop(event, this._handleIndex);
+ this._change(event, this._handleIndex);
+ this._handleIndex = null;
+ this._clickOffset = null;
+
+ return false;
+
+ },
+
+ _detectOrientation: function() {
+ this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal';
+ },
+
+ _normValueFromMouse: function(position) {
+
+ var pixelTotal, pixelMouse;
+ if ('horizontal' == this.orientation) {
+ pixelTotal = this.elementSize.width;
+ pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0);
+ } else {
+ pixelTotal = this.elementSize.height;
+ pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0);
+ }
+
+ var percentMouse = (pixelMouse / pixelTotal);
+ if (percentMouse > 1) percentMouse = 1;
+ if (percentMouse < 0) percentMouse = 0;
+ if ('vertical' == this.orientation)
+ percentMouse = 1 - percentMouse;
+
+ var valueTotal = this._valueMax() - this._valueMin(),
+ valueMouse = percentMouse * valueTotal,
+ valueMouseModStep = valueMouse % this.options.step,
+ normValue = this._valueMin() + valueMouse - valueMouseModStep;
+
+ if (valueMouseModStep > (this.options.step / 2))
+ normValue += this.options.step;
+
+ // Since JavaScript has problems with large floats, round
+ // the final value to 5 digits after the decimal point (see #4124)
+ return parseFloat(normValue.toFixed(5));
+
+ },
+
+ _start: function(event, index) {
+ this._trigger("start", event, this._uiHash(index));
+ },
+
+ _slide: function(event, index, newVal) {
+
+ var handle = this.handles[index];
+
+ if (this.options.values && this.options.values.length) {
+
+ var otherVal = this.values(index ? 0 : 1);
+
+ if ((index == 0 && newVal >= otherVal) || (index == 1 && newVal <= otherVal))
+ newVal = otherVal;
+
+ if (newVal != this.values(index)) {
+ var newValues = this.values();
+ newValues[index] = newVal;
+ // A slide can be canceled by returning false from the slide callback
+ var allowed = this._trigger("slide", event, this._uiHash(index, newVal, newValues));
+ var otherVal = this.values(index ? 0 : 1);
+ if (allowed !== false) {
+ this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true);
+ }
+ }
+
+ } else {
+
+ if (newVal != this.value()) {
+ // A slide can be canceled by returning false from the slide callback
+ var allowed = this._trigger("slide", event, this._uiHash(index, newVal));
+ if (allowed !== false) {
+ this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate ));
+ }
+
+ }
+
+ }
+
+ },
+
+ _stop: function(event, index) {
+ this._trigger("stop", event, this._uiHash(index));
+ },
+
+ _change: function(event, index) {
+ this._trigger("change", event, this._uiHash(index));
+ },
+
+ value: function(newValue) {
+
+ if (arguments.length) {
+ this._setData("value", newValue);
+ this._change(null, 0);
+ }
+
+ return this._value();
+
+ },
+
+ values: function(index, newValue, animated, noPropagation) {
+
+ if (arguments.length > 1) {
+ this.options.values[index] = newValue;
+ this._refreshValue(animated);
+ if(!noPropagation) this._change(null, index);
+ }
+
+ if (arguments.length) {
+ if (this.options.values && this.options.values.length) {
+ return this._values(index);
+ } else {
+ return this.value();
+ }
+ } else {
+ return this._values();
+ }
+
+ },
+
+ _setData: function(key, value, animated) {
+
+ $.widget.prototype._setData.apply(this, arguments);
+
+ switch (key) {
+ case 'orientation':
+
+ this._detectOrientation();
+
+ this.element
+ .removeClass("ui-slider-horizontal ui-slider-vertical")
+ .addClass("ui-slider-" + this.orientation);
+ this._refreshValue(animated);
+ break;
+ case 'value':
+ this._refreshValue(animated);
+ break;
+ }
+
+ },
+
+ _step: function() {
+ var step = this.options.step;
+ return step;
+ },
+
+ _value: function() {
+
+ var val = this.options.value;
+ if (val < this._valueMin()) val = this._valueMin();
+ if (val > this._valueMax()) val = this._valueMax();
+
+ return val;
+
+ },
+
+ _values: function(index) {
+
+ if (arguments.length) {
+ var val = this.options.values[index];
+ if (val < this._valueMin()) val = this._valueMin();
+ if (val > this._valueMax()) val = this._valueMax();
+
+ return val;
+ } else {
+ return this.options.values;
+ }
+
+ },
+
+ _valueMin: function() {
+ var valueMin = this.options.min;
+ return valueMin;
+ },
+
+ _valueMax: function() {
+ var valueMax = this.options.max;
+ return valueMax;
+ },
+
+ _refreshValue: function(animate) {
+
+ var oRange = this.options.range, o = this.options, self = this;
+
+ if (this.options.values && this.options.values.length) {
+ var vp0, vp1;
+ this.handles.each(function(i, j) {
+ var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100;
+ var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
+ $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);
+ if (self.options.range === true) {
+ if (self.orientation == 'horizontal') {
+ (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate);
+ (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
+ } else {
+ (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate);
+ (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
+ }
+ }
+ lastValPercent = valPercent;
+ });
+ } else {
+ var value = this.value(),
+ valueMin = this._valueMin(),
+ valueMax = this._valueMax(),
+ valPercent = valueMax != valueMin
+ ? (value - valueMin) / (valueMax - valueMin) * 100
+ : 0;
+ var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
+ this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);
+
+ (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate);
+ (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
+ (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate);
+ (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
+ }
+
+ },
+
+ _uiHash: function(index, value, values) {
+
+ var multiple = this.options.values && this.options.values.length;
+ return {
+ handle: this.handles[index],
+ value: value || (multiple ? this.values(index) : this.value()),
+ values: values || (multiple && this.values())
+ };
+
+ }
+
+}));
+
+$.extend($.ui.slider, {
+ getter: "value values",
+ version: "1.7",
+ eventPrefix: "slide",
+ defaults: {
+ animate: false,
+ delay: 0,
+ distance: 0,
+ max: 100,
+ min: 0,
+ orientation: 'horizontal',
+ range: false,
+ step: 1,
+ value: 0,
+ values: null
+ }
+});
+
+})(jQuery);
--- /dev/null
+#PHP IMAGE EDITOR TEXTS\r
+EDIT IMAGE=Edit Image\r
+RESIZE IMAGE=Resize Image\r
+WIDTH=Width\r
+HEIGHT=Height\r
+KEEP PROPORTIONS=Keep Proportions\r
+ROTATE IMAGE=Rotate Image\r
+LEFT 90 DEGREES=Left 90 Degrees\r
+RIGHT 90 DEGREES=Right 90 Degrees\r
+CROP IMAGE=Crop Image\r
+EFFECTS=Effects\r
+SELECT EFFECT=Select Effect\r
+SAVE AND CLOSE=Save and Close\r
+GRAYSCALE=Grayscale\r
+CONTRAST=Contrast\r
+BRIGHTNESS=Brightness \r
+DARKER=Darker\r
+IS REQUIRED=is required\r
+MUST BE NUMERIC=must be numeric\r
+NOT NEGATIVE=must be a positive number\r
+NOT IN RANGE=is not in valid range\r
+CANT BE LARGER THEN=can´t be larger then\r
+NO PROVIDED IMAGE=No image has been provided.\r
+IMAGE DOES NOT EXIST=The image doesn´t exist.\r
+INVALID IMAGE TYPE=Image must be of type jpeg, png or gif.\r
+OLD PHP VERSION=is too old php version. Minimum is:\r
+OLD GD VERSION=is too old GD version. Minimum is:\r
+UNDO=Undo\r
+UPDATE=Update\r
+LOADING=Loading\r
+AN UNEXPECTED ERROR=An unexpected error has occured, please try again...\r
+RESIZE HELP=Update Width and Height fields.<br/>Or drag and drop in the right or bottom side of the image.\r
+CROP HELP=Drag and drop to create a crop area on the image.\r
+CROP WIDTH=Crop Width\r
+CROP HEIGHT=Crop Height\r
+CROP KEEP PROPORTIONS=Keep Crop Proportions\r
+INSTRUCTIONS=Instructions
\ No newline at end of file
--- /dev/null
+<?php
+
+/**
+ * Page.php
+ *
+ * PHP version 5
+ *
+ * All rights reserved.
+ *
+ * @category Toolkit
+ * @package Page
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license http://demo.gaslightmedia.com Gaslight Media
+ * @version CVS: $Id: Page.php,v 1.80 2010/08/16 17:39:58 jamie Exp $
+ * @link http://demo.gaslightmedia.com
+ */
+/**
+ * Page for Error Doc
+ */
+define("ERROR_DOCUMENT", "404.html");
+
+/**
+ * The home page template
+ */
+define("HOME_TEMPLATE", "template.html");
+
+/**
+ * inside page template
+ */
+define("INSIDE_TEMPLATE", "template.html");
+
+/**
+ * Template for the error doc
+ */
+define("ERROR_DOCUMENT_TEMPLATE", "404-template.html");
+
+/**
+ * page title default
+ */
+define("PAGE_TITLE", SITENAME);
+
+/**
+ * Toolkit_Page
+ *
+ * A class Object for use with merging into the flexy template for output.
+ * Sets up the $page object used for merging with the flexy template
+ * to output the toolbox and members admin content
+ *
+ * @category Toolkit
+ * @package Page
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license http://demo.gaslightmedia.com Gaslight Media
+ * @link http://demo.gaslightmedia.com
+ */
+class Toolkit_Page
+{
+
+ /**
+ * used on img src and style href tags
+ * @var $baseURL
+ * @access public
+ */
+ public $mediaBaseURL;
+
+ /**
+ * used in href's
+ * @var $baseURL
+ * @access public
+ */
+ public $baseURLDefined;
+
+ /**
+ * meta tag description element
+ * @var $metaTags
+ * @access public
+ */
+ public $metaTags;
+
+ /**
+ * title tag node
+ * @var string
+ * @access public
+ */
+ public $pageTitle;
+
+ /**
+ * The main content of website
+ * @var $toolboxContent
+ * @access public
+ */
+ public $toolboxContent;
+ private $_breadCrumbs;
+ private $_toolboxPage;
+ private $_pageGateway;
+ private $_paragraphGateway;
+ private $_navigationFactory;
+ private $_keywordReplacement;
+ private $_catid;
+
+ /**
+ * Creates objects for class Page
+ *
+ * @param Toolkit_Template_Page $toolboxPage Toolbox Page
+ * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory BreadCrumbes
+ * @param Toolkit_Toolbox_GatewayFactoryAbstract $pageGatewayFactory Page Gateway
+ * @param Toolkit_Toolbox_GatewayFactoryAbstract $paragraphGatewayFactory Paragraph
+ * @param Toolkit_NavigationFactoryAbstract $navFactory Navigation
+ * @param Toolkit_Template_KeywordReplacement $keywordReplacement Keyword replacements
+ * @param type $catid catid
+ *
+ * @return void
+ */
+ public function __construct(
+ Toolkit_Template_Page $toolboxPage,
+ Toolkit_BreadCrumbsFactory $breadCrumbsFactory,
+ Toolkit_Toolbox_GatewayFactoryAbstract $pageGatewayFactory,
+ Toolkit_Toolbox_GatewayFactoryAbstract $paragraphGatewayFactory,
+ Toolkit_NavigationFactoryAbstract $navFactory,
+ Toolkit_Template_KeywordReplacement $keywordReplacement, $catid
+ ) {
+ $this->_toolboxPage = $toolboxPage;
+ $this->_breadCrumbs = $breadCrumbsFactory;
+ $this->_pageGateway = $pageGatewayFactory->createGateway();
+ $this->_paragraphGateway = $paragraphGatewayFactory->createGateway();
+ $this->_navigationFactory = $navFactory;
+ $this->_keywordReplacement = $keywordReplacement;
+ $this->_catid = $catid;
+
+ // determine the base url to use (for images and stylesheet urls)
+ $this->mediaBaseURL = MEDIA_BASE_URL;
+
+ $this->baseURLDefined = BASE_URL;
+
+ // determine the base url to use (for MEDIA_APP_BASE_URL)
+ $this->glmAppBaseURL = MEDIA_APP_BASE_URL;
+
+ $this->sitemapURL = $this->BaseURLDefined . 'site-map';
+
+ $this->homePageUrl
+ = ($_ENV['GLM_HOST_ID'] == 'PRODUCTION')
+ ? BASE_URL
+ : BASE_URL . 'index.php';
+
+ // Resources needed for every page.
+ $GLOBALS['styleSheets'] = array();
+ // Resources needed for every page.
+ $GLOBALS['topScripts'][] = JQUERY_CDN_JS;
+ }
+
+ private function _video()
+ {
+ //$GLOBALS['styleSheets'][]
+ // = GLM_APP_BASE_URL . 'gallery/colorbox/colorbox.css';
+ //$GLOBALS['bottomScripts'][]
+ // = GLM_APP_BASE_URL . 'libjs/plugins/colorbox/1.3.15/jquery.colorbox-min.js';
+ //$GLOBALS['bottomScripts'][]
+ // = BASE_URL . 'Toolkit/Videos/libjs/thickbox.js';
+ $GLOBALS['bottomScripts'][]
+ = BASE_URL . 'Toolkit/Videos/libjs/videos.js';
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT id
+ FROM videos
+ WHERE featured = true
+ AND active = true
+ ORDER BY pos
+ LIMIT 1
+ OFFSET 0";
+ $row = $dbh->query($sql)->fetch(PDO::FETCH_ASSOC);
+ if ($row) {
+ $video = new Toolkit_Videos_WebDecorator();
+ $this->video = $video->toHtml(
+ Toolkit_Database::getInstance(),
+ $this->_pageGateway
+ );
+ }
+ }
+
+ /**
+ * Add Banner module
+ *
+ * @param array $page toolbox page
+ *
+ * @return void
+ * @access public
+ */
+ public function banners(array $page)
+ {
+ $bannerConf = new Config;
+ $bannerRoot = & $bannerConf->parseConfig(
+ BASE . 'Toolkit/Banners/config.ini', 'IniFile'
+ );
+ $dbh = Toolkit_Database::getInstance();
+
+ // top banners
+ $banners = & Toolkit_Banners_BannersIterator::create('Bottom');
+ if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ $categoriesIterator = Toolkit_Members_CategoriesIterator::create();
+ $banners->fetchAllAvailable(
+ $dbh, $bannerRoot, $categoriesIterator, $page['id']
+ );
+ } else {
+ $banners->fetchAllAssignedToPage($dbh, $bannerRoot, $page['id']);
+ }
+
+ $availableBanners = $banners->getAvailable();
+
+ // Are there any banners even available
+ if (count($availableBanners)) {
+ $GLOBALS['bottomScripts'][]
+ = $this->glmAppBaseURL . 'libjs/banner-link.js';
+ $decoratorsTop = Toolkit_Banners_StaticBannersDecorator::create();
+ foreach ($availableBanners as $i) {
+ $decorator = Toolkit_Banners_HorizontalDecorator::create($i);
+ $decoratorsTop->add($decorator);
+ }
+
+ // application configuration
+ $conf = new Config;
+ $bannersRoot = & $conf->parseConfig(
+ BASE . 'Toolkit/Banners/config.ini', 'IniFile'
+ );
+
+ $this->hasBanner = count($decoratorsTop->getIterator());
+
+ if ($this->hasBanner) {
+
+ $mailerFactory = new Toolkit_Banners_MailerFactory(
+ $bannersRoot,
+ $GLOBALS['flexyOptions']
+ );
+
+ $notifier = new Toolkit_Banners_Notifier($mailerFactory, $dbh);
+
+ $this->bannerAds = $decoratorsTop->toHtml(
+ $dbh,
+ new Toolkit_Image_Server(),
+ $notifier,
+ $page['id'],
+ 'top'
+ );
+ }
+ }
+ // side banners
+ $banners = & Toolkit_Banners_BannersIterator::create('Side');
+ if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ $categoriesIterator = Toolkit_Members_CategoriesIterator::create();
+ $banners->fetchAllAvailable(
+ $dbh, $bannerRoot, $categoriesIterator, $page['id']
+ );
+ } else {
+ $banners->fetchAllAssignedToPage($dbh, $bannerRoot, $page['id']);
+ }
+
+ $availableSideBanners = $banners->getAvailable();
+
+ // Are there any banners even available
+ if (count($availableSideBanners)) {
+ $GLOBALS['bottomScripts'][]
+ = $this->glmAppBaseURL . 'libjs/banner-link.js';
+ $decoratorsSide = Toolkit_Banners_StaticBannersDecorator::create();
+ foreach ($availableSideBanners as $i) {
+ $decorator = Toolkit_Banners_VerticalDecorator::create($i);
+ $decoratorsSide->add($decorator);
+ }
+
+ // application configuration
+ $conf = new Config;
+ $bannersRoot = & $conf->parseConfig(
+ BASE . 'Toolkit/Banners/config.ini', 'IniFile'
+ );
+
+ $this->hasSideBanner = count($decoratorsSide->getIterator());
+ if ($this->hasSideBanner) {
+
+ $mailerFactory = new Toolkit_Banners_MailerFactory(
+ $bannersRoot,
+ $GLOBALS['flexyOptions']
+ );
+
+ $notifier = new Toolkit_Banners_Notifier($mailerFactory, $dbh);
+
+ $this->sideBannerAds = $decoratorsSide->toHtml(
+ $dbh,
+ new Toolkit_Image_Server(),
+ $notifier,
+ $page['id'],
+ 'side'
+ );
+ }
+ }
+ }
+
+ /**
+ * Create the error document page
+ *
+ * @return void
+ * @access public
+ */
+ function createErrorDocument()
+ {
+ $this->baseURL = MEDIA_BASE_URL;
+ $this->homeURL = $this->toolbox->get_seo_url(HOME_ID);
+ ;
+ // Initiate HTML_Template_Flexy.
+ $template = new HTML_Template_Flexy($GLOBALS['flexyOptions']);
+
+ // Create a template object for the 404 content part
+ $errorDocumentTemplate = new HTML_Template_Flexy($GLOBALS['flexyOptions']);
+ $errorDocumentTemplate->compile(ERROR_DOCUMENT_TEMPLATE);
+ $errorDocumentContents = $errorDocumentTemplate->bufferedOutputObject($this);
+
+ // set defaults
+ $this->toolboxContent = $errorDocumentContents;
+ $this->pageTitle = '404 Not Found - ' . PAGE_TITLE;
+ $this->hasHeadlines = false;
+ $this->hasAreaEvents = false;
+ $this->hasNews = false;
+ $this->sideNav = null;
+ $this->mainNav = $this->toolbox->get_main_nav();
+ $this->hasWeather = false;
+ $this->isHomePage = false;
+ $this->sitemapURL = false;
+
+ // compile the flexy template
+ $template->compile(INSIDE_TEMPLATE);
+
+ // Merge compiled template with the object.
+ $fileContents = $template->bufferedOutputObject($this);
+ file_put_contents(BASE . ERROR_DOCUMENT, $fileContents);
+ }
+
+ /**
+ * Add Event module
+ *
+ * @param Toolkit_Template_Page $toolboxPage page template
+ * @param Toolkit_Toolbox_GatewayAbstract $pageGateway page gateway
+ *
+ * @return void
+ * @access private
+ */
+ private function _events(
+ Toolkit_Template_Page $toolboxPage,
+ Toolkit_Toolbox_GatewayAbstract $pageGateway
+ ) {
+ if (defined('COMMON_EVENTS') && COMMON_EVENTS) {
+ if (!defined('COMMON_APP_BASE')) {
+ define('COMMON_APP_BASE', '/var/www/server/CommonApps/');
+ }
+ $this->events = array();
+ define('COMMON_EVENTS_SCHEMA', 'events');
+ require_once COMMON_APP_BASE . 'EventCalendar/V1/models/EventMapper.php';
+ $eventMapper = new EventMapper(Toolkit_Database::getInstance());
+
+ $events = $eventMapper->fetchFilteredEvents(
+ "slideshow is true"
+ );
+ if (is_array($events)) {
+ foreach ($events as $event) {
+ $this->events[] = array(
+ 'id' => $event->getId(),
+ 'href' => $event->getHref(),
+ 'bdate' => $event->getDates(),
+ 'header' => strip_tags($event->getHeader()),
+ 'descr' => substr(strip_tags($event->getDescription()), 0, 150),
+ 's-img' => (($event->getImage())
+ ? FILE_SERVER_URL . IS_OWNER_ID
+ . '/eventSlider/' . $event->getImage()
+ :''),
+ 't-img' => (($event->getImage())
+ ? FILE_SERVER_URL . IS_OWNER_ID
+ . '/eventFeaturedThumb/' . $event->getImage()
+ :''),
+ 'f-img' => (($event->getImage())
+ ? FILE_SERVER_URL . IS_OWNER_ID
+ . '/eventSlider/' . $event->getImage()
+ :''),
+ );
+ }
+ }
+ } else {
+ $events = new Toolkit_Events_HomeEvents(
+ Toolkit_Database::getInstance()
+ );
+ $this->events = $events->getHomeEvents();
+ }
+ $this->hasEvents = !empty($this->events);
+ $this->eventsUrl = Toolkit_Template_Page::getSeoUrl(
+ $pageGateway, EVENT_PAGE
+ );
+ }
+
+ /**
+ * Setup the page with all applications (banners home events navigation)
+ *
+ * @return void
+ */
+ public function fetchPage()
+ {
+ if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ // check to see if this page is a member only page
+ $memberOnlyPage = Toolkit_Template_Page::isMemberOnly(
+ $this->_pageGateway, $this->_catid
+ );
+ if ($memberOnlyPage
+ && !strpos($_SERVER['REQUEST_URI'], 'members-only-area')
+ ) {
+ header('Location: ' . $this->getToolboxUrl(MEMBERS_CATEGORY));
+ }
+ }
+ $this->pageTitle = $this->_getPageTitle($this->_catid);
+
+ $bodyFactory = new Toolkit_Template_Page_BodyFactory(
+ $this->_breadCrumbs,
+ $this->_pageGateway,
+ $this->_paragraphGateway,
+ $this->_keywordReplacement,
+ new Cache_Lite($GLOBALS['cacheOptions'])
+ );
+
+ $this->toolboxContent = $this->_toolboxPage->getBody(
+ $this->_catid, $bodyFactory
+ );
+ $page = $this->_pageGateway->find($this->_catid);
+ $this->topParentId = $this->_pageGateway->findTopParent($this->_catid);
+
+ // set the metaTags
+ if ($page['meta_description']) {
+ $this->metaTags
+ = htmlentities(
+ strip_tags($page['meta_description']), ENT_QUOTES, 'UTF-8'
+ );
+ } else {
+ $this->metaTags
+ = htmlentities(
+ substr(
+ trim(strip_tags($page['description'])), 0, 250
+ ), ENT_QUOTES, 'UTF-8'
+ );
+ }
+
+ if (filter_var($_REQUEST['sitemap'], FILTER_VALIDATE_INT)) {
+ $this->isHomePage = false;
+ } elseif (HOME_ID == $page['id']) {
+ $this->isHomePage = true;
+ } else {
+ $this->isHomePage = false;
+ }
+ if ($this->_catid != HOME_ID) {
+ $this->parentPageId = $this->_pageGateway->findTopParent($this->_catid);
+ $this->pageId = $this->_catid;
+ }
+ $this->_navigationFactory->setGateway($this->_pageGateway);
+ $this->mainNav = $this->_getMainNav($this->_catid);
+ $this->sideNav = $this->_getSideNav($this->_catid);
+
+ $this->newsletterAction = Toolkit_Template_Page::getSeoUrl(
+ $this->_pageGateway, 10
+ );
+
+ $this->tripPlannerCount = isset($_SESSION['wish_list'])
+ ? count($_SESSION['wish_list'])
+ : 0;
+ $this->tripPlannerUrl = Toolkit_Template_Page::getSeoUrl(
+ $this->_pageGateway, MEMBER_SESSION_PAGE
+ );
+
+ // check if define for GOOGLE_SEARCH is set
+ if (defined("GOOGLE_SEARCH")
+ && GOOGLE_SEARCH
+ && isset($_REQUEST['query'])
+ ) {
+ $this->_googleSearch();
+ }
+
+ if ( defined("VIDEOS")
+ && VIDEOS
+ && $this->_catid == HOME_ID
+ ) {
+ $this->_video();
+ }
+
+ // check if define for GLM_SEARCH is set
+ if (defined("GLM_SEARCH")
+ && GLM_SEARCH
+ ) {
+ $this->glmSearch = GLM_SEARCH;
+ $this->glmSearchSite = GLM_SEARCH_SITE;
+ $this->glmSearchLogin = GLM_SEARCH_LOGIN;
+ $this->glmSearchKey = GLM_SEARCH_KEY;
+
+ // Check if GLMSearch page called
+ if ($_REQUEST['GLMSearch'] == 'true') {
+ $this->isHomePage = false;
+ }
+ }
+
+ // check if define for HOME_EVENTS is set
+ if (defined("HOME_EVENTS")
+ && HOME_EVENTS
+ && !filter_var($_REQUEST[ 'sitemap'], FILTER_VALIDATE_INT)
+ && !isset($_REQUEST['query'])
+ && $this->isHomePage
+ ) {
+ $this->_events($this->_toolboxPage, $this->_pageGateway);
+ }
+
+ if ( defined("GLM_BLOCKS")
+ && GLM_BLOCKS
+ && !filter_var($_REQUEST[ 'sitemap'], FILTER_VALIDATE_INT)
+ && !isset($_REQUEST['query'])
+ ) {
+ $this->_getBlocks();
+ }
+
+ if ( defined("PRESS_DB")
+ && PRESS_DB
+ && $page['id'] == PRESS_PAGE_ID
+ ) {
+ $this->_getNewsPage();
+ }
+ // check if define for WEATHER is set
+ if (defined("WEATHER") && WEATHER) {
+ $this->hasWeather = true;
+ $this->_weather();
+ }
+
+ // check if define for BANNERS is set
+ if (defined("BANNERS") && BANNERS && is_array($page)) {
+ $this->banners($page);
+ }
+
+ if (defined("ROTATING_IMAGES")
+ && ROTATING_IMAGES
+ && !filter_var($_REQUEST['sitemap'], FILTER_VALIDATE_INT)
+ && !isset($_REQUEST['query'])
+ ) {
+ $this->_rotatingImages();
+ }
+
+ if (defined('SEASONS') && SEASONS) {
+ $this->_seasons();
+ }
+
+ if (defined("VIDEOS")
+ && VIDEOS
+ && !filter_var($_REQUEST[ 'sitemap'], FILTER_VALIDATE_INT)
+ && !isset($_GET['query'])
+ && in_array($page['id'], array(HOME_ID))
+ ) {
+ $this->_getFeaturedVideo();
+ }
+
+ }
+
+ /**
+ * Returns page main navigation
+ *
+ * @param type $catid page catid
+ *
+ * @return type
+ */
+ private function _getMainNav($catid)
+ {
+ $nav = $this->_navigationFactory->createMainNav();
+ $mainNavArray = $nav->getNavStructure($this->_pageGateway, $catid);
+
+ return $nav->renderPageNav($mainNavArray, 'tree');
+ }
+
+ /**
+ * Returns page title
+ *
+ * @param type $id page id
+ *
+ * @return string
+ */
+ private function _getPageTitle($id)
+ {
+ if (filter_input(INPUT_GET, 'member_id', FILTER_VALIDATE_INT)) {
+ // Member profile pages can't have search page title tags
+ return SITENAME;
+ }
+
+ $page = $this->_pageGateway->find($id);
+
+ if (!empty($page['meta_title'])) {
+ $title = $page['meta_title'];
+ } elseif (!empty($page['title'])) {
+ $title = $page['title'];
+ } elseif (!empty($page['navigation_name'])) {
+ $title = $page['navigation_name'];
+ }
+
+ $title = strip_tags($title);
+
+ $title = isset($title)
+ ? htmlentities("$title - ", ENT_QUOTES, 'UTF-8') . SITENAME
+ : SITENAME;
+
+ return $title;
+ }
+
+ /**
+ * Returns side navigation
+ *
+ * @param type $catid page catid
+ *
+ * @return type
+ */
+ private function _getSideNav($catid)
+ {
+ if ($catid == HOME_ID) {
+ return;
+ } else {
+ // side nav
+ $nav
+ = $this->_navigationFactory->createSideNav($this->_pageGateway);
+ $sideNavArray = $nav->getNavStructure(
+ $this->_pageGateway, $catid
+ );
+ return (!empty($sideNavArray))
+ ? $nav->renderPageNav($sideNavArray, 'tree')
+ : '';
+ }
+ }
+
+ /**
+ * Add Google Search module
+ *
+ * @return void
+ * @access private
+ */
+ private function _googleSearch()
+ {
+ $this->gSearchOn = false;
+ $this->isHomePage = false;
+ if (isset($_REQUEST['query']) && $_REQUEST['query']) {
+ $this->gSearchOn = true;
+ $query = urlencode($_REQUEST['query']);
+ $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'css/gsearch.css';
+ $GLOBALS['bottomScripts'][]
+ = 'http://www.google.com/uds/api?file=uds.js&v=1.0&key=' .
+ GSEARCH_API;
+ $GLOBALS['bottomScripts'][]
+ = $this->mediaBaseURL . 'js/gsearch.php?query=' . $query;
+ }
+ }
+
+ /**
+ * create code for conditional styles
+ *
+ * @return type
+ */
+ public function getConditionalStyles()
+ {
+ return '
+ <!--[if lte IE 7]>
+ <link rel="stylesheet" type="text/css" href="' . MEDIA_BASE_URL . 'css/ie7.css">
+ <![endif]-->';
+ }
+
+ /**
+ * grab the navigation name for the id
+ *
+ * @param integer $id id for pages table
+ *
+ * @return string page nav name
+ * @access public
+ */
+ function getToolboxName($id)
+ {
+ $page = $this->_pageGateway->find($id);
+ return $page['navigation_name'];
+ }
+
+ /**
+ * grab the navigation url for the id
+ *
+ * @param integer $id id for pages table
+ *
+ * @return string url
+ * @access public
+ */
+ public function getToolboxUrl($id)
+ {
+ return Toolkit_Template_Page::getSeoUrl($this->_pageGateway, $id);
+ }
+
+ /**
+ * grab the home page headlines
+ *
+ * @return void
+ * @access private
+ */
+ private function _headlines()
+ {
+ // get headlines aka 'Quick Links'
+ $this->headlines = $this->_pageGateway->getHomePageHeadlines();
+ // boolean for if toolbox has headlines
+ $this->hasHeadlines = !empty($this->headlines);
+ }
+
+ /**
+ * grab the GLM Blocks
+ *
+ * @return void
+ * @access private
+ */
+ private function _getBlocks()
+ {
+ $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+ if ($blockContent = $cache->get($this->_catid, 'Block')) {
+ $this->headlines = unserialize($blockContent);
+ } else {
+ $blocks = new Toolkit_Blocks_Display(
+ Toolkit_Database::getInstance()
+ );
+ $this->headlines
+ = $blocks->getPageBlocksAsArray((int)$this->_catid);
+ $cache->save(serialize($this->headlines), $this->_catid, 'Block');
+ }
+ $this->hasHeadlines = !empty($this->headlines);
+ }
+
+ /**
+ * Check if this page has photo gallery in it
+ *
+ * @return boolean If this page has a photo gallery assigned to it
+ * @access public
+ */
+ function isPhotoGalleryPage()
+ {
+ $sql = "
+ SELECT photocat_id
+ FROM photo_category_bus
+ WHERE buscat_id = {$this->toolbox->catid}";
+ if ($pData = $this->toolbox->DB->select($sql)) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * grab the home page newsletter/press info
+ *
+ * @param object $toolbox Toolbox object
+ *
+ * @return void
+ * @access public
+ */
+ public function news($toolbox)
+ {
+ if (HOME_ID == $toolbox->catid) {
+ $this->news = $toolbox->get_news();
+ $this->hasNews = (!empty($this->news));
+ } else {
+ $this->hasNews = false;
+ }
+ }
+
+ /**
+ * Sets toolboxContent with news
+ *
+ * @return void
+ */
+ private function _getNewsPage()
+ {
+ $dbh = Toolkit_Database::getInstance();
+ $press = new Toolkit_Press_Newsletter();
+ $this->toolboxContent = $press->toHtml($dbh);
+ }
+
+ /**
+ * Sets rotatingImages
+ *
+ * @return void
+ */
+ private function _rotatingImages()
+ {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT id
+ FROM rotatingimages.application
+ WHERE page = " . $this->_catid;
+ $appId = $dbh->query($sql)->fetchColumn();
+ if ($appId) {
+ define('SLIDESHOW_APP_ID', $appId);
+ } else {
+ return;
+ }
+ $gateway = new Toolkit_RotatingImages_Gateway(
+ Toolkit_Database::getInstance()
+ );
+ $nodesIterator = new Toolkit_RotatingImages_NodesIterator();
+ $images = $gateway->findAll();
+ foreach ($images as $image) {
+ $nodesIterator->addImage($image);
+ }
+ $is = new Toolkit_FileServer_ImageAdapter();
+ $decorator = new Toolkit_RotatingImages_Decorator_User();
+ foreach ($nodesIterator as $v) {
+ if ($v->getActive()) {
+ $imgDecorator = new Toolkit_RotatingImages_Decorator_Image($v);
+ if ($v->isAnchor()) {
+ $imgDecorator = new Toolkit_RotatingImages_Decorator_Anchor(
+ $imgDecorator,
+ $v
+ );
+ }
+ $decorator->add($imgDecorator);
+ }
+ }
+ $this->rotatingImages = $decorator->toHtml($is);
+ }
+
+ /**
+ * Add Weather module
+ *
+ * @return void
+ * @access private
+ */
+ private function _weather()
+ {
+ $weather = new Toolkit_Weather();
+ if (PEAR::isError($weather->currentCond)) {
+ return false;
+ }
+
+ $this->weather = $weather->currentCond['weather'];
+ $this->tempF = $weather->currentCond['temp_f'];
+ $this->location = $weather->currentCond['location'];
+ $this->iconUrlName
+ = ($weather->currentCond['icon_url_name'])
+ ? $weather->currentCond['icon_url_name']
+ : 'na.png';
+
+ $iconUrl
+ = ($_SERVER['HTTPS'] == 'on')
+ ? 'https://app.gaslightmedia.com/weather/'
+ : 'http://app.gaslightmedia.com/weather/';
+ $this->fullIconUrl = $iconUrl . $this->iconUrlName;
+ }
+
+ private function _seasons()
+ {
+ $seasonMapper = new Toolkit_Seasons_Season();
+ $season = $seasonMapper->fetchById(
+ Toolkit_Database::getInstance(),
+ 1
+ );
+ $GLOBALS['styleSheets'][] = $this->mediaBaseURL . 'css/' .
+ $season->getName() . '.css?_=' . strtotime($season->getLast_update());
+ }
+
+ /**
+ * Sets the video url for the embed video if not found then set as empty
+ *
+ * @return void
+ */
+ private function _getFeaturedVideo()
+ {
+ try {
+ $dbh = Toolkit_Database::getInstance();
+ $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) {
+ $videoMapper = new Toolkit_Videos_VideoMapper($dbh);
+ $video = $videoMapper->getVideoById($row['id'], false);
+ $this->featuredVideoCode
+ = ($video)
+ ? $video->getVideoCode()
+ : '';
+ }
+ } catch(PDOException $e) {
+ Toolkit_Common::handle_error($e);
+ }
+ }
+}
--- /dev/null
+<?php
+
+/**
+ * Variable Registry
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit
+ * @package Registry
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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];
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * Router.php
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit
+ * @package Router
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * ShortURL.php
+ *
+ * Integration of Toolbox with creation of ShortURL
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Toolkit_ShortURL
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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');
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * SiteMap.php
+ *
+ * PHP versions 4 and 5
+ *
+ * @category Toolkit
+ * @package Toolkit_SiteMap
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license Gaslight Media
+ * @link <>
+ */
+class Toolkit_SiteMap
+{
+ // {{{ Properties
+ /**
+ * Description of $beginLevel
+ * @var string
+ * @access public
+ */
+ var $beginLevel = "<ul>";
+
+ /**
+ * Description of $endLevel
+ * @var string
+ * @access public
+ */
+ var $endLevel = "</ul>";
+
+ /**
+ * Description of $beginItem
+ * @var string
+ * @access public
+ */
+ var $beginItem = "<li>";
+
+ /**
+ * Description of $endItem
+ * @var string
+ * @access public
+ */
+ var $endItem = "</li>";
+
+ /**
+ * 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 .= '<a href="'.$page.'">';
+ $this->wholeThread .= $value["category"]
+ . "</a>";
+ if ($threads[$parent]) {
+ ++$level_counter;
+ $this->convertToThread($threads, $threads[$parent]);
+ --$level_counter;
+ }
+ $this->wholeThread .= $this->endItem ."\n";
+ }
+ $this->wholeThread .= $this->endLevel;
+ return $this->wholeThread;
+ }
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * SiteMapXml.php
+ *
+ * PHP Version 5.2
+ *
+ * @category Toolkit
+ * @package Toolkit
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license Gaslight Media
+ * @version SVN: $id$
+ * @link <>
+ */
+
+/**
+ * Toolkit_SiteMapXml
+ *
+ * Description of Toolkit_SiteMapXml
+ *
+ * @category Toolkit
+ * @package Toolkit
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 = '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
+ . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'
+ . "\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><loc>' . $url . "</loc></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 .= '<url><loc>' . $murl
+ . "</loc></url>\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 .= "</urlset>\r\n";
+ return $xml;
+ }
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Creates a sortform to be used w/ datagrid DataGrids
+ *
+ * PHP version 5
+ *
+ * @category HTML
+ * @package Toolkit_SortForm
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * Table.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Table
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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);
+ }
+ }
+}
--- /dev/null
+<?php
+/**
+ * BreadCrumbs.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<a href="'.$seoUrl.'">'.$page['navigation_name'].'</a>';
+ array_unshift($stack, $anchor);
+ }
+
+ if ($id != HOME_ID) {
+ $page = $this->pageGateway->findNavItem($id);
+ if ($hasPhotoGalleriesOnThisPage) {
+ // Do Nothing
+ } else {
+ array_unshift($stack, $page['navigation_name']);
+ }
+ $parent = $page['parent'];
+ while ($parent != 0) {
+ $page = $this->pageGateway->findNavItem($parent);
+ $seoUrl = Toolkit_Template_Page::getSeoUrl(
+ $this->pageGateway,
+ $parent
+ );
+ $anchor = '<a href="'.$seoUrl.'">'.$page['navigation_name'].'</a>';
+ array_unshift($stack, $anchor);
+ $parent = $page['parent'];
+ }
+
+ $anchor = '<a href="' . BASE_URL . 'index.php">Home</a>';
+ array_unshift($stack, $anchor);
+ }
+
+ return $stack;
+ }
+
+ // }}}
+ // {{{ 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)
+ ? '<div id="breadcrumbs" class="opensearchserver.ignore">' . $breadCrumbs . '</div>'
+ : '';
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * Exception.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<a href="'.$seoUrl.'">'.$page['navigation_name'].'</a>';
+ array_unshift($stack, $anchor);
+ $parent = $page['parent'];
+ }
+
+ $anchor = '<a href="' . BASE_URL . 'index.php">Home</a>';
+ array_unshift($stack, $anchor);
+
+ return $stack;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * DraftController.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * Exception.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license Gaslight Media
+ * @release Release: $id$
+ * @link <>
+ */
+class Toolkit_Template_Exception extends Exception {}
+?>
--- /dev/null
+<?php
+/**
+ * Factory.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Image
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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();
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * Page Image Element
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+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 src="%s" title="%s" alt="%s">';
+ $img = sprintf(
+ $format,
+ $size . $this->_src,
+ $this->_caption,
+ $this->_src
+ );
+
+ return $img;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * Page Image
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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 = '<div class="imageleft" style="width: ' . $imageData[0] . 'px;">';
+ $html .= parent::getImage($size);
+ if (!empty($this->_caption)) {
+ $html .= '<div class="imagecaption">';
+ $html .= $this->_caption;
+ $html .= '</div>';
+ }
+ $html .= '</div>';
+
+ return $html;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * Coupon Image Element
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * Page Image
+ *
+ * PHP version 5
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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 = '<div class="imageright" style="width: ' . $imageData[0] . 'px;">';
+ $html .= parent::getImage($size);
+ if (!empty($this->_caption)) {
+ $html .= '<div class="imagecaption">';
+ $html .= $this->_caption;
+ $html .= '</div>';
+ }
+ $html .= '</div>';
+
+ return $html;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * IndexController.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * KeywordReplacement.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<a href="'.$seoUrl.'">'.$page['navigation_name'].'</a>';
+ $haystack = str_replace($needle[0], $anchor, $haystack);
+ }
+ } else {
+ return $haystack;
+ }
+
+ if (strstr($haystack, '{') !== false) {
+ return $this->findAndReplace($haystack);
+ }
+ }
+
+ return $haystack;
+ }
+}
+?>
--- /dev/null
+<?php
+
+/**
+ * AllInOneSideNav.php
+ *
+ * PHP version 5.3
+ *
+ * @category Toolkit
+ * @package Package
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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);
+ }
+ }
+}
+
--- /dev/null
+<?php
+/**
+ * Factory.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Navigation
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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'
+ )
+ );
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * MainNavigationAbstract.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Navigation
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<a href="%s" %s>{Title}</a>';
+ $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() {}
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * MainNavigationAllInOne.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Navigation
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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);
+ }
+ }
+}
--- /dev/null
+<?php
+/**
+ * MainNavigationDynamic.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Navigation
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * MainNavigationStatic.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Navigation
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Renderer to create a LI list that has an id on the last element
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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
+ );
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Renderer to create a LI list that has an id on the last element
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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
+ );
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Render the side nav w/ the top parent as a header above the nav
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit
+ * @package Toolkit_Template
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @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 <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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)
+ ? "<a href=\"{$link}\">{$page['navigation_name']}</a>"
+ : "{$page['navigation_name']}";
+ $this->_html = "<h2>{$title}</h2>" . $this->_html;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Renderer to create a LI list that has an id on the last element
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+class Toolkit_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
+ );
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+/**
+ * SideNavigation.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Navigation
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<a href="%s" %s>{Title}</a>';
+ $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;
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+/**
+ * Page.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+ }/*}}}*/
+}
--- /dev/null
+<?php
+/**
+ * Bad.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 '<h1>Sorry this page is down!</h1>';
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * BodyFactory.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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)
+ {
+ $memberId = filter_var($_REQUEST['member_id'], FILTER_VALIDATE_INT);
+ $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);
+ if ($pageDoesNotExist && $memberId) {
+ $pageDoesNotExist = 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']
+ || $memberId
+ );
+
+ 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
+ );
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+/**
+ * Abstract base class for file links
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version CVS: $Id:$
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+
+/**
+ * Abstract base class for file links
+ *
+ * Long description (if any) ...
+ *
+ * @category Toolkit_Template
+ * @package Template
+ * @author Jamie Kahgee <jamie@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license http://www.gaslightmedia.com/ Gaslightmedia
+ * @version Release: @package_version@
+ * @link <>
+ * @see References to other sections (if any)...
+ */
+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 = '<div><a class="file-download %s" href="%s">%s</a></div>';
+
+ /**
+ * 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();
+
+ // }}}
+}
--- /dev/null
+<?php
+/**
+ * Factory.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page/FileLink
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+}
--- /dev/null
+<?php
+/**
+ * File.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page/FileLink
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+/**
+ * Image.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page/FileLink
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+/**
+ * GLMSearch.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Chuck Scott <cscott@gaslightmedia.com>
+ * @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 <cscott@gaslightmedia.com>
+ * @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;
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * GoogleSearch.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 '<div id="searchcontrol"></div>';
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * IBody.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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();
+}
+?>
--- /dev/null
+<?php
+/**
+ * Member.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<a href="#">' . $lastNode . '</a>';
+ 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;
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+/**
+ * SiteMap.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 . "memberProfiles/"
+ . 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;
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * Toolbox.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template/Page
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<ul id="paragraphLinks">';
+ foreach ($this->paragraphLinks as $anchor) {
+ $links .= "<li>$anchor</li>";
+ }
+ $links .= '</ul>';
+
+ 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 = '<div id="category">';
+ $html .= "<h1>{$page['title']}</h1>";
+ if ($page['paragraph_links']) {
+ $html .= $this->getParagraphLinks();
+ }
+ $html .= $this->getParagraphImage($page, $side);
+ $html .= $this->keywordReplacement->findAndReplace($page['description']);
+ $html .= '</div>';
+
+ $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 = '<a href="#sect-%s">%s</a>';
+ foreach ($paragraphs as $paragraph) {
+ if ($paragraph['active']) {
+ $html .= '<div class="listing" id="sect-'.$paragraph['id'].'">';
+ $html .= "<h2>{$paragraph['title']}</h2>";
+ $html .= $this->getParagraphImage($paragraph, $side[$key]);
+ $html .= $this->keywordReplacement->findAndReplace($paragraph['description']);
+
+ $html .= $this->getParagraphFiles($paragraph['files']);
+
+ if ($paragraph['back_to_top']) {
+ $html .= '<a href="#toolbox">Back to Top</a>';
+ }
+
+ $html .= '</div>';
+
+ $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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * PageControllerAbstract.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Template
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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'
+ );
+ $memberName = str_replace(' ', '-', $memberName);
+ $pattern = '/[\/#&?\'"]|amp;/';
+ $name = preg_replace(
+ $pattern,
+ '',
+ strip_tags(strtolower(trim($memberName)))
+ );
+ $glmPage->canonicalUrl = BASE_URL . "memberProfiles/"
+ . htmlspecialchars($name) . "-{$memberId}.html";
+ }
+ }
+
+ $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);
+ }
+}
+?>
--- /dev/null
+<?php
+
+abstract class Toolkit_Toolbox_BreadCrumbsAbstract
+{
+ // {{{ properties
+
+ protected $dbh;
+ protected $id;
+ protected $path;
+
+ // }}}
+ // {{{ __construct()
+
+ public function __construct(PDO $dbh, $id)
+ {
+ $this->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 '<div id="breadcrumbs">' . $this->getPath() . '</div>';
+ }
+
+ // }}}
+ // {{{ 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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+--
+-- 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
--- /dev/null
+--
+-- 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
--- /dev/null
+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
+--
--- /dev/null
+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', '<p>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.</p>
+<p> 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. </p>
+<p> 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.</p>', '', '', 1, 1);
+INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Paragraph A', '<p>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.</p>', '', '', TRUE, 1, 1);
+INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Paragraph B', '<p>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.</p>', '', '', TRUE, 1, 1);
+INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Paragraph C', '<p>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.</p>', '', '', TRUE, 1, 1);
+INSERT INTO toolbox.paragraphs(active, title, description, image, caption, page, pos) VALUES(TRUE, 'Parent Title', '<p>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.</p>', '', '', 2, 1);
+INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Parent Paragraph A', '<p>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.</p>', '', '', TRUE, 2, 1);
+INSERT INTO toolbox.paragraphs(active, title, description, image, caption, back_to_top, page, pos) VALUES(TRUE, 'Parent Paragraph B', '<p>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.</p>', '', '', 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);
--- /dev/null
+--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();
--- /dev/null
+--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();
--- /dev/null
+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;
--- /dev/null
+--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();
--- /dev/null
+--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();
--- /dev/null
+--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();
--- /dev/null
+--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();
--- /dev/null
+--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();
--- /dev/null
+--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();
--- /dev/null
+--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();
--- /dev/null
+--
+-- 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;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+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);
--- /dev/null
+CREATE TEMPORARY TABLE toolbox.pages_preview
+(LIKE toolbox.pages
+ INCLUDING DEFAULTS,
+ PRIMARY KEY (id)
+);
+
+GRANT ALL ON toolbox.pages_preview TO nobody;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+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;
--- /dev/null
+CREATE TEMPORARY TABLE toolbox.paragraphs_preview
+(LIKE toolbox.paragraphs
+ INCLUDING DEFAULTS
+);
+
+GRANT ALL ON toolbox.paragraphs_preview TO nobody;
--- /dev/null
+<?php
+class Toolkit_Toolbox_DraftPagesTree extends Toolkit_Toolbox_PagesTree
+{
+ // {{{ createTree()
+
+ protected function createTree(array $tree, $leaf, $level = 0)
+ {
+ $html = !$level ? $this->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 .= "<strong>{$branch['navigation_name']}</strong>";
+
+ $html .= '<div class="right-element">';
+
+ $html .= '<a href="'.MEDIA_BASE_URL.'admin/toolbox.php?rt=EditDraft&id='.$branch['id'].'" class="editPage">[Edit]</a> ';
+ $html .= '<a href="'.MEDIA_BASE_URL.'admin/toolbox.php?rt=ParagraphsDraft&pageid='.$branch['id'].'" class="editParagraphs">[Paragraphs]</a> ';
+ $html .= '<a href="'.$previewUrl.'" class="pagePreview">[Preview]</a> ';
+ $html .= $this->getActiveBall($branch);
+
+ $html .= '</div>';
+
+ $html .= $this->leafEnd;
+ }
+ }
+ }
+
+ $html .= $this->treeEnd;
+ if ($level) {
+ $html .= $this->leafEnd;
+ }
+
+ return $html;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_EditDraftController
+ extends Toolkit_Toolbox_FormControllerAbstract
+{
+ // {{{ cancel()
+
+ protected function cancel()
+ {
+ header('Location: ' . MEDIA_BASE_URL . 'admin/toolbox.php?rt=EditDraft');
+ exit();
+ }
+
+ // }}}
+
+ // {{{ delete()
+
+ protected function delete($id)
+ {
+ $gateway = new Toolkit_Toolbox_PageGatewayDraft($this->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;
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_EditPageController
+ extends Toolkit_Toolbox_FormControllerAbstract
+{
+ // {{{ cancel()
+
+ protected function cancel()
+ {
+ header('Location: ' . MEDIA_BASE_URL . 'admin/toolbox.php');
+ exit();
+ }
+
+ // }}}
+
+ // {{{ delete ()
+
+ protected function delete($id)
+ {
+ $gateway = new Toolkit_Toolbox_PageGatewayPublish($this->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;
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+class Toolkit_Toolbox_Exception extends Exception {}
+?>
--- /dev/null
+<?php
+/**
+ * FileExtension.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Toolbox
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link <>
+ */
+
+/**
+ * Toolkit_Toolbox_FileExtension
+ *
+ * Description for Toolkit_Toolbox_FileExtension
+ *
+ * @category Toolkit
+ * @package Toolbox
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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);
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+abstract class Toolkit_Toolbox_FormControllerAbstract
+ extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+ // {{{ getForm()
+
+ protected function getForm(
+ $controller,
+ Toolkit_Toolbox_GatewayFactoryAbstract $factory
+ ) {
+ // Need three separate objects otherwise,
+ // new parses overwrite existing root variable data.
+
+ if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ $memConf = new Config;
+ $memRoot =& $memConf->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 = "[<b>$navTitle</b>] successfully deleted.";
+ } else {
+ $return = $form->getErrorMessage();
+ $return .= $form->toHtml();
+ }
+ } else {
+ $return = $form->toHtml();
+ }
+
+ return $return;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Toolbox page edit form
+ *
+ * PHP version 5
+ *
+ * @category Toolbox
+ * @package Toolkit_Toolbox
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @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 = "<img src=\"".MEDIA_BASE_URL.'Toolkit/Toolbox/assets/'."template$i.gif\" alt=\"page template $i\">";
+
+ $templates[] = array(
+ 'type' => 'radio',
+ 'req' => false,
+ 'name' => 'template',
+ 'att' => $i,
+ 'opts' => "Template $i<br>$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' => '</tbody>',
+ );
+ $e[] = array(
+ 'type' => 'html',
+ 'req' => false,
+ 'name' => '<tbody id="attributes" class="section">',
+ );
+ $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.<br>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' => '</tbody>',
+ );
+ $e[] = array(
+ 'type' => 'html',
+ 'req' => false,
+ 'name' => '<tbody id="members" class="section">',
+ );
+ $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' => '<tr>
+ <td class="labelcell"></td>
+ <td class="fieldcell">
+ To include all members, turn this feature on and
+ don\'t select categories or regions below.<br>
+ To restrict to specific categories, select desired
+ categories under Category Filter.<br>
+ To restrict to specific regions, select desired
+ regions under Region Filter.
+ </td>
+ </tr>'
+ );
+ // 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<br>(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<br>(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' => '</tbody>',
+ );
+ $e[] = array(
+ 'type' => 'html',
+ 'req' => false,
+ 'name' => '<tbody id="coupons" class="section">',
+ );
+ $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' => '<tr>
+ <td class="labelcell"></td>
+ <td class="fieldcell">
+ To include all coupons, turn this feature on and
+ don\'t select categories below.<br>
+ To restrict to specific categories, select desired
+ categories under Categories Filter.
+ </td>
+ </tr>'
+ );
+ // 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<br>(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' => '</tbody>',
+ );
+ $e[] = array(
+ 'type' => 'html',
+ 'req' => false,
+ 'name' => '<tbody id="headlines" class="section">',
+ );
+ $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' => '</tbody>',
+ );
+ if ($_SERVER['PHP_AUTH_USER'] == 'MediaAdmin' || DEVELOPMENT) {
+ $e[] = array(
+ 'type' => 'html',
+ 'req' => false,
+ 'name' => '<tbody id="metadata" class="section">',
+ );
+ $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' => '</tbody>',
+ );
+ } 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' => '<tbody id="template" class="section">',
+ );
+ $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' => '</tbody>',
+ );
+ if (isset($_GET['id']) && ctype_digit($_GET['id'])) {
+ $e[] = array(
+ 'type' => 'html',
+ 'req' => false,
+ 'name' => '<tbody id="data" class="section">',
+ );
+ $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' => '</tbody>',
+ );
+ }
+ $e[] = array(
+ 'type' => 'html',
+ 'req' => false,
+ 'name' => '<tbody>',
+ );
+
+ // 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 = '<!-- BEGIN required -->';
+ $required .= '<span class="req"> * </span>';
+ $required .= '<!-- END required -->';
+
+ $error = '<!-- BEGIN error -->';
+ $error .= '<div class="req">{error}</div>';
+ $error .= '<!-- END error -->';
+
+ $baseUrl = MEDIA_BASE_URL;
+
+ $renderer->setFormTemplate(
+ "<div class=\"webform\">\n
+ <form{attributes}>\n
+ <div class=\"hiddenElements\">
+ {hidden}
+ </div>
+ {requiredNote}
+ <table>\n
+ <tbody id=\"pageContent\" class=\"section\"> {content} </tbody>\n
+ </table>\n
+ </form>\n
+ </div>"
+ );
+
+ $renderer->setElementTemplate(
+ "<tr>\n
+ <td class=\"labelcell\">$required{label}</td>\n
+ <td class=\"fieldcell\">{$error}{$baseUrl}{element}/</td>\n
+ </tr>\n",
+ 'short_url'
+ );
+ $renderer->setElementTemplate(
+ "<tr align=\"center\">\n
+ <td colspan=\"2\">$required{label}$error{element}</td>
+ </tr>",
+ 'description'
+ );
+ $renderer->setElementTemplate(
+ "<tr align=\"center\">\n
+ <td colspan=\"2\">$required{label}$error{element}</td>
+ </tr>",
+ 'submit_buttons'
+ );
+ $renderer->setElementTemplate(
+ "<tr align=\"center\">\n
+ <td colspan=\"2\">$required{label}$error{element}</td>\n
+ </tr>",
+ 'edit'
+ );
+
+ $renderer->setElementTemplate(
+ "<tr align=\"center\">\n
+ <td colspan=\"2\">$required{label}$error{element}</td>\n
+ </tr>\n",
+ 'page_layout'
+ );
+ $renderer->setGroupTemplate(
+ "<table id=\"templates\">\n
+ <tr>{content}</tr>\n
+ </table>\n",
+ 'page_layout'
+ );
+ $renderer->setGroupElementTemplate(
+ "<td>\n
+ {element}<br>{label}\n
+ </td>\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();
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+// vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Edit a page paragraph form
+ *
+ * PHP version 5
+ *
+ * @category Toolbox
+ * @package Toolkit_Toolbox
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @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 <jamie.kahgee@gmail.com>
+ * @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[] = '
+ <li id="pFile-'.$file['id'].'" class="ui-state-default">
+ <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
+ '.$fileLink.'
+ File Name:
+ <input type="text" size="35" name="uploaded_files[urltext][]" value="'.htmlspecialchars($file['urltext']).'"><br>
+ <label>
+ <input type="checkbox" name="deleteFile[]" value="'.htmlspecialchars($file['filename']).'">
+ Remove File
+ </label>
+ <input type="hidden" value="'.htmlspecialchars($file['filename']).'" name="uploaded_files[filename][]">
+ <input type="hidden" value="'.htmlspecialchars($file['bytes']).'" name="uploaded_files[bytes][]">
+ <input type="hidden" value="'.htmlspecialchars($file['type']).'" name="uploaded_files[type][]">
+ </li>';
+ }
+ $paragraph['uploaded_files'] = '<ul class="files">' . implode('', $files) . '</ul>';
+ }
+ } 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' => '<ul class="files"></ul>'
+ );
+
+ // 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 = '<!-- BEGIN required -->';
+ $required .= '<span class="req"> * </span>';
+ $required .= '<!-- END required -->';
+
+ $error = '<!-- BEGIN error -->';
+ $error .= '<div class="req">{error}</div>';
+ $error .= '<!-- END error -->';
+
+ $renderer->setElementTemplate(
+ "<tr align=\"center\">\n
+ <td colspan=\"2\">$required{label}$error{element}</td>
+ </tr>",
+ 'submit_buttons'
+ );
+ $renderer->setElementTemplate(
+ "<tr align=\"center\">\n
+ <td colspan=\"2\">$required{label}$error{element}</td>\n
+ </tr>",
+ 'insert'
+ );
+
+ $renderer->setElementTemplate(
+ "<tr align=\"center\">\n
+ <td colspan=\"2\">$required{label}$error{element}</td>
+ </tr>",
+ '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')
+ ? '<div class="form-success">Form Submit Successfull!</div>'
+ : '';
+
+ return $out . parent::toHtml();
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+class Toolkit_Toolbox_Forms_SearchForm
+ extends Toolkit_FormBuilder
+{
+ // {{{ properties
+
+ /**
+ * Don't need to register any rules for this form.
+ * @var array
+ * @access protected
+ */
+ protected $registeredRules = array();
+
+ // }}}
+
+ // {{{ configureConstants()
+
+ /**
+ * Form constant definitions
+ *
+ * @return void
+ * @access public
+ */
+ public function configureConstants()
+ {
+ $c = array('rt' => '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 = '<!-- BEGIN required -->';
+ $required .= '<span class="req"> * </span>';
+ $required .= '<!-- END required -->';
+
+ $error = '<!-- BEGIN error -->';
+ $error .= '<div class="req">{error}</div>';
+ $error .= '<!-- END error -->';
+
+ $renderer->setElementTemplate(
+ "<tr>\n
+ <td colspan=\"2\">$required{label}$error{element}</td>\n
+ </tr>\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();
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+abstract class Toolkit_Toolbox_GatewayAbstract
+{
+ // {{{ properties
+
+ protected $dbh;
+
+ // }}}
+ // {{{ __construct()
+
+ public function __construct(PDO $dbh)
+ {
+ $this->dbh = $dbh;
+ }
+
+ // }}}
+ // {{{ find()
+
+ abstract public function find($id);
+
+ // }}}
+ // {{{ update()
+
+ abstract public function update(array $data, $id);
+
+ // }}}
+ // {{{ insert()
+
+ abstract public function insert(array $data);
+
+ // }}}
+}
--- /dev/null
+<?php
+abstract class Toolkit_Toolbox_GatewayFactoryAbstract
+{
+ protected $dbh;
+
+ public function __construct(PDO $dbh)
+ {
+ $this->dbh = $dbh;
+ }
+
+ abstract public function createGateway();
+}
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_IndexController extends Toolkit_BaseControllerAbstract
+ implements Toolkit_IController
+{
+ // {{{ indexAction()
+
+ public function indexAction()
+ {
+ $searchForm = new Toolkit_Toolbox_Forms_SearchForm(
+ 'search_form',
+ 'get',
+ MEDIA_BASE_URL . 'admin/toolbox.php?rt=search',
+ null,
+ null,
+ true
+ );
+ $searchForm->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;
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_ListDraftsController
+ extends Toolkit_Toolbox_IndexController implements Toolkit_IController
+{
+ // {{{ indexAction()
+
+ public function indexAction()
+ {
+
+ $toolboxConfig = new Config;
+ $toolboxConfigRoot =& $toolboxConfig->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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_Navigation extends Toolkit_NavigationAbstract
+ implements Toolkit_INavigation
+{
+ // {{{ __construct()
+
+ public function __construct(
+ HTML_Menu $menu,
+ HTML_Menu_Renderer $rEngine
+ ) {
+ $this->menu = $menu;
+ $this->rEngine = $rEngine;
+ $this->currIndex = 'listToolbox';
+ }
+
+ // }}}
+ // {{{ setNavTemplates()
+
+ protected function setNavTemplates()
+ {
+ $tpl = '<li><a href="%s" title="%s">{Title}</a></li>';
+ $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('<ul class="admin_nav">', '</ul>');
+ }
+
+ // }}}
+ // {{{ 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
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_Page
+{
+ // {{{ properties
+ public $content;
+ public $members;
+ public $coupons;
+ public $attributes;
+ public $headlines;
+ public $metaData;
+
+ private $_createDate;
+ private $_lastModifiedDate;
+ private $_revisions;
+ private $_active;
+
+ // }}}
+
+ // {{{ __construct()
+ public function __construct(
+ Toolkit_Toolbox_ComponentFactory $cf,
+ array $data,
+ $id = null
+ ) {
+ if (!empty($id)) {
+ if (ctype_digit($id)) {
+ $this->_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;
+ }
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_PageBreadCrumbs
+ extends Toolkit_Toolbox_BreadCrumbsAbstract
+{
+ protected function getPageUri(array $page)
+ {
+ $uri = MEDIA_BASE_URL . "admin/toolbox.php?rt=EditPage&id={$page['id']}";
+ return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+ }
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_PageDraftBreadCrumbs
+ extends Toolkit_Toolbox_BreadCrumbsAbstract
+{
+ // {{{ getPageUri()
+
+ protected function getPageUri(array $page)
+ {
+ $uri = MEDIA_BASE_URL . "admin/toolbox.php?rt=EditPage&id={$page['id']}";
+ return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+ }
+
+ // }}}
+ // {{{ 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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+abstract class Toolkit_Toolbox_PageGatewayAbstract
+ extends Toolkit_Toolbox_GatewayAbstract
+{
+ protected $page;
+
+ // {{{ hasMemberDb()
+
+ protected function hasMemberDb()
+ {
+ return (defined('MEMBERS_DB') && MEMBERS_DB);
+ }
+
+ // }}}
+ // {{{ hasCouponDb()
+
+ protected function hasCouponDb()
+ {
+ return (defined('COUPONS') && COUPONS);
+ }
+
+ // }}}
+ // {{{ hasHeadlines()
+
+ protected function hasHeadlines()
+ {
+ return (defined('HOME_HEADLINES') && HOME_HEADLINES);
+ }
+
+ // }}}
+ // {{{ hasPhotoGallery()
+
+ protected function hasPhotoGallery()
+ {
+ return (defined('PHOTO_GALLERY') && PHOTO_GALLERY);
+ }
+
+ // }}}
+
+ // {{{ findAll()
+
+ abstract public function findAll();
+
+ // }}}
+ // {{{ findAllByParent()
+
+ public function findAllByParent($parent)
+ {
+ try {
+ $sql = "
+ SELECT id,navigation_name,parent,active
+ FROM pages
+ WHERE parent = :parent
+ ORDER by parent, pos";
+
+ $stmt = $this->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 = "<img alt=\"%s\" src=\"%s\">";
+ $page['current_image_original'] = sprintf(
+ $imgFormat,
+ $page['image'],
+ TOOLBOX_ORIGINAL . $page['image']
+ );
+ $page['current_image_resized'] = sprintf(
+ $imgFormat,
+ $page['image'],
+ TOOLBOX_RESIZED . $page['image']
+ );
+ $page['current_image_midsized'] = sprintf(
+ $imgFormat,
+ $page['image'],
+ TOOLBOX_MIDSIZED . $page['image']
+ );
+ $page['current_image_thumb'] = sprintf(
+ $imgFormat,
+ $page['image'],
+ TOOLBOX_THUMB . $page['image']
+ );
+ } else {
+ $page['current_image_original'] = 'Image not yet uploaded';
+ $page['current_image_resized'] = 'Image not yet uploaded';
+ $page['current_image_midsized'] = 'Image not yet uploaded';
+ $page['current_image_thumb'] = 'Image not yet uploaded';
+ }
+
+ $this->page = $page;
+ return $this->page;
+ }
+
+ // }}}
+
+ // {{{ getCurrentPage()
+
+ /**
+ * Gets the current page for the template if it exists
+ *
+ * @return mixed array of current page or false if no current page is set
+ * @access public
+ */
+ public function getCurrentPage()
+ {
+ return is_array($this->page) ? $this->page : false;
+ }
+
+ // }}}
+ // {{{ getHomePageHeadlines()
+
+ public function getHomePageHeadlines()
+ {
+ $wordCounter = array(
+ 1 => 'one',
+ 2 => 'two',
+ 3 => 'three',
+ 4 => 'four'
+ );
+ $headlines = array();
+ $sql = "
+ SELECT p1.id, p1.navigation_name, p1.headline_intro, p2.image
+ FROM pages p1 join paragraphs p2 on (p1.id = p2.page)
+ WHERE p1.headline = true
+ AND p1.active = true
+ AND p2.pos = 1
+ ORDER BY p1.parent, p1.pos";
+
+ $count = 1;
+ foreach ($this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) {
+ $headlines[] = array(
+ 'count' => $wordCounter[$count],
+ 'href' => Toolkit_Template_Page::getSeoUrl($this, $row['id']),
+ 'img' => ($row['image'])
+ ? HOMEPAGE_HEADLINE_THUMB . $row['image']
+ : '',
+ 'header' => $row['navigation_name'],
+ 'descr' => nl2br($row['headline_intro']),
+ );
+ if (++$count > 4) {
+ $count = 1;
+ }
+ }
+
+ return $headlines;
+ }
+
+ // }}}
+
+ // {{{ setPageVars()
+
+ protected function setPageVars(PDOStatement &$stmt, $data)
+ {
+ if ($this->hasHeadlines()) {
+ $data['headline'] = (bool)$data['headline'];
+ $stmt->bindParam(
+ ':headline',
+ $data['headline'],
+ PDO::PARAM_BOOL
+ );
+ $stmt->bindParam(':headline_intro', $data['headline_intro']);
+ }
+
+ if ($this->hasMemberDb()) {
+ $data['include_member_map'] = (bool)$data['include_member_map'];
+ $data['search_form'] = (bool)$data['search_form'];
+ $stmt->bindParam(
+ ':include_member_map',
+ $data['include_member_map'],
+ PDO::PARAM_BOOL
+ );
+ $stmt->bindParam(
+ ':search_form',
+ $data['search_form'],
+ PDO::PARAM_BOOL
+ );
+ }
+
+ $stmt->bindParam(':keyword', $data['keyword']);
+ $stmt->bindParam(':meta_title', $data['meta_title']);
+ $stmt->bindParam(':meta_description', $data['meta_description']);
+ $stmt->bindParam(':navigation_name', $data['navigation_name']);
+ $stmt->bindParam(':parent', $data['parent']);
+ $stmt->bindParam(':paragraph_links', $data['paragraph_links']);
+ $stmt->bindParam(':short_url', $data['short_url']);
+ $stmt->bindParam(':template', $data['template']);
+ $stmt->bindParam(':include_members', $data['include_members']);
+ $stmt->bindParam(':include_coupons', $data['include_coupons']);
+ }
+
+ // }}}
+ // {{{ setParagraphVars()
+
+ protected function setParagraphVars(PDOStatement &$stmt, $data)
+ {
+ if ($data['remove_image']) {
+ $data['image'] = '';
+ }
+ $stmt->bindParam(':title', $data['title']);
+ $stmt->bindParam(':description', $data['description']);
+ $stmt->bindParam(':image', $data['image']);
+ $stmt->bindParam(':caption', $data['caption']);
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+class Toolkit_Toolbox_PageGatewayDraft
+ extends Toolkit_Toolbox_PageGatewayAbstract
+{
+ // {{{ delete()
+
+ public function delete($id)
+ {
+ $pageSql = "
+ DELETE
+ FROM pages_draft
+ WHERE id = :id";
+
+ try {
+ $stmt = $this->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`"
+ );
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_PageGatewayDraftFactory
+ extends Toolkit_Toolbox_GatewayFactoryAbstract
+{
+ public function createGateway()
+ {
+ return new Toolkit_Toolbox_PageGatewayDraft($this->dbh);
+ }
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_PageGatewayPublish
+ extends Toolkit_Toolbox_PageGatewayAbstract
+{
+ // {{{ delete()
+
+ public function delete($id)
+ {
+ $pageSql = "SELECT delete_subtree(:id)";
+
+ $createTableSql = "
+ CREATE LOCAL TEMPORARY TABLE WorkingTable
+ (id INTEGER NOT NULL)
+ ON COMMIT DELETE ROWS";
+
+ try {
+
+ $this->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`"
+ );
+ }
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+class Toolkit_Toolbox_PageGatewayPublishFactory
+ extends Toolkit_Toolbox_GatewayFactoryAbstract
+{
+ public function createGateway()
+ {
+ return new Toolkit_Toolbox_PageGatewayPublish($this->dbh);
+ }
+}
--- /dev/null
+<?php
+class Toolkit_Toolbox_PagesTree extends Toolkit_Toolbox_TreeAbstract
+{
+ // {{{ properties
+
+ protected $rootNodeStart = "<ul id=\"toolbox\">\n";
+ protected $leafStart = "\n\t<li id=\"cat_%s\" %s>\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 '<a class="tOff"><img src="'.MEDIA_BASE_URL . 'Toolkit/Toolbox/assets/grnball.gif" alt="Active Ball"></a>';
+ }
+
+ $activeFormat = '<a class="active-ball" rel="%s" href="%s" title="%s">';
+ $activeFormat .= $this->getActiveBallImage($branch);
+ $activeFormat .= '</a>';
+
+ 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 '<a class="tOff"><img src="'.MEDIA_BASE_URL . 'Toolkit/Toolbox/assets/grnball.gif" alt="Active Ball"></a>';
+ }
+
+ $activeFormat = '<a class="mobile-active-ball" rel="%s" href="%s" title="%s">';
+ $activeFormat .= $this->getActiveMobileBallImage($branch);
+ $activeFormat .= '</a>';
+
+ 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 = '<img src="%s" class="tOff" alt="%s">';
+
+ $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 = '<img src="%s" alt="Move %s Arrow" class="move%s">';
+
+ $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 '<select style="'.$showOn.'" class="'.$addClass.'" name="pos'.$branch['id'].'" rel="'.$branch['pos'].'"></select>';
+ }
+ }/*}}}*/
+
+ // {{{ 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 .= '<div class="right-element">';
+
+ $html .= '<a href="'.MEDIA_BASE_URL.'admin/toolbox.php?rt=EditPage&id='.$branch['id'].'" class="editPage" title="Edit Page">Top
+Section </a> ';
+ $html .= '<a href="'.MEDIA_BASE_URL.'admin/toolbox.php?rt=Paragraphs&pageid='.$branch['id'].'" class="editParagraphs" title="Page
+Paragraphs">Paragraphs</a> ';
+ $html .= '<a href="'.$previewUrl.'" class="pagePreview" title="Preview Page">[Preview]</a> ';
+ if (!$lockMainNavPages) {
+ $html .= $this->getActiveBall($branch);
+ if (defined("MOBILE_SITE") && MOBILE_SITE) {
+ $html .= $this->getActiveMobileBall($branch);
+ }
+ $html .= $this->_getPositionSelect($branch);
+ }
+
+ $html .= '</div>';
+ $html .= "<strong>{$branch['navigation_name']}</strong>";
+
+ 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 "<div id=\"tree\">$html</div>";
+ }
+
+ // }}}
+}
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_ParagraphBreadCrumbs
+ extends Toolkit_Toolbox_BreadCrumbsAbstract
+{
+ // {{{ getPageUri()
+
+ protected function getPageUri(array $page)
+ {
+ // go to parent edit page form
+ $uri = MEDIA_BASE_URL . "admin/toolbox.php?rt=EditPage&id={$page['id']}";
+ return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+ }
+
+ // }}}
+ // {{{ 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[] = "<a href=\"{$uri}\">Paragraphs</a>";
+ }
+
+ $this->path = implode(' > ', $reverse);
+
+ return $this->path;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_ParagraphDraftBreadCrumbs
+ extends Toolkit_Toolbox_BreadCrumbsAbstract
+{
+ // {{{ getPageUri()
+
+ protected function getPageUri(array $page)
+ {
+ // go to parent paragraphs
+ $uri = MEDIA_BASE_URL . "admin/toolbox.php?rt=Paragraphs&pageid={$page['id']}";
+ // go to parent edit page form
+ $uri = MEDIA_BASE_URL . "admin/toolbox.php?rt=EditPage&id={$page['id']}";
+ return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+ }
+
+ // }}}
+ // {{{ 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("<a href=\"{$uri}\">Paragraphs</a>");
+ }
+
+ 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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+abstract class Toolkit_Toolbox_ParagraphGatewayAbstract
+ extends Toolkit_Toolbox_GatewayAbstract
+{
+ // {{{ findAll()
+
+ abstract public function findAll($page);
+
+ // }}}
+
+ // {{{ setParagraphVars()
+
+ protected function setParagraphVars(PDOStatement &$stmt, $data)
+ {
+ $data['active'] = (bool) $data['active'];
+ $data['back_to_top'] = (bool) $data['back_to_top'];
+ if ($data['remove_image']) {
+ $data['image'] = '';
+ }
+
+ $stmt->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);
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_ParagraphGatewayDraft
+ extends Toolkit_Toolbox_ParagraphGatewayAbstract
+{
+ // {{{ delete()
+
+ public function delete($id)
+ {
+ $pageSql = "
+ DELETE
+ FROM paragraphs_draft
+ WHERE id = :id";
+
+ try {
+ $stmt = $this->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 = "<img src=\"%s{$paragraph['image']}\">";
+ $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]"
+ );
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_ParagraphGatewayDraftFactory
+ extends Toolkit_Toolbox_GatewayFactoryAbstract
+{
+ public function createGateway()
+ {
+ return new Toolkit_Toolbox_ParagraphGatewayDraft($this->dbh);
+ }
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_ParagraphGatewayPublish
+ extends Toolkit_Toolbox_ParagraphGatewayAbstract
+{
+ // {{{ delete()
+
+ public function delete($id)
+ {
+ $pageSql = "
+ DELETE
+ FROM paragraphs
+ WHERE id = :id";
+
+ try {
+ $stmt = $this->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 = "<img src=\"%s{$paragraph['image']}\">";
+ $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 '<pre>'.print_r($data, true).'</pre>';
+ //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]"
+ );
+ }
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_ParagraphGatewayPublishFactory
+ extends Toolkit_Toolbox_GatewayFactoryAbstract
+{
+ public function createGateway()
+ {
+ return new Toolkit_Toolbox_ParagraphGatewayPublish($this->dbh);
+ }
+}
+?>
--- /dev/null
+<?php
+/**
+ * ParagraphsController.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Toolbox
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link <>
+ */
+
+/**
+ * Toolkit_Toolbox_ParagraphsController
+ *
+ * Description for Toolkit_Toolbox_ParagraphsController
+ *
+ * @category Toolkit
+ * @package Toolbox
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @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 = "[<b>$paragraphTitle</b>] 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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_ParagraphsDraftController
+ extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+ // {{{ _getForm()
+
+ 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=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 = "[<b>$paragraphTitle</b>] successfully deleted.";
+ }
+ } else {
+ $return = $form->toHtml();
+ }
+
+ return $return;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_ParagraphsDraftTree extends Toolkit_Toolbox_TreeAbstract
+{
+ // {{{ getActiveBall()
+
+ protected function getActiveBall(array $branch)
+ {
+ $activeFormat = '<a href="%s" title="%s">';
+ $activeFormat .= $this->getActiveBallImage($branch);
+ $activeFormat .= '</a>';
+
+ 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 '<h2>No paragraph drafts created for this page yet</h2>'; // page has no paragraphs
+ }
+
+ $html = $this->rootNodeStart;
+
+ while (list($parent, $branch) = each($leaf)) {
+ $html .= sprintf($this->leafStart, $branch['id'], null);
+
+ $html .= "<strong>{$branch['title']}</strong>";
+ $html .= '<div class="right-element">';
+ $html .= '<a href="'.MEDIA_BASE_URL.'admin/toolbox.php?rt=ParagraphsDraft&ac=edit&id='.$branch['id'].'&pageid='.$_GET['pageid'].'">[Edit]</a> ';
+ $html .= $this->getActiveBall($branch);
+ $html .= '</div>';
+ $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 "<div id=\"tree\">$html</div>";
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_ParagraphsTree extends Toolkit_Toolbox_TreeAbstract
+{
+ protected $leafStart = "\n\t<li id=\"cat_%s\" %s>\n";
+ // {{{ getActiveBall()
+
+ protected function getActiveBall(array $branch)
+ {
+ $activeFormat = '<a class="active-ball" rel="%s" href="%s" title="%s">';
+ $activeFormat .= $this->getActiveBallImage($branch);
+ $activeFormat .= '</a>';
+
+ return sprintf(
+ $activeFormat,
+ $branch['id'],
+ MEDIA_BASE_URL . "admin/toolbox.php?rt=Paragraphs&id={$branch['id']}",
+ $branch['active_alt']
+ );
+ }
+
+ // }}}
+ // {{{ _getMoveArrows()
+
+ private function _getMoveArrows()
+ {
+ $format = '<img src="%s" alt="Move %s Arrow" class="move%s">';
+
+ $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 '<select class="pos-select" name="pos'.$branch['id'].'" rel="'.$branch['pos'].'"></select>';
+ }/*}}}*/
+ // {{{ createTree()
+
+ protected function createTree(array $tree, $leaf, $level = 0)
+ {
+ if (empty($leaf)) {
+ return '<h2>No paragraphs created for this page yet</h2>'; // page has no paragraphs
+ }
+
+ $html = $this->rootNodeStart;
+
+ while (list($parent, $branch) = each($leaf)) {
+ $html .= sprintf($this->leafStart, $branch['id'], null);
+
+ $html .= '<div class="right-element paragraph-line">';
+ $html .= '<a class="editPage" href="'.MEDIA_BASE_URL.'admin/toolbox.php?rt=Paragraphs&ac=edit&id='.$branch['id'].'&pageid='.$_GET['pageid'].'">[Edit]</a> ';
+ $html .= $this->getActiveBall($branch);
+ if (count($leaf) > 1) {
+ $html .= $this->_getPositionSelect($branch);
+ }
+ $html .= "<strong>{$branch['title']}</strong>";
+ $html .= '</div>';
+
+ $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 "<div id=\"tree\">$html</div>";
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+
+class Toolkit_Toolbox_SearchController extends Toolkit_BaseControllerAbstract
+ implements Toolkit_IController
+{
+ // {{{ index()
+
+ public function indexAction()
+ {
+ $searchForm = new Toolkit_Toolbox_PageSearchForm(
+ 'search_form',
+ 'get',
+ MEDIA_BASE_URL . 'admin/toolbox.php?rt=search',
+ null,
+ null,
+ true
+ );
+ $searchForm->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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+class Toolkit_Toolbox_SearchTree extends Toolkit_Toolbox_PagesTree
+{
+ // {{{ getActiveBall()
+
+ protected function getActiveBall(array $branch)
+ {
+ $activeFormat = '<a href="%s" title="%s"><img src="%s" alt="%s"></a>';
+ $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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * TreeAbstract.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package Toolbox
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link <>
+ */
+
+/**
+ * Toolkit_Toolbox_TreeAbstract
+ *
+ * Description for Toolkit_Toolbox_TreeAbstract
+ *
+ * @category Toolkit
+ * @package Toolbox
+ * @author Jamie Kahgee <steve@gaslightmedia.com>
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @link <>
+ */
+abstract class Toolkit_Toolbox_TreeAbstract
+{
+ // {{{ properties
+
+
+ /**
+ * Description for $rootNodeStart
+ * @var string
+ * @access protected
+ */
+ protected $rootNodeStart = "<ul>\n";
+
+ /**
+ * Description for $subTreeStart
+ * @var string
+ * @access protected
+ */
+ protected $subTreeStart = "\n<ul>\n";
+
+ /**
+ * Description for $treeEnd
+ * @var string
+ * @access protected
+ */
+ protected $treeEnd = "\n</ul>\n";
+
+ /**
+ * Description for $leafStart
+ * @var string
+ * @access protected
+ */
+ protected $leafStart = "\n\t<li>\n";
+
+ /**
+ * Description for $leafEnd
+ * @var string
+ * @access protected
+ */
+ protected $leafEnd = "\n\t</li>\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 = '<img %s src="%s" alt="%s" border="0">';
+
+ $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 = '<img %s src="%s" alt="%s" border="0">';
+
+ $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;
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+[conf]
+applicationName = "Toolbox"
+lockMainNavPages = Off
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+$dbh->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 '<p style="color:white;background-color:red;">
+ Adding paragraph! PageId:'.$row['id'].'</p>';
+ } else {
+ echo '<p style="color:white;background-color:green;">
+ Good Page PageId:'.$row['id'].'</p>';
+ }
+ }
+ $dbh->commit();
+} catch(PDOException $e) {
+ die($e->getMessage());
+}
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+$dbh->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 '<p>fixing page positions</p>';
+ 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 '<p>fixing paragraphs positions</p>';
+ 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();
--- /dev/null
+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('<span class="'+element+'"></span>');
+ var $holder = container.find('.'+element),
+ $numSelected = target.find(':selected').length;
+ if ($numSelected) {
+ EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Categories');
+ }
+ target.change(function() {
+ var $numSelected = target.find(':selected').length;
+ EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Categories');
+ });
+ }
+ },// }}}
+ createRegionShortcutView: function(element, section, container)// {{{
+ {
+ var target = section.find('select[name="'+element+'[]"]');
+ if (target.length) {
+ container.append('<span class="'+element+'"></span>');
+ var $holder = container.find('.'+element),
+ $numSelected = target.find(':selected').length;
+ if ($numSelected) {
+ EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Regions');
+ }
+ target.change(function() {
+ var $numSelected = target.find(':selected').length;
+ EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Regions');
+ });
+ }
+ },// }}}
+ createCheckboxShortcutView: function(element, section, container, text)// {{{
+ {
+ var target = section.find('input[name='+element+']:checkbox');
+ if (target.length) {
+ container.append('<span class="'+element+'"></span>');
+ var $holder = container.find('.'+element),
+ $checked = target.is(':checked')
+ ? '<tt>[X]</tt>'
+ : '<tt>[ ]</tt>';
+ EditPage.updateText($holder, $checked + text);
+
+ target.change(function() {
+ var $checked = target.is(':checked')
+ ? '<tt>[X]</tt>'
+ : '<tt>[ ]</tt>';
+ EditPage.updateText($holder, $checked + text);
+ });
+ }
+ },// }}}
+ createTextShortcutView: function(element, section, container)// {{{
+ {
+ var target = section.find('input[name='+element+']');
+ if (target.length) {
+ container.append('<span class="'+element+'"></span>');
+ 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('<span class="attributes"></span>');
+
+ $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('<span class="attributes"></span>');
+
+ $attributes = $section.find('tr.hdr .attributes');
+
+ EditPage.createCheckboxShortcutView('headline', $section, $attributes, 'Headline');
+ },// }}}
+
+ pageAttributes: function()// {{{
+ {
+ var $section = $('#attributes');
+ $section.find('tr.hdr td')
+ .append('<span class="attributes"></span>');
+
+ $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('<span class="attributes"></span>');
+
+ $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);
--- /dev/null
+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('<span id="upload_notification" style="display: none;">Uploading</span>');
+ $('#filename').after('<span id="success_notification" style="display: none;"><span></span> Successfully uploaded</span>');
+ 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);
--- /dev/null
+var PagesTree =
+{
+ init: function()
+ {
+ PagesTree.updateMoveArrowVisibility();
+ $('.admin_nav')
+ .append('<li><a id="expand_all" href="#">Expand All</a></li>')
+ .append('<li><a id="collapse_all" href="#">Collapse All</a></li>')
+ .append('<li><a id="show_pos" href="#">Show Positions</a></li>')
+ .append('<li><a id="hide_pos" href="#">Hide Positions</a></li>')
+ ;
+
+ 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 = '<option value="'+i+'"';
+ if (selCount == i) {
+ html += ' selected="selected"';
+ }
+ html += '>'+i+'</option>';
+ $(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);
--- /dev/null
+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 = '<option value="'+realNum+'"';
+ if (selCount == realNum) {
+ html += ' selected="selected"';
+ }
+ html += '>'+ i +'</option>';
+ $(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);
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+//echo '<pre>'.print_r($_REQUEST, true).'</pre>';
+$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 '<pre>'.print_r($_REQUEST, true).'</pre>';
+ //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');
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+$someNewPos = 999;
+try {
+ $dbh->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);
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+
+if (!isset($_GET['kpass'])) {
+ return false;
+}
+if (!ctype_digit($_GET['catid'])) {
+ return false;
+}
+
+$dbh = Toolkit_Database::getInstance();
+
+try {
+ $sql = "
+ UPDATE pages
+ SET active = not active
+ WHERE id = :id";
+
+ $stmt = $dbh->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;
+}
+?>
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+
+if (!isset($_GET['kpass'])) {
+ return false;
+}
+if (!ctype_digit($_GET['catid'])) {
+ return false;
+}
+
+$dbh = Toolkit_Database::getInstance();
+try {
+ $sql = "
+ UPDATE pages
+ SET mobile_active = not mobile_active
+ WHERE id = :id";
+
+ $stmt = $dbh->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;
+}
+?>
--- /dev/null
+<?php
+if (!isset($_GET['kpass'])) {
+ die();
+}
+
+require_once '../../setup.phtml';
+
+$writer = new Zend_Log_Writer_Firebug();
+$logger = new Zend_Log($writer);
+
+$request = new Zend_Controller_Request_Http();
+$response = new Zend_Controller_Response_Http();
+$channel = Zend_Wildfire_Channel_HttpHeaders::getInstance();
+$channel->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();
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+
+if (!isset($_GET['kpass'])) {
+ return false;
+}
+if (!ctype_digit($_GET['paragraphId'])) {
+ return false;
+}
+
+$dbh = Toolkit_Database::getInstance();
+
+try {
+ $sql = "
+ UPDATE paragraphs
+ SET active = not active
+ WHERE id = :id";
+
+ $stmt = $dbh->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;
+}
+?>
--- /dev/null
+<?php
+require_once '../../setup.phtml';
+
+$fs = new Toolkit_FileServer_FileAdapter();
+try {
+ $res = $fs->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);
+?>
--- /dev/null
+<?php
+if (!isset($_GET['kpass'])) {
+ die();
+}
+
+require_once '../../setup.phtml';
+
+$dbh = Toolkit_Database::getInstance();
+
+extract($_GET);
+
+try {
+ $dbh->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`"
+ );
+}
+?>
--- /dev/null
+.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;}
--- /dev/null
+<?php
+/**
+ * HTML_QuickForm_CAPTCHA example - Image generator
+ *
+ * PHP versions 4 and 5
+ *
+ * @category HTML
+ * @package HTML_QuickForm_CAPTCHA
+ * @subpackage Examples
+ * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
+ * @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();
+?>
--- /dev/null
+RewriteEngine Off
--- /dev/null
+<?php
+require_once '../setup.phtml';
+$page = filter_var($_REQUEST['page'], FILTER_SANITIZE_STRING);
+$page = $page ? $page : 'splash.phtml';
+?>
+<!DOCTYPE HTML>
+<html lang="en">
+<head>
+ <title><?php echo SITENAME;?> Administration</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+</head>
+<frameset cols="160,*">
+ <frame name="Nav" src="nav.phtml" frameborder="0">
+ <frame name="Main" src="<?php echo $page;?>" frameborder="0">
+ <noframes>
+ <p>Admin Requires Frames Capable Browser</p>
+ You can get a Standard Compliant browser from:
+ <ul>
+ <li>Google
+ <a href="http://www.google.com/chrome">Chrome</a>
+ </li>
+ <li>Mozilla's
+ <a href="http://www.mozilla.org/products/firefox/">Firefox</a>
+ </li>
+ <li>Microsoft
+ <a href="http://www.microsoft.com/windows/ie/">Internet Explorer</a>
+ </li>
+ </ul>
+ </noframes>
+</frameset>
+</html>
--- /dev/null
+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
--- /dev/null
+<?php require_once '../setup.phtml';?>
+<!DOCTYPE HTML>
+<html lang="en">
+<head>
+<title>Admin Navigation</title>
+<style type="text/css">
+<?php
+$logoAdminSmall
+ = (file_exists('../images/logoAdminSmall.gif'))
+ ? 'background: url(../images/logoAdminSmall.gif) no-repeat;'
+ : '';
+?>
+body {
+ margin: 2px;
+ font-family: arial, sans-serif;
+ font-size: 12px;
+ background-color: #fff;}
+a:link {color: #004C64;}
+a:visited {color: #004C64;}
+a:hover {color: #2C788F;}
+a:active {color: #004C64;}
+
+h1 {
+ font-weight: bold;
+ text-align: center;
+ font-size: 14px;
+ <?php echo $logoAdminSmall;?>
+ text-indent: -3000px;
+ width: 130px;
+ height: 53px;
+ margin-left: 10px;
+ }
+ul { margin: 0; padding: 0; list-style-type: none; }
+li { margin: 0; padding: 0; display: block; }
+li a {
+ text-decoration: none;
+ display: block;
+ margin: 0;
+ padding: 4px 8px;
+ background-color: #004C64;
+ border-bottom: 1px solid #eee;
+ width: 136px;
+ }
+li a:link, li a:visited, li a:active { color: #EEE; }
+li a:hover { background-color: #2C788F; color: #fff; }
+</style>
+</head>
+<body>
+ <h1><a href="<?php echo MEDIA_BASE_URL.$url;?>" target="_top">
+ <?php echo SITENAME;?></a>
+ </h1>
+<ul>
+<?php
+
+$conf = new Config;
+
+$nav['Home'] = MEDIA_BASE_URL.'admin/splash.phtml';
+$nav['Toolbox'] = MEDIA_BASE_URL.'admin/toolbox.php';
+if (defined('GLM_BLOCKS') && GLM_BLOCKS) {
+ $blocksConfig = new Zend_Config_Ini(
+ BASE . 'Toolkit/Blocks/application.ini',
+ strtolower($_ENV['GLM_HOST_ID'])
+ );
+ $nav[$blocksConfig->application->name] = $blocksConfig->application->path;
+}
+if (defined('ROTATING_IMAGES') && ROTATING_IMAGES) {
+ $dbh = Toolkit_Database::getInstance();
+ $sql = "
+ SELECT id,name
+ FROM rotatingimages.application
+ ORDER BY id";
+ $stmt = $dbh->query($sql);
+ while ($app = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ $nav[$app['name']] = MEDIA_BASE_URL . 'admin/rotatingImages.php?app=' . $app['id'];
+ }
+}
+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 '
+ <li>
+ <a href="'.$url.'" target="Main">'.$name.'</a>
+ </li>';
+}
+?>
+</ul>
+
+<a
+ style="display: block; margin: 10px auto; text-align: center;"
+ href="http://www.gaslightmedia.com/"
+ target="_blank">
+ <img
+ alt=""
+ src="https://app.gaslightmedia.com/assets/poweredby.gif"
+ border="0"
+ title="Gaslight Media Website">
+</a>
+</body>
+</html>
--- /dev/null
+<?php require_once '../setup.phtml';?>
+<!DOCTYPE HTML>
+<html lang="en">
+<head>
+<link
+ type="text/css"
+ rel=stylesheet
+ href="<?php echo MEDIA_BASE_URL.'admin/main.css';?>">
+<title>Welcome to GLM Toolbox</TITLE>
+</head>
+<body>
+
+<div style="text-align: center;">
+<p>
+ <strong>Welcome To The <?php echo SITENAME;?> Administration Area</strong>
+</p>
+<p>Please Choose The Area You Wish To Update.</p>
+<img src="<?php echo MEDIA_BASE_URL.'images/logo.gif';?>">
+</div>
+
+</body>
+</html>
+
--- /dev/null
+<?php
+require_once '../setup.phtml';
+$registry = new Toolkit_Registry;
+$registry->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 '<div
+ style="position:absolute;top:2px;right:5px;padding:5px;float:right;width:165px;background-color:#dddddd;"><a style="color:#000000;"
+ href="http://app.gaslightmedia.com/docs/ToolboxHelpGuide.pdf" target="_blank">Printable Toolbox Help Guide</a></div>';
+echo $navHtml;
+echo $html;
+GLM_TOOLBOX::footer();
+?>
--- /dev/null
+<?php
+
+/**
+ * class_db.inc
+ *
+ * Class build for providing postgres function to facilitate
+ * database abstraction.
+ * We're moving on to using PHP Data Objects (PDO) now
+ *
+ * PHP version 5
+ *
+ * @category Classes
+ * @package GLM_DB
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 <steve@gaslightmedia.com>
+ * @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
+ *
+ * <p>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.</p>
+ *
+ * {@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 "<font color=red>".$qs."</font>";
+ }
+ 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);
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/**
+ * Toolbox Classes :)
+ *
+ * @package Toolbox Library
+ * @subpackage Template Library
+ * @filesource
+ */
+
+require_once BASE."classes/class_db.inc";
+require_once BASE."classes/class_toolbox.inc";
+
+/**
+ * Template Class :)
+ *
+ * <p>
+ * $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.
+ * </p>
+ * <p>
+ * For the page title and meta tags make a $title and $meta vars depending on
+ * weather or not it is the home page.
+ * </p>
+ *
+ * @package Toolbox Library
+ * @subpackage Template Library
+ * @category Template
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 = '<h1>';
+
+ /**
+ * The ending style for the header
+ * @var string header_end
+ * @access protected
+ */
+ protected $header_end = '</h1>';
+
+ /**
+ * The starting style for the sub header
+ * @var string
+ * @access protected
+ */
+ protected $subheader_begin = '<h2>';
+
+ /**
+ * The ending style for the sub header
+ * @var string
+ * @access protected
+ */
+ protected $subheader_end = '</h2>';
+
+ /**
+ * 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("<br />","<br>",$output);
+ $output = str_replace("<p><br></p>","",$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 '<pre>'.print_r($e, true).'</pre>';
+ 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 '<pre>'.print_r($e, true).'</pre>';
+ 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 '<pre>'.print_r($e, true).'</pre>';
+ 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[] = '<a href="'.$url.'">Home</a>';
+ if (!is_array( $row ) ) {
+ return false;
+ } else {
+ $out .= '<div id="nav-bottom">';
+ 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[] = '<a href="'.$url.'">'.$category."</a>\n";
+ }
+ if (is_array($links)) {
+ $out .= implode(" | ",$links);
+ }
+ $out .= '</div>';
+ 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[] = '<a href="'.BASE_URL.'">Home</a>';
+ }
+ for($i = 0; $i < $end; ++$i) {
+ $outarray[] = '<a href="'.$string[$i]["link"].'">'.$string[$i]["label"].'</a>';
+ }
+ 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[] = '<a href="'.$currPageUri.'">'.$currPageLabel.'</a>';
+
+ $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 = '<div id="breadcrumbs">'.$out.'</div>';
+ }
+ }
+ 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 .= '<div id="category">';
+ }
+
+ 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 .= '</div>';
+ }
+ $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 '<pre>'.print_r($e, true).'</pre>';
+ 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 = '<span class="dtstart">
+ <span class="value" title="'.date('Y-m-d', $start).'">' .
+ $dateBegin . '</span>
+ </span>';
+ $dateEnd
+ = ($dateEnd)
+ ? '<span class="dtend">
+ <span class="value" title="'.date('Y-m-d', $end).'">' .
+ $dateEnd . '</span>
+ </span>'
+ : '';
+ }
+ 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 = '<div id="h-hotspecials">
+ <span class="h-all">Hot specials</span>';
+ foreach ($data as $row) {
+ $intro = htmlspecialchars(strip_tags($row['intro']));
+ $intro_text = '<p>'.htmlspecialchars(strip_tags($row['feature_intro'] ) ).'</p>';
+ $out .= '<div class="h-hotspecial">
+ <a href="'.$this->get_seo_url( $row['id'] ).'">'.$intro.'</a>
+ '.$intro_text.'
+ </div>';
+ }
+ $out .= '</div>';
+ }
+ 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 = '<ul id="nav">';
+ foreach( $data as $row ){
+ $out .= '<li><a href="'.$this->get_seo_url( $row['id'] ).'">'.$row['category'].'</a></li>';
+ }
+ $out .= '</ul>';
+ }
+ 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[] = '<a href="#sect-'.$val['id'].'">'.strip_tags($val["name"]).'</a>';
+ }
+ // items can be moved around as needed
+ $output .= '<div class="listing" id="sect-'.$val['id'].'">'."\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 .= '<a href="#toolbox">Back to Top</a>';
+ }
+ $output .= "</div>"."\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 = '<div>'.$this->get_distance_from_traverse($_REQUEST['zipcode']).' miles from '.$_REQUEST['zipcode'].'</div>';
+ }
+
+ if ($this->page_status != 'Good') {
+ return '<h1>Sorry this page is Down!</h1>';
+ }
+
+ if ( defined('GOOGLE_SEARCH')
+ && GOOGLE_SEARCH
+ && isset($_REQUEST['query'])
+ && $_REQUEST['query']
+ ) {
+ $out = '<div id="searchcontrol"></div>';
+ } 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 .= '<div id="category">';
+ $out .= $pageHeader;
+ // $out .= $category;
+ $out .= '</div>';
+ }
+
+ // 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 = '<ul id="paragraphLinks">';
+ foreach ($this->sectionAnchors as $anchors) {
+ $links .= '<li>'.$anchors.'</li>';
+ }
+ $links .= '</ul>';
+ $this->cache->save($links, 'sectionLinks-'.$this->catid, 'Toolbox');
+ }
+ }
+ $out = $breadCrumbs;
+ $out .= '<div id="category">';
+ $out .= $pageHeader;
+ $out .= $links;
+ $out .= $category;
+ $out .= '</div>';
+ $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( '
+<div id="topimg">
+ <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="565" height="95" id="accommodations" align="middle">
+ <param name="allowScriptAccess" value="sameDomain">
+ <param value="transparent" name="wmode">
+ <param name="movie" value="'.$base_url.'assets/headers/headers.swf?XMLfile='.$base_url.'assets/headers/'.$headers[$top_parent].'.xml">
+ <param name="quality" value="high">
+ <param name="bgcolor" value="#3D8D3A">
+ <embed wmode="transparent" src="'.$base_url.'assets/headers/headers.swf?XMLfile='.$base_url.'assets/headers/'.$headers[$top_parent].'.xml" quality="high" bgcolor="#ffffff" width="565" height="95" name="accommodations" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
+ </object>
+</div>
+' );
+ } 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 .= '<li><a title="' .
+ htmlentities($title,ENT_QUOTES,'UTF-8') .
+ '" href="'.$url.'"';
+ if ($this->catid == $row['id']) {
+ $return .= ' id="current"';
+ }
+ $return .= '>' .
+ htmlentities($row['category'],ENT_QUOTES,'UTF-8')."</a>";
+ $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 .= '</li>';
+ }
+ $main_cats = $this->get_main_cats();
+ if ($main_cats[$parent]) {
+ $return = '<h2>'.$this->get_catheader($parent, $this->DB).'</h2>
+ <ul>'.$return.'</ul>';
+ $this->cache->save($return, $this->catid, 'Nav');
+ return $return;
+ } else {
+ $return = "\n<ul>$return</ul>\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.'<br>';
+ $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 = '<div id="subnav">';
+ $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 .= '<a title="'.$title.'" class="current" href="'.$url.'">';
+ } else {
+ $output .= '<a title="'.$title.'" href="'.$url.'">';
+ }
+ $output .= $val["category"];
+ $output .= '</a>';
+ 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 .= '</div>';
+ $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.
+ *
+ * <p><b>NOTICE:</b> This is ment to get the top level parent not the parent of the id given.</p>
+ *
+ * @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 = "<a href=\"".$url."\">".htmlspecialchars($keyres[0]['category'])."</a>";
+ $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 .= "\t<li><a title=\"".htmlentities($title, ENT_QUOTES, 'UTF-8').'" href="'.$url.'"';
+ if ($this->catid == $row['id']) {
+ $return .= ' id="current"';
+ }
+ $return .= '>' . htmlentities($row['category'], ENT_QUOTES, 'UTF-8') . '</a>';
+ $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 .= "</li>\n";
+ }
+ $main_cats = $this->get_main_cats();
+ if ( (isset($parent) && $parent != 0)
+ || ( isset($main_cats)
+ && isset($main_cats[$parent])
+ && $main_cats[$parent]
+ )
+ ) {
+ return "<ul>\n\t$return</ul>\n";
+ } else {
+ return "<ul id=\"nav\">\n\t" . $return . "</ul>\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 '<pre>'.print_r($e, true).'</pre>';
+ 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 '<pre>'.print_r($data, true).'</pre>';
+ } catch(PDOException $e) {
+ echo '<pre>'.print_r($e, true).'</pre>';
+ 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
+ * <code><p>{$address}<br>{$city},{$state} {$zip}</p></code>
+ * @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 .= '<br>'.$data["city"].', '.$data["state"].' '.$data["zip"];
+ } elseif ($data["city"] && $data["state"]) {
+ $address .= '<br>'.$data["city"].', '.$data["state"];
+ } elseif ($data["city"]) {
+ $address .= '<br>'.$data["city"];
+ }
+
+ if ($address != "") {
+ return '<p>'.$address.'<br></p>';
+ }
+ }
+
+ // }}}
+ // {{{ 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 .= '
+ <script type="text/javascript" src="http://www.google.com/uds/api?file=uds.js&v=1.0&key='.$apikey.'"></script>';
+ $this->scripts .= '<link rel="stylesheet" type="text/css" href="'.BASE_URL.'gsearch.css">';
+ $this->scripts .= '<script type="text/javascript" src="'.BASE_URL.'libjs/gsearch.php?query='.urlencode($_REQUEST['query']).'"></script>';
+ }
+ }
+
+ // }}}
+ // {{{ 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
+ * <code><p><strong>Contact Name:</strong> {$text}</p></code>
+ *
+ * @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 = '<p><strong>Contact Name:</strong> '.$text.'</p>';
+ }
+ 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
+ *
+ * <p>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]</p>
+ * @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
+ * <code><p><strong>Contact:</strong> <a href="mailto:{$email}" target="_blank">{$text}</a></p></code>
+ * @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 = '<p><strong>Contact:</strong> <a href="mailto:'.$email.'" target="_blank">'.htmlspecialchars($contact).'</a></p>';
+ } else {
+ $email = '<p><strong>Email:</strong> <a href="mailto:'.$email.'" target="_blank">'.htmlspecialchars($email).'</a></p>';
+ }
+ }
+ return $email;
+ }
+
+ // }}}
+ // {{{ set_fax()
+
+ /**
+ * set_fax:Set the fax string
+ * <code><p><strong>Fax:</strong> {$text}</p></code>
+ * @param string $text: The text as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_fax($text)
+ {
+ if ($text != "") {
+ $text = '<p><strong>Fax:</strong> '.htmlspecialchars($text).'</p>';
+ }
+ return $text;
+ }
+
+ // }}}
+ // {{{ set_file()
+
+ /**
+ * set_file:Set the file string
+ * <code><p><strong>Contact Name:</strong> {$text}</p></code>
+ * @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 = '<p><a';
+ if (preg_match("/[.]([A-Z0-9]{3}$)/i", $text, $tmp)) {
+ $outtext .= ' class="file-download '.strtolower($tmp[1]).'"';
+ }
+ $outtext .= ' href="'.MEDIA_BASE_URL.'uploads/'.$text.'" target="_blank">';
+ if ($name) {
+ $outtext .= htmlspecialchars($name);
+ } else {
+ $outtext .= htmlspecialchars($text);
+ }
+ $outtext .= '</a>';
+ if (preg_match("/[.]([A-Z0-9]{3}$)/i", $text, $tmp)) {
+ // don't output second link
+ //$outtext .= '<a href="'.BASE_URL.'download.php?file='.$text.'" class="download">Click here to Download </a>';
+ }
+ $outtext .= '</p>';
+ }
+ 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
+ * <p><code>
+ * <div class="image{$align}" style="width: {$width}px" src="{$size}{$image}" {$titletag}>
+ * <div class="imagecaption">{$caption}</div>
+ * </div>
+ * </code>
+ * </p>
+ *
+ * @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 = '<div '.$img_align.' style="width: '.$image_size[0].'px">';
+ $img .= '<img ';
+ if (isset($img_attr)) {
+ $img .= $img_attr;
+ }
+ $img .= ' src="'.$size.$image.'" '.$titletag.'>';
+ if ($caption) {
+ $img .= '<div class="imagecaption">'.$caption.'</div>';
+ }
+ $img .= '</div>';
+ 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
+ * <code><p><strong>Phone:</strong> {$text}</p></code>
+ * @param string $text: The text as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_phone($text)
+ {
+ if ($text != "") {
+ $text = '<p><strong>Phone:</strong> '.$text.'</p>';
+ }
+ 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
+ * <code><p>{$text}</code>
+ * @param string $text: The text as string
+ *
+ * @return string $text
+ * @access public
+ **/
+ function set_text($text)
+ {
+ if ("" == str_replace("<br />", "", 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
+ * <p>
+ * <code><p><a href="http://{$url}" target="_blank">{$text}</a></code>
+ * </p>
+ *
+ * @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 = '<p><a href="'.$url.'" target="_blank">'.htmlspecialchars($text).'</a></p>';
+ } else {
+ $url = '<p><a href="http://'.$url.'" target="_blank">'.htmlspecialchars($text).'</a></p>';
+ }
+ }
+ 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 = '<img src="'.MIDSIZED.$data[0]["image"].'" border="0" vspace="30" hspace="0">';
+ } else {
+ $img = '<img src="assets/logo_small.gif" width="150" height="85" vspace="0" hspace="0" border="0" alt="Birchwood Construction"><BR>';
+ }
+ echo $img;
+ echo '<BR><img src="assets/clear.gif" height="30" width="1">';
+ }
+
+ // }}}
+ // {{{ 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 = '<div id="subnav"> ';
+
+ $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 .= '<a title="'.$title.'" href="'.$url.'">';
+ $out .= $val["category"];
+ $out .= '</a>';
+ }
+ }
+ $out .= '</div>';
+ 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 '<pre>'.print_r($e, true).'</pre>';
+ 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
+ *
+ * <p>Checks for a valid format and good (mx check)
+ * email address.</p>
+ * @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 );
+ }
+
+ // }}}
+}
+?>
--- /dev/null
+<?php
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
+
+/**
+ * Toolbox Classes :)
+ *
+ * PHP version 5
+ *
+ * <p>
+ * These classes and any code is not licensed for anyone but gaslight to use
+ * </p>
+ *
+ * @category Toolbox
+ * @package GLM_TOOLBOX
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @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 :)
+ *
+ * <p><b>NOTICE</b>
+ * Im going to be moving all functions from the setup.phtml
+ * file and putting it into this</p>
+ * <p>class. This is so we can eventially move
+ * everything to one siteinfo.inc file.</p>
+ * <kbd>matrix@devsys Does this work?</kbd>
+ *
+ * @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 <steve@gaslightmedia.com>
+ * @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 = '<select name="'.$month_name.'">';
+ for ($i = 1; $i < 13; $i++) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= "0";
+ }
+ $date .= $i.'"';
+ if ($i == $month) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ $date .= '<select name="'.$year_name.'">';
+ for ($i = $year; $i < $year + 15; $i++) {
+ $date .= '<option value="'.$i.'"';
+ if ($i == $year) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ 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<strlen($Num); $x++) {
+ $digit = substr($Num, $x, 1);
+ if ($x/2 != floor($x/2)) {
+ $digit *= 2;
+ if (strlen($digit) == 2) {
+ $digit = substr($digit, 0, 1) + substr($digit, 1, 1);
+ }
+ }
+ $Total += $digit;
+ }
+ if ($GoodCard && $Total % 10 == 0) {
+ return true;
+ } else {
+ return false;
+ }
+ }// }}}
+ // {{{ build_checklist($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_checklist($name, $data)
+ {
+ if (!is_array($selected)) {
+ $sel[0] = $selected;
+ } else {
+ $sel = $selected;
+ }
+ if (!is_array($data)) {
+ return false;
+ }
+ foreach ($data as $field => $title) {
+ $out .= '<label for="'.$name.'['.$field.']">
+ <input type="checkbox" id="'.$name.'['.$field.']"
+ name="'.$name.'['.$field.']" value="t"';
+ if ($_POST[$field] == 't') {
+ $out .= ' checked';
+ }
+ $out .= '>'.$title.'</label>';
+ }
+ 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 = "<select name=\"".$fieldname."\" multiple size=\"10\" ".$autosubmit.">\n";
+ while (list($key, $val) = each($data)) {
+ if (in_array($key, $sel)) {
+ $select = " selected ";
+ } else {
+ $select = "";
+ }
+ $str .= " <option value=\"$key\"".$select.">$val\n";
+ }
+ break;
+ case "simple":
+ $str = "<select name=\"$fieldname\" ".$autosubmit.">\n";
+ for ($i = 0; $i < count($data); $i++) {
+ $select = (in_array($data[$i], $sel)) ? " selected ":"";
+ $str .= " <option value=\"".$data[$i]."\"".$select.">".$data[$i]."\n";
+ }
+ break;
+
+ case "standard":
+ default:
+ $str = "<select name=\"$fieldname\" ".$autosubmit.">\n";
+ while (list($key, $val) = each($data)) {
+ $select = (in_array($key, $sel)) ? " selected ":"";
+ $str .= " <option value=\"$key\"".$select.">$val\n";
+ }
+ break;
+ }
+ $str .= "</select>\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 .= '<label for="'.$name.'-'.$count.'">
+ <input type="radio" id="'.$name.'-'.$count.'"
+ name="'.$name.'" value="'.$field.'"';
+ if ($_POST[$name] == $field) {
+ $out .= ' checked';
+ }
+ $out .= '>'.$title.'</label><br>';
+ $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 = '
+ <input value="'.(($value)?$value:'Enter Date').'"
+ style="width:100px;float:left;" type="text" name="'.$name.'"
+ id="'.$name.'" readonly="1">
+ <img src="'.$icon_path.'img.gif" id="'.$name.'_trigger"
+ style="cursor: pointer; border: 1px solid red;" title="Date selector"
+ onmouseover="this.style.background=\'red\';"
+ onmouseout="this.style.background=\'\'">
+ ';
+ 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 .= '
+ <script type="text/javascript">
+ Calendar.setup({
+ inputField : "'.$name.'", // id of the input field
+ ifFormat : "%m/%e/%Y", // format of the input field
+ button : "'.$name.'_trigger",// trigger for the calendar (button ID)
+ align : "Bl", // alignment (defaults to "Bl")
+ singleClick : true,
+ step : 1
+
+ ';
+ if ($value && $value != 'Enter Date') {
+ $out .= ',date : "'.$value.'"';
+ }
+ $out .= '
+ });
+</script>';
+ 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 = '<select id="'.$month_name.'" name="'.$month_name.'" '.$onChange.'>';
+ for ($i=1;$i<13;$i++) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= "0";
+ }
+ $date .= $i.'"';
+ if ($i == $month) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ $date .= '<select id="'.$day_name.'" name="'.$day_name.'" '.$onChange.'>';
+ for ($i=1;$i<32;$i++) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= "0";
+ }
+ $date .= $i.'"';
+ if ($i == $day) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ $date .= '<select id="'.$year_name.'" name="'.$year_name.'" '.$onChange.'>';
+ $ystart = $cur_date['year'] - 10;
+ for ($i=$ystart;$i<=$year;$i++) {
+ $date .= '<option value="'.$i.'"';
+ if ($i == $year) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ 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 = '<a'.$class.$title.$onClick.$onMouseout.$id.'
+ href="'.$options["href"].'">'.$text.'</a>';
+ 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 = "[<a href=\"$GLOBALS[PHP_SELF]?start=".$last
+ ."&$params\">PREVIOUS PAGE</a>]";
+ }
+ if ($end < $totalnum) {
+ $next = "[<a href=\"$GLOBALS[PHP_SELF]?start=".$end
+ ."&$params\">NEXT PAGE</a>]";
+ } else {
+ $next = "";
+ }
+ $starting = $start + 1;
+ $last_c = $start + $num;
+ $links = '<div class="page-links">Showing: '.$starting.' to '
+ .$last_c.' of '.$totalnum.'<div> '.$prev. ' '
+ .$next.'</div></div>';
+ 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 = '<select id="'.$month_name.'" name="'.$month_name.'" '.$onChange.'>';
+ for ($i=1;$i<13;$i++) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= "0";
+ }
+ $date .= $i.'"';
+ if ($i == $month) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ $date .= '<select id="'.$day_name.'" name="'.$day_name.'" '.$onChange.'>';
+ for ($i=1;$i<32;$i++) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= "0";
+ }
+ $date .= $i.'"';
+ if ($i == $day) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ $date .= '<select id="'.$year_name.'" name="'.$year_name.'" '.$onChange.'>';
+ for ($i=2000;$i<2023;$i++) {
+ $date .= '<option value="'.$i.'"';
+ if ($i == $year) {
+ $date .= ' selected';
+ }
+ $date .= '>'.$i.'</option>';
+ }
+ $date .= '</select>';
+ 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 </body></html>";
+ }
+
+ // }}}
+ // {{{ form_footer($name, $suppress = 0, $cs)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $name Parameter description (if any) ...
+ * @param integer $suppress Parameter description (if any) ...
+ * @param unknown $cs Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function form_footer($name, $suppress = 0, $cs = 2)
+ {
+ echo "<tr><td colspan=\"$cs\" align=center>
+ <input type=\"SUBMIT\" name=\"Command\" value=\"$name\">";
+ if ($suppress == 1) {
+ echo '<input type="SUBMIT" name="Command" value="Delete" onclick="return confirm(\'This will be Deleted! Are you sure?\');">';
+ }
+ /* echo "<input type=\"SUBMIT\" name=\"Command\" value=\"Cancel\">";*/
+ echo "</td>";
+ }// }}}
+ // {{{ form_header($action, $method, $hidden = "")
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $action Parameter description (if any) ...
+ * @param unknown $method Parameter description (if any) ...
+ * @param mixed $hidden Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function form_header($action, $method, $hidden = "")
+ {
+ echo "<form action=\"$action\" method=\"$method\"
+ enctype=\"multipart/form-data\">";
+ if ($hidden != "" && is_array($hidden)) {
+ foreach ($hidden as $key=>$value) {
+ echo "<input type=\"hidden\" name=\"$key\" value=\"$value\">";
+ }
+ }
+ }// }}}
+ // {{{ get_parentid($id)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param integer $id Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function get_parentid($id)
+ {
+ static $parentshow;
+ if ($id == 0) {
+ return 0;
+ }
+ if (!is_array($parentshow)) {
+ $qs = "select parent from bus_category where id = $id";
+ $parentrow = GLM_TOOLBOX::db_auto_get_data($qs);
+ }
+ if ($parentrow[0]['parent'] == 0) {
+ return $id;
+ } else {
+ return GLM_TOOLBOX::get_parentid($parentrow[0]['parent']);
+ }
+ }// }}}
+ // {{{ get_season()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function get_season()
+ {
+ /*
+ The seasons
+ Spring March 21st to June 20
+ Summer June 21 to Sept 20
+ Fall Sept 21 to Dec 20
+ Winter Dec 21 to March 20
+ */
+ $Spring = mktime(0, 0, 0, 3, 21, date("Y"));
+ $Summer = mktime(0, 0, 0, 6, 21, date("Y"));
+ $Fall = mktime(0, 0, 0, 9, 21, date("Y"));
+ $Winter = mktime(0, 0, 0, 12, 21, date("Y"));
+ $time = mktime();
+ if ($time >= $Spring && $time < $Summer) {
+ $season = "spring";
+ } elseif ($time >= $Summer && $time < $Fall) {
+ $season = "summer";
+ } elseif ($time >= $Fall && $time < $Winter) {
+ $season = "fall";
+ } else {
+ $season = "winter";
+ }
+ return $season;
+ }// }}}
+ // {{{ get_size($file)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $file Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function get_size($file)
+ {
+ $size = filesize($file) / 1024;
+ if ($size >= 1000) {
+ $size = (float) number_format($size / 1000, 2);
+ $size .= 'MB';
+ } elseif ($size < 1000) {
+ $size = ceil($size);
+ $size .= 'KB';
+ }
+ return $size;
+ }// }}}
+ // {{{ html_error($msg, $bail)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $msg Parameter description (if any) ...
+ * @param unknown $bail Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function html_error($msg, $bail)
+ {
+ echo '<div style="color:red;"><pre>'.$msg.'</pre></div>';
+ if ($bail) {
+ GLM_TOOLBOX::footer();
+ }
+ }// }}}
+ // {{{ html_header($title, $msg, $img)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $title Parameter description (if any) ...
+ * @param unknown $msg Parameter description (if any) ...
+ * @param unknown $img Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function html_header($title, $msg, $img)
+ {
+ $header_table_width = "400";
+ $header_table_align = "center";
+ echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+ "http://www.w3.org/TR/html4/loose.dtd">
+ <html>
+ <head>
+ <title><?echo $title?></title>
+ <link type="text/css" rel=stylesheet href="<?echo STYLE?>">
+ </head>
+ <body>
+ <table width="<?echo $header_table_width?>" align="<?echo $header_table_align?>" summary="Header Information" class="headertable" cellspacing="0" cellpadding="3">
+ <tr class="headertr">
+ <td class="headertd">';
+ if ($img) {
+ echo '<img src="<?echo IMG_BASE.$img?>" alt="<?echo HEAD?>" border="0">';
+ }
+ echo '</td>
+ </tr>
+ <tr>
+ <td class="headertd2" align="center">
+ <div class="headerh2" align="center"><?echo "$msg"?></div>
+ </td>
+ </tr>
+ </table>';
+ }// }}}
+ // {{{ html_nav_table($nav, $w)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param array $nav Parameter description (if any) ...
+ * @param unknown $w Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function html_nav_table($nav, $w)
+ {
+ if (is_array($nav)) {
+ $out = '<ul class="admin_nav">';
+ foreach ($nav as $link => $url) {
+ if (is_array($url)) {
+ $out .= '<li><a href="'.$url[0].'" '.$url[1].'>'.$link.'</a></li>';
+ } else {
+ $out .= '<li><a href="'.$url.'">'.$link.'</a></li>';
+ }
+ }
+ $out .= '</ul>';
+ }
+ echo $out;
+ }// }}}
+ // {{{ http_strip(&$string)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown &$string Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function http_strip(&$string)
+ {
+ $test_string = strtolower($string);
+ if (substr($test_string, 0, 7) == "http://") {
+ $string = substr($string, 7);
+ }
+ }// }}}
+ // {{{ img_resize($path2image, $path2thumb, $size)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $path2image Parameter description (if any) ...
+ * @param unknown $path2thumb Parameter description (if any) ...
+ * @param unknown $size Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function img_resize($path2image, $path2thumb, $size)
+ {
+ exec("which convert", $output, $return);
+ if ($return == 0) {
+ $CONVERT = $output[0];
+ } else {
+ return $error = array('convert path uknown');
+ }
+ $imageName = basename($path2image);
+ $thumbName = basename($path2thumb);
+
+ exec("$CONVERT -quality 100 -scale $size $path2image $path2thumb");
+ //chmod($path2thumb,660);
+
+ $img_resize_array = array("$imageName","$path2image","$thumbName","$path2thumb");
+ return $img_resize_array;
+ }// }}}
+ // {{{ img_upload($form_field, $img_name, $destination_path)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $form_field Parameter description (if any) ...
+ * @param unknown $img_name Parameter description (if any) ...
+ * @param unknown $destination_path Parameter description (if any) ...
+ *
+ * @return boolean Return description (if any) ...
+ * @access public
+ */
+ function img_upload($form_field, $img_name, $destination_path)
+ {
+ return GLM_TOOLBOX::file_upload($form_field, $img_name, $destination_path, true);
+ }// }}}
+ // {{{ is_utf8($string)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $string Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function is_utf8($string)
+ {
+ return preg_match('/^([\x00-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xec][\x80-\xbf]{2}|\xed[\x80-\x9f][\x80-\xbf]|[\xee-\xef][\x80-\xbf]{2}|f0[\x90-\xbf][\x80-\xbf]{2}|[\xf1-\xf3][\x80-\xbf]{3}|\xf4[\x80-\x8f][\x80-\xbf]{2})*$/', $string) === 1;
+ }// }}}
+ // {{{ make_data_table($data, $tableId = null)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param array $data Parameter description (if any) ...
+ * @param string $tableId Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function make_data_table($data, $tableId = null)
+ {
+ if (is_array($data)) {
+ $count = 0;
+ foreach ($data as $row) {
+ if (!is_array($row)) {
+ return false;
+ }
+ $table_body .= '<tr>
+ ';
+ $col = 1;
+ foreach ($row as $field_name => $field) {
+ if ($count == 0) {
+ $table_head .= '<th>'.$field_name.'</th>';
+ }
+ $table_body .= '<td class="c'.$col.'">'.$field.'</td>';
+ $col++;
+ }
+ $count++;
+ $table_body .= '</tr>
+ ';
+ }
+ $table = '<table'.(($tableId)?' id="'.$tableId.'"':'').'>
+ <tr>'.$table_head.'</tr>
+ '.$table_body.'
+ </table>';
+ }
+ return $table;
+ }// }}}
+ // {{{ make_teaser($text, $maxlength, $strip_tags=false)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $text Parameter description (if any) ...
+ * @param unknown $maxlength Parameter description (if any) ...
+ * @param boolean $strip_tags Parameter description (if any) ...
+ *
+ * @return unknown Return description (if any) ...
+ * @access public
+ */
+ function make_teaser($text, $maxlength, $strip_tags=false)
+ {
+ if ($strip_tags) {
+ $text = strip_tags($text);
+ }
+ if (strlen($text) > $maxlength) {
+ if (!($pos = strpos($text, ' ', $maxlength))) {
+ return $text;
+ }
+ $text = substr($text, 0, $pos);
+ }
+ return $text;
+ }// }}}
+ // {{{ myEncode($string)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $string Parameter description (if any) ...
+ *
+ * @return boolean Return description (if any) ...
+ * @access public
+ */
+ function myEncode($string)
+ {
+ if (GLM_TOOLBOX::is_utf8($string)) {
+ return $string;
+ } else {
+ return GLM_TOOLBOX::cp1252_to_utf8($string);
+ }
+ }// }}}
+ // {{{ php_old_pg()
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @return boolean Return description (if any) ...
+ * @access public
+ */
+ function php_old_pg()
+ {
+ switch($this->php_version[0]) {
+ case 5:
+ return false;
+ break;
+
+ case 4:
+ switch($php_version[1]) {
+ case 2:
+ return false;
+ break;
+ case 1:
+ return true;
+ break;
+ }
+ break;
+ }
+ }// }}}
+ // {{{ php_version_check()
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @return array Return description (if any) ...
+ * @access public
+ */
+ function php_version_check()
+ {
+ $this->php_version = explode(".", phpversion());
+ return $this->php_version;
+ }// }}}
+ // {{{ process_image($image, $image_name)
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $image Parameter description (if any) ...
+ * @param unknown $image_name Parameter description (if any) ...
+ *
+ * @return unknown Return description (if any) ...
+ * @access public
+ */
+ function process_image($image)
+ {
+ require_once BASE.'Toolkit/Image/Server.php';
+ $imServer = new Toolkit_Image_Server();
+ $image_name = $imServer->imageUpload($image);
+ return $image_name;
+ }// }}}
+ // {{{ send_html_email($to, $subject, $body, $headers, $charset = 'utf-8')
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $to Parameter description (if any) ...
+ * @param unknown $subject Parameter description (if any) ...
+ * @param unknown $body Parameter description (if any) ...
+ * @param string $headers Parameter description (if any) ...
+ * @param string $charset Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function send_html_email($to, $subject, $body, $headers, $charset = 'utf-8')
+ {
+ if ($headers) {
+ $headers .= "\n";
+ }
+ $headers .= "MIME-Version: 1.0\n"
+ . "Content-type: text/html; charset=".$charset;
+ mail($to, $subject, $body, $headers);
+ }// }}}
+ // {{{ template_read($template)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param nknown $template Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function template_read($template)
+ {
+ $fp = fopen($template, "r");
+ $contents = fread($fp, filesize($template));
+ fclose($fp);
+ if ($contents) {
+ return $contents;
+ } else {
+ return "";
+ }
+ }// }}}
+ // {{{ template_replacement($template, $fieldarr)
+
+
+ /**
+ * 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) ...
+ * @access public
+ */
+ function template_replacement($template, $fieldarr)
+ {
+ if (is_array($fieldarr)) {
+ $fieldarr['BASE_URL'] = BASE_URL;
+ foreach ($fieldarr as $key => $value) {
+ $p = "/<!-- loop:$key -->(.*?)<!-- endloop:$key -->/s";
+ if (preg_match($p, $template, $match) && is_array($value)) {
+ // ok we have found a loop for this array
+ // now lets add into this template the correct
+ // number we'll need to do the replacement
+ // replace template loop section with {loop:$key}
+ $p = "/<!-- loop:$key -->(.*?)<!-- endloop:$key -->/s";
+ $template = preg_replace($p, "{loop:$key}", $template);
+ // saving the actual template with match run through
+ // the array to build a tempory section
+ // then switch it out for {loop:$key}
+ $template_temp = '';
+ foreach ($value as $srow) {
+ $tpl = $match[1];
+ foreach ($srow as $field => $val) {
+ $p = "/<!-- if:$key:$field -->(.*?)<!-- endif:$key:$field -->/s";
+ if (preg_match($p, $template) && $val == '') {
+ $p = "/<!-- if:$key:$field -->(.*?)<!-- endif:$key:$field -->/s";
+ $tpl = preg_replace($p, '', $tpl);
+ } else {
+ $tpl = str_replace("<!-- $key:$field -->", $val, $tpl);
+ }
+ }
+ $template_temp .= $tpl;
+ }
+ $template = str_replace("{loop:$key}", $template_temp, $template);
+
+ } else {
+ $p = "/<!-- if:$key -->(.*?)<!-- endif:$key -->/s";
+ if (preg_match($p, $template) && $value == '') {
+ $p = "/<!-- if:$key -->(.*?)<!-- endif:$key -->/s";
+ $template = preg_replace($p, '', $template);
+ } else {
+ $template = str_replace("<!-- $key -->", $value, $template);
+ }
+ }
+ }
+ }
+
+ return $template;
+ }// }}}
+ // {{{ text_area($name, $value, $rows = 15, $cols = 50, $wrap = "virtual")
+
+
+ /**
+ * create td element with textarea element inside
+ * Creates the textarea field with souround ing td tags
+ *
+ * @deprecated
+ *
+ * @param unknown $name name attr
+ * @param unknown $value text node
+ * @param integer $rows rows attr
+ * @param integer $cols cols attr
+ * @param string $wrap wrap attr
+ *
+ * @return void
+ * @access public
+ */
+ function text_area($name, $value, $rows = 15, $cols = 50, $wrap = "virtual")
+ {
+ $html = '
+ <td>
+ <textarea id="%s" name="%s" rows="%s" cols="%s" wrap="%s">%s</textarea>
+ </td>';
+ return printf(
+ $html,
+ $name,
+ $name,
+ $rows,
+ $cols,
+ $wrap,
+ htmlspecialchars($value)
+ );
+ }// }}}
+ // {{{ text_box($name, $value, $size = 35)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $name Parameter description (if any) ...
+ * @param unknown $value Parameter description (if any) ...
+ * @param integer $size Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function text_box($name, $value, $size = 35)
+ {
+ echo "<td class=\"navtd2\"><input type=\"text\" name=\"$name\"
+ value=\"".htmlspecialchars($value)."\" size=\"$size\"></td>";
+ }// }}}
+ // {{{ time_entry($H, $m, $F, $H_name, $m_name, $F_name)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param mixed $H Parameter description (if any) ...
+ * @param string $m Parameter description (if any) ...
+ * @param string $F Parameter description (if any) ...
+ * @param unknown $H_name Parameter description (if any) ...
+ * @param unknown $m_name Parameter description (if any) ...
+ * @param unknown $F_name Parameter description (if any) ...
+ *
+ * @return string Return description (if any) ...
+ * @access public
+ */
+ function time_entry($H, $m, $F, $H_name, $m_name, $F_name)
+ {
+ $cur_date = getdate();
+ if ($H == "") {
+ $H = $cur_date['hours'];
+ }
+ if ($m == "") {
+ $m = $cur_date['minutes'];
+ }
+ if ($H>12) {
+ $F = "PM";
+ $H = $H - 12;
+ }
+ $time = "Hr:<select name=\"$H_name\" size=\"1\">";
+ for ($i=1;$i<=12;$i++) {
+ $time .= "<option value=\"";
+ if ($i < 10) {
+ $time .= "0";
+ }
+ $time .= "$i\"";
+ if ($i == $H) {
+ $time .= " selected";
+ }
+ $time .= ">$i\n";
+ }
+ $time .= "</select>\n";
+ $time .= "Min:<select name=\"$m_name\" size=\"1\">";
+ for ($i=0;$i<60;$i=$i+15) {
+ $time .= "<Option value=\"";
+ if ($i < 10) {
+ $time .= "0";
+ }
+ $time .= "$i\"";
+ if ($i == $m) {
+ $time .= " selected";
+ }
+ $time .= ">";
+ if ($i < 10) {
+ $time .= "0";
+ }
+ $time .= "$i\n";
+ }
+ $time .= "</select>";
+ $time .= "<select name=\"$F_name\" size=\"1\">";
+ $time .= "<option value=\"AM\"";
+ if ($F == "AM") {
+ $time .= " selected";
+ }
+ $time .= ">AM\n";
+ $time .= "<option value=\"PM\"";
+ if ($F == "PM") {
+ $time .= " selected";
+ }
+ $time .= ">PM\n";
+ $time .= "</select>\n";
+ return $time;
+ }// }}}
+ // {{{ top($message, $hp,$hp2 = null)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param string $message Parameter description (if any) ...
+ * @param unknown $hp Parameter description (if any) ...
+ * @param string $hp2 Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function top($message, $hp, $hp2 = null, $includeMainStyleSheet = true)
+ {
+ if ($hp2 != "") {
+ $help_guide = '<div id="glm-manual">';
+ /*
+ $help_guide = '<div id="glm-manual"><a id="manual-html"
+ href="http://www.gaslightmedia.com/manuals/html/'.$hp2.'.html"
+ target="_blank">Online Help Guide</a> ';
+ */
+ $help_guide .= '<a id="manual-pdf"
+ href="http://www.gaslightmedia.com/manuals/pdf/'.$hp2.'.pdf"
+ target="_blank">Printable Help Guide</a></div>';
+ }
+ // Default resources for admin pages.
+ if (is_array($GLOBALS['topScripts'])) {
+
+ $topScripts = $GLOBALS['topScripts'];
+ array_reverse($topScripts);
+ array_push($topScripts, JQUERY_CDN_JS);
+ array_reverse($topScripts);
+
+ $GLOBALS['topScripts'] = $topScripts;
+ } else {
+ $GLOBALS['topScripts'] = array(
+ JQUERY_CDN_JS
+ );
+ }
+ if ($includeMainStyleSheet) {
+ $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'admin/main.css';
+ }
+
+ $topScripts = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+ $styles = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+ if (!empty($message)) {
+ $header = "<h1>$message</h1>";
+ }
+
+ $out = '
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+ <html>
+ <head>
+ <title>Untitled</title>
+ <meta http-equiv="content-type" content="text/html;charset=utf-8">
+ ' . $styles . $topScripts .'
+ </head>
+ <body>' .
+ $header . ' ' .
+ $help_guide;
+ echo $out;
+ }
+
+ // }}}
+ function topUserArea($message, $hp, $hp2 = null, $includeMainStyleSheet = true)
+ {
+ if ($hp2 != "") {
+ $help_guide = '<div id="glm-manual">';
+ /*
+ $help_guide = '<div id="glm-manual"><a id="manual-html"
+ href="http://www.gaslightmedia.com/manuals/html/'.$hp2.'.html"
+ target="_blank">Online Help Guide</a> ';
+ */
+ $help_guide .= '<a id="manual-pdf"
+ href="http://www.gaslightmedia.com/manuals/pdf/'.$hp2.'.pdf"
+ target="_blank">Printable Help Guide</a></div>';
+ }
+ // Default resources for admin pages.
+ $GLOBALS['topScripts'][] = MEDIA_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js';
+ if ($includeMainStyleSheet) {
+ $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'userArea/main.css';
+ }
+
+ $topScripts = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+ $styles = Toolkit_Common::getStyleSheets($GLOBALS['styleSheets']);
+
+ if (!empty($message)) {
+ $header = "<h1>$message</h1>";
+ }
+
+ $out = '
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+ <html>
+ <head>
+ <title>Untitled</title>
+ <meta http-equiv="content-type" content="text/html;charset=utf-8">
+ ' . $styles . $topScripts .'
+ </head>
+ <body>' .
+ $header . ' ' .
+ $help_guide;
+ echo $out;
+ }
+ // {{{ top2($message, $hp,$hp2 = null)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $message Parameter description (if any) ...
+ * @param unknown $hp Parameter description (if any) ...
+ * @param unknown $hp2 Parameter description (if any) ...
+ *
+ * @return void
+ * @access public
+ */
+ function top2($message, $hp, $hp2 = null)
+ {
+ // make this an alias to top()
+ // by calling top instead of adding extra code
+ GLM_TOOLBOX::top($message, $hp, $hp2);
+ }// }}}
+ // {{{ valid_email($email)
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $email Parameter description (if any) ...
+ *
+ * @return boolean Return description (if any) ...
+ * @access public
+ */
+ function valid_email($email)
+ {
+ // First, we check that there's one @ symbol, and lengths are right
+ if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
+ // Email invalid because wrong number of characters in one section,
+ // or wrong number of @ symbols.
+ return false;
+ }
+ // Split it into sections to make life easier
+ $email_array = explode("@", $email);
+ $local_array = explode(".", $email_array[0]);
+ for ($i = 0; $i < sizeof($local_array); $i++) {
+ $p = "/^(([A-Za-z0-9!#$%&'*+\/=?^_`{"
+ ."|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})"
+ . "|(\"[^(\\|\")]{0,62}\"))$/";
+ if (!preg_match($p, $local_array[$i])) {
+ return false;
+ }
+ }
+ if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) {
+ // Check if domain is IP. If not, it should be valid domain name
+ $domain_array = explode(".", $email_array[1]);
+ if (sizeof($domain_array) < 2) {
+ return false; // Not enough parts to domain
+ }
+ for ($i = 0; $i < sizeof($domain_array); $i++) {
+ $p = "/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])"
+ ."|([A-Za-z0-9]+))$/";
+ if (!preg_match($p, $domain_array[$i])) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }// }}}
+ // {{{ word_limiter($str, $limit = 100, $end_char = '…')
+
+
+ /**
+ * Short description for function
+ *
+ * Long description (if any) ...
+ *
+ * @param unknown $str Parameter description (if any) ...
+ * @param mixed $limit Parameter description (if any) ...
+ * @param string $end_char Parameter description (if any) ...
+ *
+ * @return mixed Return description (if any) ...
+ * @access public
+ */
+ function word_limiter($str, $limit = 100, $end_char = '…')
+ {
+ if (trim($str) == '') {
+ return $str;
+ }
+
+ preg_match('/\s*(?:\S*\s*) {'. (int) $limit .'}/', $str, $matches);
+
+ if (strlen($matches[0]) == strlen($str)) {
+ $end_char = '';
+ }
+ return rtrim($matches[0]) . $end_char;
+ }// }}}
+}
+?>
--- /dev/null
+; Production server configuration data
+[production]
+; Turn the banner application On or Off
+bannerdb.application = Off
+; Turn the Shop application On or Off
+retailShop.application = Off
+
+; Turn the contact application On or Off
+contactdb.application = Off
+; Set the first year available in the year select lists
+; these are in the report builder form for admin
+; site > admin > contacts > report builder
+contactdb.first_year = 2014
+; used in the email out for the contact db
+contactdb.production_mode = "ON"
+; turn on for html email
+contactdb.html_email = "ON"
+
+; STREAM SEND API
+; Turn on the streamsend module to use with our contact application
+contactdb.streamsend.application = Off
+; Login id for the streamsend account
+contactdb.streamsend.login = Off
+; Transaction key for the streamsend account
+contactdb.streamsend.key = Off
+; Streamsend account name
+contactdb.streamsend.account_name = Off
+; Streamsend audience number
+contactdb.streamsend.audience = Off
+
+; CONSTANT CONTACT API
+; Constant Contact forms
+constantcontact.application = Off
+; login for Constant Contact
+constantcontact.login = Off
+; password for Constant Contact
+constantcontact.password = Off
+; API Key
+constantcontact.apikey = Off
+; API Path
+constantcontact.apipath = Off
+; Constant Contact List - Array of list to add contacts to
+; example BeaverIslandBoatCo/lists/1
+constantcontact.list.0 = Off
+
+; Turn the coupon application On or Off
+coupons.application = Off
+
+; Turn the event application On or Off
+eventdb.application = Off
+; Turn the Events Common Application On or Off
+eventdb.commonEvents = On
+; The page id in the toolbox that holds the event calendar
+eventdb.event_page = Off
+; Turn the home page events module On or Off for the event application
+eventdb.home_events = Off
+
+; Turn the events management application On or Off
+event_management.application = Off
+; The page id in the toolbox that is the entry page for Event management - Generally set for each server
+event_management.home_page = Off
+event_management.members_only_page = Off
+
+; Turn the google search application On of Off
+google.search.application = Off
+
+; Turn on Gaslight Media Search application On or Off
+glmsearch.application = On
+glmsearch.site = "demo.gaslightmedia.com"
+glmsearch.login = "WebsiteServices"
+glmsearch.key = "829800701e8440b67a78e3afbefa1049"
+
+; Turn the home page headlines module On or Off for the toolbox
+headlines.application = Off
+
+; Turn the member application On or Off
+memberdb.application = Off
+; The page id in the toolbox that holds the login box to the members only area
+memberdb.login_page = Off
+; The page id in the toolbox that is the members only area home page
+memberdb.members.home_page = Off
+; The page id in the toolbox that is the members only area profile form page
+memberdb.members.profile_form_page = Off
+; The page id in the toolbox that is the members only area coupons page
+memberdb.members.coupons.page = Off
+memberdb.members.coupons.notification_email = Off
+; The page id in the toolbox that is the members only area events page
+memberdb.members.events_page = Off
+memberdb.members.events.notification_email = Off
+; The page id in the toolbox that is the members only reporting page
+memberdb.members.reports_page = Off
+; The page id in the toolbox that is the members only leads page
+memberdb.members.leads_page = Off
+; Turn the trip planner module On or Off for the member application
+memberdb.session.list = Off
+; The page id in the toolbox that holds the output for the trip planner
+memberdb.session.page = Off
+; The page id in the toolbox that holds the create account form for the trip planner
+memberdb.session.form = Off
+; Turn on the streamsend module to use with our member application
+memberdb.streamsend.application = Off
+
+; Turn the news On or Off
+news.application = Off
+; Turn the home page news On or Off
+news.home = Off
+; The page id for news output
+news.page = Off
+
+; Turn the photo gallery application On or Off
+photo_gallery.application = Off
+
+; Turn the rotating image application On or Off
+rotating_images.application = Off
+
+; Turn the weather application On or Off
+weather.application = Off
+
+; Turn the gift certificate application On or Off
+gift_certificates.application = Off
+
+ticketing.available = Off
+ticketing.catid = Off
+ticketing.cat_seo = Off
+
+employment.application = Off
+videos.application = Off
+seasons.application = Off
+blocks.application = Off
+; 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]
+
--- /dev/null
+; production server configuration for application
+[production]
+; Application specific options
+options.categoryBlocks.show = On
+options.categoryBlocks.events = 3
+options.defaultSearchDays = 7
+options.shortCuts.today = On
+options.shortCuts.tommorrow = On
+options.hasMajorEvents = Off
+options.eventsPerPageOnPdf = 8
+options.hasNameSearch = On
+; short cuts for next 7 days (date ranges)
+options.shortCuts.dayRange[] = 7
+
+; for pdf logo path from BASE
+options.pdfLogoPath = Off
+
+; default Flexy Options for this application
+flexyOptions.multiSource = On
+flexyOptions.templateDir[] = BASE "Toolkit/Events/views"
+flexyOptions.templateDir[] = COMMON_APP_PATH "views"
+flexyOptions.compileDir = BASE "Toolkit/Events/views/compiled"
+flexyOptions.templateDirOrder = "reverse"
+
+; development server configuration inherits from production and
+; overrides values as needed
+[development : production]
+
+; Chuck's server configuration inherits from development and
+; overrides values as needed
+[chuck : development]
+
+; Steve's server configuration inherits from development and
+; overrides values as needed
+[steve : development]
--- /dev/null
+; Production site configuration data
+[production]
+; Name used in the title tag, admin area and emails
+site_url = "http://www.soolocks.com/"
+coupon_site_url = "www.soolocks.com"
+
+; Link URL to access mobile site to home page
+mobile.link =
+mobile.hostname = On
+
+; google search api key
+google.search.key = "ABQIAAAANX0yQZ2OteLu_zqbwdfUuRT9PY8-4c5xPr71Q7CZ_E9OOktIvhS7e6r_9XaLW5jy3O84t-dz7SK21Q"
+; google search site restriction
+google.search.site_restriction = "http://demo.gaslightmedia.com/"
+; google maps api key
+google.maps.key = "ABQIAAAANX0yQZ2OteLu_zqbwdfUuRT9PY8-4c5xPr71Q7CZ_E9OOktIvhS7e6r_9XaLW5jy3O84t-dz7SK21Q"
+
+; unsecure url to servers app.gaslightmedia.com directory
+app.base_url = "http://app.gaslightmedia.com/"
+; secure url to servers app.gaslightmedia.com directory
+app.base_secure_url = "https://app.gaslightmedia.com/"
+
+; secure url to file server
+file_server.secure = "https://is0.gaslightmedia.com/"
+; unsecure url to file server
+file_server.unsecure = "http://is0.gaslightmedia.com/"
+; owner id for the file server
+file_server.owner_id = "soolocks"
+; owner password for the file server
+file_server.owner_password = "BWPxYvNP"
+
+; Who to send emails to when we handle an error
+error.email = "errors@gaslightmedia.com"
+; level of error reporting
+error.reporting = 0
+; display errors on web page?
+error.display = 0
+; type of PEAR_Log subclass to use for error logging
+error.type = "error_log"
+; constant name of PEAR_Log store to use
+error.name = "PEAR_LOG_TYPE_FILE"
+; identity reported to the log system
+error.ident = "Production"
+; Log error messages up to and including this level
+; HIGHEST PRIORITY
+; +-------------------------------------------+
+; |PEAR_LOG_EMERG |System is unusable |
+; +-----------------+-------------------------+
+; |PEAR_LOG_ALERT |Immediate action required|
+; +-----------------+-------------------------+
+; |PEAR_LOG_CRIT |Critical conditions |
+; +-----------------+-------------------------+
+; |PEAR_LOG_ERR |Error conditions |
+; +-----------------+-------------------------+
+; |PEAR_LOG_WARNING |Warning conditions |
+; +-----------------+-------------------------+
+; |PEAR_LOG_NOTICE |Normal but significant |
+; +-----------------+-------------------------+
+; |PEAR_LOG_INFO |Informational |
+; +-----------------+-------------------------+
+; |PEAR_LOG_DEBUG |Debug-level messages |
+; +-------------------------------------------+
+; LOWEST PRIORITY
+error.level = "PEAR_LOG_WARNING"
+; constant used to figure out what site we are in
+error.conf.server = "SERVER_DIRECTORY"
+; path to log file
+error.conf.path = "/var/www/log/"
+; log file name
+error.conf.file = "php.error"
+; format of printed error message in log file
+error.conf.line_format = "%{timestamp: PRIORITY: %{priority} MESSAGE: %{message}
+"
+
+; type of database we're using
+database.type = "postgres"
+; adapter for database
+database.adapter = "pgsql"
+; error message displayed - used for GLM_DB class
+database.error.message = "An error has occured with the database!"
+; host to connect to
+database.params.host = "ds3"
+; username to connect as
+database.params.username = "nobody"
+; database name to connect to
+database.params.dbname = "soolocks"
+
+; if we're in development mode or not
+development = Off
+
+; site owner email address
+email.owner = "contact@gaslightmedia.com"
+; contact form email
+email.contact = "contact@gaslightmedia.com"
+; Add Your Event Form Email
+email.addEventForm = "contact@gaslightmedia.com"
+; enews form email
+email.enews = "contact@gaslightmedia.com"
+; visitor guide form email
+email.visitor_guide = "contact@gaslightmedia.com"
+; employment application form
+email.applicationForm = "contact@gaslightmedia.com"
+; reply header for admin/MContact
+email.reply_member_news = "contact@gaslightmedia.com"
+; which email address should pending member update notifications go to
+; if you set this to false - no emails will be sent for updates
+email.member_record_updates_advisor = "contact@gaslightmedia.com"
+; reply-to email used in the members forgot password email
+email.member_forgot_password_email_reply_to = "contact@gaslightmedia.com"
+; This is where the first email goes to notify the site owner that a gift
+; certificate has been ordered
+email.giftcert = "contact@gaslightmedia.com"
+; used at the from address for gift certificate emails
+email.giftcert_from = "contact@gaslightmedia.com"
+; email contains senstive information and must be an upnorth.net address
+email.giftcert_secure = "info@upnorth.net"
+; used in admin/Contact mailout.phtml file in the reply-to header
+email.reply_to = "contact@gaslightmedia.com"
+; email address to send the banner reports to for the site admin
+email.banner_reports_admin = "contact@gaslightmedia.com"
+; email address to send banner expiration notices to
+email.expiring_banner_notification = "contact@gaslightmedia.com"
+; from header for admin/Contact mailout
+;
+; the networking department assigns an alias for the
+; "From:newsletter@xxx.com address that forwards to a
+; "xxx_bounce@harbor.gaslightmedia.com" address
+;
+; xxx being the domain of the website
+email.from_news = "newsletter@gaslightmedia.com"
+email.server_from = "server@gaslightmedia.com"
+; from header for admin/MContact mailout
+;
+; the networking department assigns an alias for the
+; "From:newsletter@xxx.com address that forwards to a
+; "xxx_bounce@harbor.gaslightmedia.com" address
+;
+; xxx being the domain of the website
+email.from_member_news = "newsletter@gaslightmedia.com"
+; dead email address for forms w/ one-way communication
+; ie: pending member updates
+email.do_not_reply = "donotreply@gaslightmedia.com"
+
+auth.test = "LOCAL_TEST"
+auth.send_conf = Off
+auth.merchant_email = Off
+auth.debug = Off
+
+; turn on/off xhtml output
+; if Off, html 4 strict is used
+xhtml = Off
+
+; version number for site resources
+; ie: stylesheets or scripts
+; this will be used for cache-busting
+resources.version = 1
+; environment request for resources
+; choices are "dev" or "prod"
+; dev will request resources that are not compressed
+; prod will request resources that have been compressed and minified
+resources.environment.javascript = "prod"
+resources.environment.css = "prod"
+
+; development site configuration data inherits from production and
+; overrides values as necessary
+[development : production]
+site_url = "http://dev53.gaslightmedia.com/www.soolocks.com/"
+
+mobile.link =
+mobile.hostname = Off
+
+google.search.key = "ABQIAAAANX0yQZ2OteLu_zqbwdfUuRTeX7yNUukyMrmY8FsCXcCA9axlYBTyhehgzuXOUfNI0E5UYHCLponA0A"
+google.maps.key = "ABQIAAAANX0yQZ2OteLu_zqbwdfUuRQsHGkczIjpqPY1-dTKNoaiGtfPJBTloI-YH7fzUV-bsMLwcy2Yjyti7A"
+
+app.base_url = "http://dev53.gaslightmedia.com/app.gaslightmedia.com/"
+app.base_secure_url = "https://dev53.gaslightmedia.com/app.gaslightmedia.com/"
+
+error.reporting[] = E_ALL
+error.reporting[] = E_NOTICE
+error.display = 1
+error.ident = ""
+error.conf.path = "/var/www/server/"
+
+database.params.host = "ds3"
+
+development = On
+
+email.owner = "leif@gaslightmedia.com"
+email.contact = "leif@gaslightmedia.com"
+email.addEventForm = "leif@gaslightmedia.com"
+email.enews = "leif@gaslightmedia.com"
+email.visitor_guide = "leif@gaslightmedia.com"
+email.applicationForm = "leif@gaslightmedia.com"
+email.reply_member_news = "leif@gaslightmedia.com"
+email.member_record_updates_advisor = "leif@gaslightmedia.com"
+email.member_forgot_password_email_reply_to = "leif@gaslightmedia.com"
+email.giftcert = "leif@gaslightmedia.com"
+email.giftcert_from = "leif@gaslightmedia.com"
+email.giftcert_secure = "leif@gaslightmedia.com"
+email.reply_to = "leif@gaslightmedia.com"
+email.banner_reports_admin = "leif@gaslightmedia.com"
+email.expiring_banner_notification = "leif@gaslightmedia.com"
+email.from_news = "leif@gaslightmedia.com"
+email.server_from = "leif@gaslightmedia.com"
+email.from_member_news = "leif@gaslightmedia.com"
+
+resources.version = "rand"
+resources.environment.javascript = "dev"
+resources.environment.css = "dev"
+
+[chuck : development]
+site_url = "http://192.168.44.7/www.soolocks.com/"
+
+mobile.link =
+mobile.hostname = On
+
+google.search.key = "ABQIAAAAFEik3hTZkksVQYtPm0OFmRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQhDw8ITgl-K4LjnHuSww6VQQFDnA"
+google.maps.key = "ABQIAAAAFEik3hTZkksVQYtPm0OFmRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQhDw8ITgl-K4LjnHuSww6VQQFDnA"
+
+app.base_url = "http://192.168.44.7/app.gaslightmedia.com/"
+
+database.params.host = "localhost"
+
+email.owner = "cscott@gaslightmedia.com"
+email.contact = "cscott@gaslightmedia.com"
+email.addEventForm = "cscott@gaslightmedia.com"
+email.enews = "cscott@gaslightmedia.com"
+email.visitor_guide = "cscott@gaslightmedia.com"
+email.applicationForm = "cscott@gaslightmedia.com"
+email.reply_member_news = "cscott@gaslightmedia.com"
+email.member_record_updates_advisor = "cscott@gaslightmedia.com"
+email.member_forgot_password_email_reply_to = "cscott@gaslightmedia.com"
+email.giftcert = "cscott@gaslightmedia.com"
+email.giftcert_from = "cscott@gaslightmedia.com"
+email.giftcert_secure = "cscott@gaslightmedia.com"
+email.reply_to = "cscott@gaslightmedia.com"
+email.banner_reports_admin = "cscott@gaslightmedia.com"
+email.expiring_banner_notification = "cscott@gaslightmedia.com"
+email.from_news = "cscott@gaslightmedia.com"
+email.server_from = "cscott@gaslightmedia.com"
+email.from_member_news = "cscott@gaslightmedia.com"
+
+[steve : development]
+site_url = "http://vserver/www.soolocks.com/"
+
+mobile.link =
+mobile.hostname = Off
+
+google.search.key = "ABQIAAAAFEik3hTZkksVQYtPm0OFmRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQhDw8ITgl-K4LjnHuSww6VQQFDnA"
+google.maps.key = "ABQIAAAAFEik3hTZkksVQYtPm0OFmRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQhDw8ITgl-K4LjnHuSww6VQQFDnA"
+
+app.base_url = "http://vserver/app.gaslightmedia.com/"
+app.base_secure_url = "https://vserver/app.gaslightmedia.com/"
+
+;file_server.secure = "http://192.168.56.101/image_server/"
+;file_server.unsecure = "http://192.168.56.101/image_server/"
+
+database.params.host = "localhost"
+
+email.owner = "steve+owner@localhost"
+email.contact = "steve+contact@localhost"
+email.addEventForm = "steve+eventForm@localhost"
+email.enews = "steve+enews@localhost"
+email.visitor_guide = "steve+visitor_guide@localhost"
+email.applicationForm = "steve+applicationForm@localhost"
+email.reply_member_news = "steve+reply_member_news@localhost"
+email.member_record_updates_advisor = "steve+member_updates@localhost"
+email.member_forgot_password_email_reply_to = "steve+member_forgot@localhost"
+email.giftcert = "steve+giftcert@localhost"
+email.giftcert_from = "steve+giftcert_from@localhost"
+email.giftcert_secure = "steve+giftcert_secure@localhost"
+email.reply_to = "steve+reply_to@localhost"
+email.banner_reports_admin = "steve+banner_reports@localhost"
+email.expiring_banner_notification = "steve+exp_banner@localhost"
+email.from_news = "steve+from_news@localhost"
+email.server_from = "server@gaslightmedia.com"
+email.from_member_news = "steve+from_member_news@localhost"
--- /dev/null
+; Production server configuration data
+[production]
+
+; Web Site Owner Information - for use by certain applications
+owner.name = "Gaslight Media"
+owner.short_name = "GLM"
+owner.address1 = "120 E. Lake St."
+owner.address2 = False
+owner.city = "Petoskey"
+owner.state = "MI"
+owner.zip = "49770"
+owner.country = "US"
+owner.phone = "231-487-0692"
+owner.toll_free = False
+
+; Home page id of site in the toolbox
+home_id = 1
+; Name to use in title tag and admin
+sitename = "soolocks"
+; used in contactdb to limit number of entries per list
+entries_per_page = 10
+; Turn short urls On or Off
+; requires .htaccess enabled
+short_urls = Off
+; Site is mobile enabled
+mobile_site = Off
+mobile_max_width = 600
+mobile_site_url = "http://m.***DOMAIN_GOES_HERE***/index.php?isMobile=yes"
+
+; 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]
--- /dev/null
+#contact,
+.webform {margin: 10px;}
+
+.req {color: #f00;}
+
+/* Main table */
+#contact table,
+.webform table {
+ background-color: #fff;
+ border: 1px solid #eee;
+ border-collapse: collapse;
+ }
+/* Any Table inside the form */
+#contact table table,
+.webform table table {
+ width: 100%;
+ margin-left: 0;
+ border: 0px solid #ddd;
+ }
+#contact table table td { border: 0px solid #ddd;}
+
+/* TD's */
+#contact td,
+.webform td {
+ padding: 3px;
+ font-family: arial, helvetica, sans-serif;
+ color: #000;
+ border: 1px solid #eee;
+ border-collapse: collapse;
+ }
+/* Left Cells */
+.labelcell {
+ background-color: transparent;
+ text-align: right;
+ padding-right: 10px;
+ padding-top: 3px;
+ white-space:nowrap;
+ width: 140px;
+ }
+/*Right Cells */
+.fieldcell {
+ padding-left: 4px;
+ width: 250px;
+ }
+
+/* Misc */
+textarea {width: 95%; height: 100px; display:block;}
+
+/* WARNINGS */
+#form-warning-top {
+ margin-top: 1em;
+ margin-bottom: 0.5em;
+ color: #f00;
+ font-size: 14px;
+ font-weight: bold;
+ }
+/* SHow hide instruction div */
+#contact table tr td .form-warning-inside,
+.webform table tr td .form-warning-inside {
+ display: none;
+ }
+#contact table tr.req td .form-warning-inside,
+.webform table tr.req td .form-warning-inside {
+ display: block;
+ background-image: url('../../../../images/error.gif');
+ background-repeat:no-repeat;
+ background-position: top left;
+ padding: 2px 2px 2px 22px;
+}
+
+/* Showing/hiding rows */
+/*invisible*/
+#contact table tr td.instructioncell,
+.webform table tr td.instructioncell {
+ width: 200px;
+ white-space: nowrap;
+ color: #fff;
+ }
+
+/*visible*/
+table tr.req {
+ border: 2px solid #f00;
+ background-color:#FCD6D4;
+ border-collapse: separate;
+ border-collapse: collapse;
+}
+/*color*/
+table tr.req td { background-color: #fcd6d4;}
+table tr.req td.labelcell { background-color: #FCD6D4; }
+table tr.req td.fieldcell { background-color: #FCD6D4; }
+table tr.req td.instructioncell { background-color: #FCD6D4; }
+table tr.req td.instructioncell {
+ padding: 4px;
+ padding-left: 20px;
+ background-image: url('../../../../images/error.gif');
+ background-repeat:no-repeat;
+ background-position: center left;
+ border-width: 0;
+ color: #000;
+ }
+.glmCheckBox {
+ width: 200px;
+ float: left;
+}
+.single-checkbox label.glmCheckBox {
+ width: auto;
+ float: none;
+}
--- /dev/null
+body {
+ background-color: #ff;
+ color: black;
+ font-family: verdana, arial, helvetica, sans-serif;
+}
+h1, h2 {
+ font-family: arial, helvetica, sans-serif;
+}
+h1 {
+ font-size: 18px;
+}
+h2 {
+ font-size: 16px;
+ margin-bottom: 5px;
+}
+p {
+ font-size: 12px;
+}
+.label {
+ font-weight: bold;
+ background-color: transparent;
+ text-align: right;
+ width: 200px;
+ padding: 5px;
+}
+.field {
+ background-color: #fff;
+ padding: 3px;
+}
+table.data {
+ background-color: #fff;
+ color: #000;
+ width: 500px;
+ border: 1px solid #ccc;
+ border-collapse: collapse;
+ margin-left: 20px;
+}
+table.data td {
+ border: 1px solid #ccc;
+ padding-left: 4px;
+ font-size: 12px;
+}
--- /dev/null
+/** Copyright 2005 Google Inc. All rights reserved. */
+
+/* the GSearchControl CSS Classes
+ * .gsc-control : the primary class of the control
+ */
+#searchcontrol {background-color:white; padding: 20px; clear: both;}
+.gsc-control {
+ width: auto;
+}
+
+.gsc-control div {
+ position: static;
+}
+
+/* control inputs
+ * .gsc-search-box : the container that hosts the text input area
+ * .gsc-input : the text input area
+ * .gsc-keeper : the save link below savable results
+ */
+form.gsc-search-box {
+ font-size: 13px;
+ margin-top : 0px;
+ margin-right : 0px;
+ margin-bottom : 4px;
+ margin-left : 0px;
+ width: 100%;
+}
+
+/*
+ * This table contains the input element as well as the search button
+ * Note that the search button column is fixed width, designed to hold the
+ * button div's background image
+ */
+table.gsc-search-box {
+ border-style : none;
+ border-width : 0px;
+ border-spacing : 0px 0px;
+ width : 100%;
+ margin-bottom : 2px;
+}
+
+table.gsc-search-box td {
+ vertical-align : middle;
+}
+
+td.gsc-search-button {
+ width : 1%;
+}
+
+td.gsc-clear-button {
+ width : 14px;
+ display: none;
+}
+
+table.gsc-branding {
+ border-style : none;
+ border-width : 0px;
+ border-spacing : 0px 0px;
+ width : 100%;
+ display: none;
+ }
+
+td.gsc-branding-text {
+ vertical-align : top;
+}
+
+td.gsc-branding-text div.gsc-branding-text {
+ padding-bottom : 2px;
+ text-align : right;
+ color : #676767;
+ font-size : 11px;
+ margin-right : 2px;
+}
+
+td.gsc-branding-img-noclear {
+ width : 51px;
+ vertical-align : bottom;
+}
+
+td.gsc-branding-img {
+ width : 65px;
+ vertical-align : bottom;
+}
+
+table.gsc-branding-vertical td.gsc-branding-text div.gsc-branding-text {
+ margin-right : 0px;
+ text-align : center;
+}
+
+table.gsc-branding-vertical td.gsc-branding-img-noclear {
+ text-align : center;
+}
+
+div.gsc-branding-img,
+div.gsc-branding-img-noclear,
+img.gsc-branding-img,
+img.gsc-branding-img-noclear {
+ padding-top : 1px;
+}
+
+img.gsc-branding-img,
+img.gsc-branding-img-noclear {
+ margin : 0 0 0 0;
+ padding-right : 0;
+ padding-left : 0;
+ padding-bottom : 0;
+ border : none;
+}
+
+input.gsc-search-button {
+ margin-left : 4px;
+}
+
+div.gsc-clear-button {
+ display : inline;
+ text-align : right;
+ margin-left : 4px;
+ margin-right : 4px;
+ padding-left : 10px;
+ background-repeat: no-repeat;
+ background-position: center center;
+ background-image: url('http://www.google.com/uds/css/clear.gif');
+ cursor : pointer;
+}
+
+/*
+ * Given that this is sitting in a variable width tabel cell, the idea is
+ * for it to consume the entire cell. The adjacent cell contains the search
+ * button and that is a fixed width cell.
+ */
+input.gsc-input {
+ padding-left : 2px;
+ border-style : solid;
+ border-width : 1px;
+ border-color : #BCCDF0;
+ width : 99%;
+}
+
+.gsc-keeper {
+ color: #3366cc;
+ text-decoration: underline;
+ font-size: 13px;
+ cursor: pointer;
+ font-weight: normal;
+
+ padding-left: 16px;
+ background-repeat: no-repeat;
+ background-position: 1px 3px;
+ background-image: url('http://www.google.com/uds/css/blue_check.gif');
+}
+.gsc-imageResult .gsc-keeper {
+ text-decoration: none;
+}
+
+/* each section of results has a results header table
+ * .gsc-resultsHeader : the header itseld
+ * td.twiddleRegionCell : the section that controls twiddleing of the section to expand/collapse
+ * td.configLabelCell : the twiddler that controls active configuration of a searcher (used in GlocalSearch)
+ * .gsc-twiddle : the twiddle image, note, this is a div that wraps gsc-title so that standard image replacement is feasible
+ * .gsc-twiddle-closed : class added to gsc-twiddle when the twiddler is in the closed state
+ * .gsc-twiddle-opened : class added to gsc-twiddle when the twiddler is in the opened state
+ * .gsc-title : the section's title (e.g., Web Results, etc.)
+ * .gsc-stats : contains the result counts
+ * .gsc-stats
+ */
+.gsc-resultsHeader {
+ clear: both;
+ width: 100%;
+ border-bottom: 1px solid #e9e9e9;
+ margin-bottom : 4px;
+}
+
+.gsc-resultsHeader td.gsc-twiddleRegionCell{
+ width: 75%;
+}
+
+.gsc-resultsHeader td.gsc-configLabelCell{
+ text-align: right;
+ width: 75%;
+}
+
+/*
+ * note that the next three classes are all joined together
+ * to implement the twiddle image. apps can substitute in their
+ * own images but will need to account for the image size here
+ * as well as in the left padding of the title element
+ *
+ * Note: uds provides the following images that work with the geometry/padding defined below
+ * to use these images simply over-ride the.gsc-twiddle-opened/-closed class and specify an alternate image
+ * or use an image of your own design
+ */
+.gsc-resultsHeader .gsc-twiddle{
+ margin-top: 4px;
+ display: inline;
+ cursor: pointer;
+ background-repeat: no-repeat;
+ background-position: 0px 2px;
+}
+.gsc-resultsHeader td.gsc-twiddle-closed div.gsc-twiddle{
+ background-image: url('http://www.google.com/uds/css/arrow_close.gif');
+}
+.gsc-resultsHeader td.gsc-twiddle-opened div.gsc-twiddle{
+ background-image: url('http://www.google.com/uds/css/arrow_open.gif');
+}
+
+.gsc-resultsHeader .gsc-title{
+ color: #676767;
+ margin-right: 10px;
+ padding-left: 14px;
+ display: inline;
+}
+
+.gsc-resultsHeader .gsc-stats {
+ color: #676767;
+ font-size: 11px;
+ font-weight: normal;
+ display : inline;
+}
+
+.gsc-resultsHeader td.gsc-twiddle-opened .gsc-stats {
+ display : none;
+}
+
+/*
+ * .gsc-results-selector : box surrounding individual selectors for 1, more, or all results
+ * .gsc-result-selector : an individual selector
+ * .gsc-one-result : single result selector
+ * .gsc-more-results : more (4) results selector
+ * .gsc-all-results : all results (8) selector
+ */
+.gsc-results-selector {
+ display : inline;
+}
+
+.gsc-resultsHeader td.gsc-twiddle-closed .gsc-results-selector {
+ display : none;
+}
+
+.gsc-result-selector {
+ cursor : pointer;
+ display : inline;
+ font-size : 13px;
+ padding-left : 13px;
+ background-repeat: no-repeat;
+ background-position: center left;
+}
+
+/* default mode is dark */
+.gsc-one-result {
+ background-image: url('http://www.google.com/uds/css/one-complex-dark.gif');
+}
+
+.gsc-more-results {
+ background-image: url('http://www.google.com/uds/css/more-complex-dark.gif');
+}
+
+.gsc-all-results {
+ background-image: url('http://www.google.com/uds/css/all-complex-dark.gif');
+ padding-right : 1px;
+}
+
+/* active mode is light */
+.gsc-one-result-active .gsc-one-result {
+ background-image: url('http://www.google.com/uds/css/one-complex-light-blue.gif');
+}
+
+.gsc-more-results-active .gsc-more-results {
+ background-image: url('http://www.google.com/uds/css/more-complex-light-blue.gif');
+}
+
+.gsc-all-results-active .gsc-all-results {
+ background-image: url('http://www.google.com/uds/css/all-complex-light-blue.gif');
+}
+
+.gsc-resultsHeader .gsc-configLabel{
+ color: #676767;
+ display: inline;
+ font-size: 11px;
+ cursor: pointer;
+}
+
+.gsc-resultsHeader td.gsc-configLabelCell span.gsc-twiddle-closed {
+ padding-right: 12px;
+ background-repeat: no-repeat;
+ background-position: center center;
+ background-image: url('http://www.google.com/uds/css/settings.gif');
+}
+
+
+/* tabbed mode of search control
+ * .gsc-tabsArea : the box containing all of the tabs
+ * .gsc-tabsAreaInvisible : same as above, but this is the state when search has been cleared
+ * .gsc-tabHeader : an individual tab
+ * .gsc-tabHeader.gsc-tabhActive : the active tab
+ * .gsc-tabHeader.gsc-tabhInactive : an inactive tab
+ * .gsc-tabData : the data area/box containg results and header data for each tab
+ * .gsc-tabData.gsc-tabdActive : the data area for the active tab
+ * .gsc-tabData.gsc-tabdInactive : the data area for inactive tabs
+ */
+.gsc-tabsArea {
+ clear: both;
+ margin-top: 6px;
+ display: none;
+ }
+
+.gsc-tabsAreaInvisible {
+ display : none;
+ }
+
+.gsc-tabHeader {
+ display: inline;
+ cursor: pointer;
+ padding-left: 6px;
+ padding-right: 6px;
+ margin-right: 2px;
+ }
+
+.gsc-tabHeader.gsc-tabhActive {
+ border-left: 1px solid #e9e9e9;
+ border-right: 1px solid #e9e9e9;
+ border-top: 2px solid #ff9900;
+ color: black;
+ }
+
+.gsc-tabHeader.gsc-tabhInactive {
+ border-left: 1px solid #e9e9e9;
+ border-right: 1px solid #e9e9e9;
+ border-top: 2px solid #e9e9e9;
+ background: #e9e9e9;
+ color: #676767;
+ }
+
+.gsc-tabData.gsc-tabdActive {
+ display: block;
+ }
+
+.gsc-tabData.gsc-tabdInactive {
+ display: none;
+ }
+
+/* tab specific results header supression
+ * - no twiddle, tabbed mode runs in full expand mode
+ * - no title
+ * - no stats
+ */
+.gsc-tabData .gsc-resultsHeader .gsc-title {
+ display: none;
+ }
+
+.gsc-tabData .gsc-resultsHeader .gsc-stats {
+ display: none;
+ }
+
+.gsc-tabData .gsc-resultsHeader .gsc-results-selector {
+ display : none;
+}
+
+
+
+/* the results for each section
+ * .gsc-resultsbox-{visible,invisible} : a complete-collection of results including headers
+ * .gsc-results : the collection of results for a given searcher
+ * .gsc-result : a generic result within the control. each result has this class, as well as .gsc-xxxResult where xxx is web, image, local, blog, etc.
+ */
+.gsc-resultsbox-visible {
+ display : block;
+}
+
+.gsc-resultsbox-invisible {
+ display : none;
+}
+
+.gsc-results {
+ clear: both;
+ padding-bottom: 2px;
+}
+
+.gsc-result {
+ margin-bottom: 10px;
+}
+
+.gsc-result .gs-title {
+ height: 1.4em;
+ overflow: hidden;
+ }
+
+/* specialized, result type specific, fine grained controls */
+.gsc-result div.gs-watermark {
+ display: none;
+}
+
+/* Ads
+ * inline the title div so that we can have an adjecent ad marker
+ * in the control, the ad-marker is supressed since ads are already positioned
+ * underneath a results divider
+ */
+.gsc-webResult a div.gs-title {
+ display: inline;
+}
+.gsc-results .gsc-result img.gs-ad-marker {
+ display: none;
+}
+
+/* Standard configuration div/form */
+div.gsc-config {
+ border: 1px solid #e9e9e9;
+ margin-top: 0px;
+ margin-bottom: 10px;
+ padding-top : 2px;
+ padding-left : 6px;
+ padding-right : 6px;
+ padding-bottom : 6px;
+}
+
+form.gsc-config {
+ margin-bottom : 0px;
+}
+
+.gsc-configSetting {
+ margin-top : 6px;
+ }
+
+.gsc-configSetting_Label {
+ color: #676767;
+ }
+
+.gsc-configSettingInput {
+ color: #676767;
+ border: 1px solid #e9e9e9;
+ width: 75%;
+ }
+
+.gsc-configSettingCheckbox {
+ color: #676767;
+ margin-right: 6px;
+ }
+
+.gsc-configSettingCheckboxLabel {
+ display : inline;
+ color: #676767;
+ }
+
+div.gsc-configSettingSubmit {
+ margin-top : 8px;
+ text-align : right;
+}
+
+input.gsc-configSettingSubmit {
+ display: inline;
+ font-size: 11px;
+ cursor: pointer;
+}
+
+
+/* Image Search
+ * - support for horizontal and vertical orientation
+ * - title, url, and size supression
+ */
+.gsc-results.gsc-imageResult .gsc-imageResult.horizontal{
+ float: left;
+ width: 65px;
+ margin-bottom: 4px;
+ margin-right: 8px;
+ text-align: center;
+}
+
+.gsc-results.gsc-imageResult .gsc-imageResult.horizontal .gs-imageResult {
+ height: 41px;
+}
+
+.gsc-results.gsc-imageResult .gsc-imageResult.vertical{
+ float: none;
+ margin-bottom: 4px;
+ margin-right: 8px;
+ text-align: left;
+}
+
+.gsc-results.gsc-imageResult .gsc-imageResult.horizontal .gsc-keeper {
+ background-position: center;
+}
+
+.gsc-imageResult .gs-title {
+ display: none;
+}
+.gsc-imageResult .gs-visibleUrl {
+ display: none;
+}
+.gsc-imageResult .gs-size {
+ display: none;
+}
+
+/* Video Search
+ * - metadata, publisher small font
+ * - single line title
+ */
+
+.gsc-videoResult .gs-videoResult .gs-metadata {
+ font-size: 11px;
+}
+
+.gsc-videoResult .gs-videoResult .gs-title {
+ line-height: 1.3em;
+ height: 1.3em;
+ overflow: hidden;
+ }
+
+.gsc-videoResult .gs-videoResult .gs-snippet {
+ line-height: 1.3em;
+ max-height: 2.6em;
+ overflow: hidden;
+ }
+
+/*** End of Control, Begin Results ***/
+
+/* generic, cross cutting result style
+ * - in the form of .gs-result .gs-xxx where xxx is the generic style
+ * .gs-title : typically the first line of a result, typically a link, image results over ride this, since for image results, the image is the link
+ * .gs-divider : typically seperates results from ads
+ * .gs-visibleUrl : typically the last line of a result, displayed in green. sometimes a link (like in blog search)
+ * .gs-clusterUrl : for news, and other similar services, this is a cluster of additional results
+ * img.gs-image : an actial image in a result
+ * .gs-phone : a phone number
+ * .gs-address : an address (includes street, city, region, country)
+ * .gs-streetAddress : a street (including #)
+ * .gs-city : a city
+ * .gs-region : a region (zip code, area, etc.)
+ * .gs-country : a country
+ * .gs-snippet : snippetized content
+ * .gs-watermark : indicator that user selected this result
+ * .gs-metadata : generic metadata, e.g.,
+ * .gs-image-box : generic container for a result's image (within a table)
+ * .gs-text-box : generic container for a result's text content (within a table). Note that this class, and image-box are only used in video
+ */
+.gs-result .gs-title,
+.gs-result .gs-title * {
+ color: #0000cc;
+ text-decoration: underline;
+}
+
+.gs-divider {
+ padding-bottom: 8px;
+ text-align: center;
+ color: #676767;
+}
+
+.gs-result a.gs-visibleUrl,
+.gs-result .gs-visibleUrl {
+ color: #008000;
+ text-decoration: none;
+}
+
+/* relative and absolute dates, not, news inlines these */
+.gs-relativePublishedDate,
+.gs-publishedDate {
+ color: #6f6f6f;
+ text-decoration: none;
+}
+.gs-result a.gs-clusterUrl,
+.gs-result .gs-clusterUrl {
+ color: #008000;
+ text-decoration: none;
+ cursor: pointer;
+}
+
+.gs-newsResult .gs-publisher {
+ color: #6f6f6f;
+ display : inline;
+ text-decoration: none;
+}
+
+.gs-bookResult .gs-author {
+ color: #6f6f6f;
+}
+
+/*
+ * For news results there are two dates...
+ * The relative date is visible while in the
+ * search control and the published date
+ * is visible when clipped. Why? It doesn't
+ * make sense to say 4 hours ago for a clipped
+ * result...
+ */
+
+/* establish the base style */
+.gs-newsResult .gs-relativePublishedDate,
+.gs-newsResult .gs-publishedDate {
+ display : inline;
+ margin-left : 4px;
+}
+
+/* base styling for relative date is none */
+.gs-blogResult .gs-relativePublishedDate,
+.gs-newsResult .gs-relativePublishedDate {
+ display : none;
+}
+
+/* suppress publishedDate while in the control */
+.gsc-blogResult .gs-blogResult .gs-publishedDate,
+.gsc-newsResult .gs-newsResult .gs-publishedDate {
+ display : none;
+}
+
+/* enable relativePublishedDate while in the control */
+.gsc-blogResult .gs-blogResult .gs-relativePublishedDate,
+.gsc-newsResult .gs-newsResult .gs-relativePublishedDate {
+ display : inline;
+}
+
+.gs-newsResult .gs-location {
+ color: #6f6f6f;
+ display : inline;
+ text-decoration: none;
+}
+
+.gs-result img.gs-image {
+ vertical-align : middle;
+ border : 1px solid #0000cc;
+}
+
+.gs-result div.gs-phone {}
+
+.gs-result .gs-directions,
+.gs-result .gs-directions * {
+ color: #3366cc;
+ font-weight: normal;
+ text-decoration : underline;
+}
+
+.gs-videoResult a.gs-publisher,
+.gs-videoResult .gs-publisher {
+ color: #008000;
+ text-decoration: none;
+}
+
+.gs-result a {
+ cursor: pointer;
+}
+
+.gs-result .gs-address {
+}
+
+.gs-result .gs-snippet {
+}
+
+.gs-result .gs-watermark{
+ font-size: 10px;
+ color: #7777cc;
+}
+
+div.gs-results-attribution {
+ text-align : center;
+ margin-bottom : 4px;
+}
+
+div.gs-results-attribution,
+div.gs-results-attribution * {
+ font-size : 10px;
+ color : #676767;
+ text-decoration : none;
+}
+
+div.gs-results-attribution a {
+ color: #0000cc;
+ cursor : pointer;
+}
+
+div.gs-results-attribution a:hover {
+ text-decoration : underline;
+}
+
+.gs-result .gs-metadata{
+ color: #676767;
+}
+
+/* searcher specific styling for
+ * - web ad
+ * - web
+ * - local
+ * - image (none)
+ * - blog (none)
+ * - video (none)
+ */
+
+/* webAd search specific over rides
+ * .gs-ad-marker : disabled in control, but on in green to indicate clipped result is an ad
+ */
+.gs-localAd img.gs-ad-marker,
+.gs-webAd img.gs-ad-marker {
+ padding-left: 4px;
+}
+
+.gs-localAd a.gs-visibleUrl div.gs-visibleUrl,
+.gs-webAd a.gs-visibleUrl div.gs-visibleUrl {
+ display : none;
+}
+
+/* default is to not show long mode visible urls
+ * apps should selectively enable this while disabling
+ * div.gs-visibleUrl-short
+ */
+.gs-webResult div.gs-visibleUrl-long {
+ width : 100%;
+ overflow : hidden;
+ display : block;
+}
+
+.gs-webResult div.gs-visibleUrl-short {
+ display: none;
+}
+
+/* local search specific over rides
+ * - city, region displayed inline
+ * - country supressed
+ * - small font size for info window's
+ */
+
+.gs-localAd div.gs-address * {
+ color : #676767;
+}
+
+.gs-localAd div.gs-street {
+ display: inline;
+}
+
+div.gs-city {
+ display: inline;
+}
+
+div.gs-region {
+ display: inline;
+}
+
+div.gs-country {
+ display: none;
+}
+
+div.gs-infoWindow * {
+ font-size: 11px;
+ }
+
+/* video search specific over rides
+ * - align the table data
+ * - default image width garuntee
+ * - appropriate cell seperation
+ */
+
+/* todo(markl): workaround until gre in gmail fixes his styles */
+.gs-videoResult * {
+ font-size: 13px;
+ }
+
+/*
+.gs-videoResult td .gs-image {
+ vertical-align : middle;
+}
+
+.gs-videoResult td.gs-image-box {
+ background-color : #000000;
+}*/
+
+.gs-videoResult td div.gs-image-box {
+ width : 110px;
+ height : 78px;
+}
+
+.gs-videoResult td div.gs-text-box {
+ vertical-align: top;
+ margin-left: 4px;
+ }
+
+
+/* book search specific over rides
+ * - default image width garuntee
+ * - appropriate cell seperation
+ */
+.gs-bookResult td div.gs-image-box {
+ width : 75px;
+ height : 90px;
+}
+
+.gs-bookResult td div.gs-text-box {
+ vertical-align: top;
+ margin-left: 4px;
+ }
+
+.gs-bookResult img.gs-image,
+.gs-bookResult img {
+ border-spacing : 0px 0px;
+ border : none;
+}
+
+.gs-bookResult table.gs-image-box {
+ border-style : none;
+ border-width : 0px;
+ border-spacing : 0px 0px;
+}
+
+.gs-bookResult td.gs-pages img {
+ height : 7px;
+ width : 45px;
+}
+
+.gs-bookResult td.gs-page-edge img {
+ height : 7px;
+ width : 11px;
+}
+
+.gs-bookResult td.gs-shadow {
+ vertical-align : bottom;
+}
+
+.gs-bookResult td.gs-image img {
+ height : 80px;
+}
+.gsc-ad-box { display:none;}
+
+
+/* trailing cursor section
+ */
+.gsc-imageResult .gsc-cursor-box {
+ clear : both;
+}
+
+.gsc-results .gsc-cursor-box .gsc-trailing-more-results {
+ margin-bottom : 0px;
+ display : inline;
+}
+
+.gsc-results .gsc-cursor {
+ display : inline;
+}
+
+.gsc-results .gsc-cursor-box {
+ margin-bottom : 10px;
+}
+
+.gsc-results .gsc-cursor-box .gsc-cursor-page {
+ cursor : pointer;
+ color : #000000;
+ text-decoration: underline;
+ margin-right : 8px;
+ display : inline;
+}
+
+.gsc-results .gsc-cursor-box .gsc-cursor-current-page {
+ color : #A90A08;
+ font-weight : bold;
+ text-decoration: none;
+}
+
+.gsc-resultsHeader *{display:none;}
--- /dev/null
+body .imagecaption {
+ position: relative;
+ width: auto;
+ bottom: auto;
+ background: url("../../assets/imagecaptionBg.gif") no-repeat bottom center !important;
+ padding: 0 0 10px 0;
+ margin-top: 4px;
+ }
+
--- /dev/null
+
+#sitemap h2 {
+ font-size: 14px;
+ font-weight: bold;
+ margin: 20px 0 5px 0;
+ padding: 5px;
+ border-bottom: 1px solid #000;
+ }
+#sitemap h2 a {
+ color: #000;
+ }
+#sitemap .row {
+ clear: both;
+ overflow: hidden;
+ }
+.row ol, .row li {
+ list-style-image: none;
+ list-style-type: none;
+ text-transform: capitalize;
+ font-size: 12px;
+ font-weight: normal;
+ margin: 0;
+ padding: 0;
+}
+#sitemap a {
+ border-bottom: none;
+ text-decoration: none;
+ color: #666;
+ }
+#sitemap a:hover {
+ text-decoration: underline;
+ color: #00F;
+ }
+#sitemap a:active {
+ text-decoration: underline;
+ color: #00F;
+ }
+.row > ol {
+ float: left;
+ margin-right: 3%;
+ /* width: 30% */
+ }
+.row > ol > li {
+ margin: 5px;
+ font-weight: bold;
+ }
+.row > ol > li > ol > li {
+ margin: 5px 0 5px 20px;
+ }
\ No newline at end of file
--- /dev/null
+#! /bin/bash
+convert='/usr/bin/convert'
+composite='/usr/bin/composite'
+
+for file in original/*
+do
+ temp=`basename $file`
+ $convert -scale '287>' $file resized/$temp
+ $convert -scale '210>' $file midsized/$temp
+ $convert -scale '120>' $file thumb/$temp
+
+ echo $temp
+done
--- /dev/null
+<?php
+$includeFunctions = false;
+require_once 'setup.phtml';
+if ($_REQUEST['siteMapXml'] == '1') {
+ // Generate the sitemap
+ $siteMapXml = new Toolkit_SiteMapXml(
+ Toolkit_Database::getInstance()
+ );
+ $xml = $siteMapXml->getXmlSitemap();
+
+ // Save the sitemap into the root of the site
+ $fp = fopen(BASE_PATH.'sitemap.xml', 'w');
+ fwrite($fp, $xml);
+ fclose($fp);
+
+ // Output the sitemap as XML and quit
+ header("content-type: text/xml");
+ header('Content-Length: '.strlen($xml));
+ header('Content-Disposition: attachment;filename="sitemap.xml"');
+ echo $xml;
+ exit;
+}
+$dbh = Toolkit_Database::getInstance();
+if ( defined("SHORT_URLS")
+ && SHORT_URLS
+ && isset($_GET['glmPage'])
+ && $_GET['glmPage']
+) {
+ $shortURL = new Toolkit_ShortURL($dbh);
+ if (!$catid = $shortURL->getShortUrlId($_GET['glmPage'])) {
+ $catid = HOME_ID;
+ }
+ $_REQUEST['catid'] = $_GET['catid'] = $catid;
+} elseif ($catid = filter_input(INPUT_GET, 'catid', FILTER_VALIDATE_INT)) {
+ // do nothing, catid set and filtered
+} else {
+ $catid = HOME_ID;
+}
+$qfKeys
+ = array_filter(
+ array_keys($_REQUEST),
+ create_function('$key', 'return preg_match("/_qf/", $key);')
+ );
+if ($catid != HOME_ID) {
+ require_once 'Text/CAPTCHA.php';
+ require_once 'Text/CAPTCHA/Driver/Image.php';
+} elseif (empty($qfKeys)) {
+ $_REQUEST['catid'] = $_GET['catid'] = $catid;
+}
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+if (isset($qfKeys) && !empty($qfKeys)) {
+ if (ctype_digit($_SESSION['_regWizard_container']['values']['page1']['catid'])) {
+ $catid = $_SESSION['_regWizard_container']['values']['page1']['catid'];
+ } elseif (ctype_digit($_REQUEST['catid'])) {
+ $catid = $_REQUEST['catid'];
+ }
+ $_REQUEST['catid'] = $_POST['catid'] = $_GET['catid'] = $catid;
+}
+require_once 'setup_functions.phtml';
+
+
+// If Ticketing is enabled, run ticket login
+if (defined('TICKETING') && TICKETING) {
+ require_once 'ticketing/ticket_login.inc';
+}
+
+// Create a new registry so we don't pollute the global namespace
+$registry = new Toolkit_Registry;
+
+$registry->cacheOptions = $GLOBALS['cacheOptions'];
+$registry->flexyOptions = $GLOBALS['flexyOptions'];
+$registry->catid = $catid;
+$registry->dbh = $dbh;
+$registry->logger = Toolkit_Logger::getLogger();
+
+if (defined('SHOP_PAGE_ID') && $catid == SHOP_PAGE_ID) {
+ // Initiate HTML_Template_Flexy.
+ $template = new HTML_Template_Flexy($registry->flexyOptions);
+ $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+ new Toolkit_Toolbox_PageGatewayPublish(
+ $registry->dbh
+ )
+ );
+ $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+ new Toolkit_Toolbox_PageGatewayPublishFactory(
+ $registry->dbh
+ )
+ );
+ // 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,
+ new Toolkit_Toolbox_PageGatewayPublishFactory(
+ $registry->dbh
+ ),
+ new Toolkit_Toolbox_ParagraphGatewayPublishFactory(
+ $registry->dbh
+ ),
+ new Toolkit_Template_Navigation_Factory(),
+ $keywordReplacement,
+ $registry->catid
+ );
+ $glmPage->fetchPage();
+ ob_start();
+ include 'shop.php';
+ $glmPage->toolboxContent = ob_get_contents();
+ ob_end_clean();
+
+ $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);
+} else {
+ // Create a router so we can get where we need to be.
+ $registry->router = new Toolkit_Router($registry);
+ $registry->router->setPath(BASE . 'Toolkit/Template');
+ $registry->router->setApplication('Template');
+
+ $registry->router->loader();
+}
--- /dev/null
+<?php
+/**
+ * Media Toolbox(R)
+ *
+ * Setup.phtml file includes the functions that were in the functions.inc
+ * and siteinfo.inc file into one file.
+ * All set up stuff is on the top of the page.
+ *
+ * PHP version 5
+ *
+ * @category Gaslight_Media_Website
+ * @package Gaslight_Media
+ * @header Gaslight Media Toolbox
+ * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @author Steve Sutton <steve@gaslightmedia.com>
+ * @license http://www.gaslightmedia.com Gaslightmedia
+ * @version $Id: setup.phtml,v 1.102 2010/08/10 17:43:11 jamie Exp $
+ * @release SVN: $Id: $
+ * @link http://www.gaslightmedia.com
+ */
+
+/**
+ * DO NOT EDIT THIS SECTION
+ */
+// Find where this file is located
+$BASE_PATH = dirname(__FILE__);
+$php_version = phpversion();
+// If php5 or above
+if (version_compare($php_version, '5.0.0', '>')) {
+ $CALLED_FROM_DIR = substr(dirname($_SERVER['SCRIPT_FILENAME']), strlen($BASE_PATH));
+ define('GLM_HOST_ID', $_ENV['GLM_HOST_ID']);
+ define('PHP5', true);
+} else {
+ $CALLED_FROM_DIR = substr(dirname($HTTP_SERVER_VARS['PATH_TRANSLATED']), strlen($BASE_PATH));
+ define('GLM_HOST_ID', $_SERVER['GLM_HOST_ID']);
+ define('PHP5', false);
+}
+
+if (($x = strlen($CALLED_FROM_DIR)) > 0) {
+ $base_url = $_SERVER['HTTP_HOST'] . substr(dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($CALLED_FROM_DIR));
+} else {
+ $script_name_dir = dirname($_SERVER['SCRIPT_NAME']);
+ if ($script_name_dir == '/') {
+ $script_name_dir = '';
+ }
+ $base_url = $_SERVER['HTTP_HOST'] . $script_name_dir;
+}
+// Added to strip any trailing /'s to make sure we don't end up with many
+$base_url = preg_replace('|/*$|', '', $base_url);
+$BASE_URL = "http://$base_url";
+
+if (!isset($DEBUG)) {
+ $DEBUG = (isset($mysecretcode) && $mysecretcode == 1234);
+}
+$securePagesArray = array();
+define('SECURE_PAGES', serialize($securePagesArray));
+$nonMobilePagesArray = array();
+define('NON_MOBILE_PAGES', serialize($nonMobilePagesArray));
+/**
+ * URI used for the root of the site
+ */
+define('BASE_URL', "$BASE_URL/");
+/**
+ * Another way of calling the BASE_URL constant
+ */
+define('URL_BASE', "$BASE_URL/");
+/**
+ * root directory path of site in filesystem
+ */
+define('BASE_PATH', "$BASE_PATH/");
+/**
+ * Another way of calling the BASE_PATH constant
+ */
+define('BASE', "$BASE_PATH/");
+
+// GLM App repository config {{{
+switch ($_ENV['GLM_HOST_ID']) {
+case 'PRODUCTION' : // {{{
+ $glmAppBase = '/var/www/server/app.gaslightmedia.com/';
+ break; // }}}
+case 'DEVELOPMENT' : // {{{
+ $glmAppBase = '/var/www/server/app.gaslightmedia.com/';
+ break; // }}}
+case 'STEVE' : // {{{
+ $glmAppBase = '/var/www/server/app.gaslightmedia.com/';
+ break; // }}}
+case 'CHUCK' : // {{{
+ $glmAppBase = '/var/www/server/app.gaslightmedia.com/';
+ break; // }}}
+case 'JOHN' : // {{{
+ $glmAppBase = '/var/www/server/app.gaslightmedia.com/';
+ break; // }}}
+default : // {{{
+ die('<p>Your request could not be completed at this time, please try again later!</p>');
+ break; // }}}
+} // }}}
+/**
+ * Path to the common GLM application repository
+ */
+define('GLM_APP_BASE', $glmAppBase);
+// {{{ Path Configuration
+
+// explode the current include_path by forward slashes (/),
+// colons (:), or periods (.)
+$path = preg_split('(\/|:|\.)', get_include_path());
+if (!in_array(GLM_APP_BASE . 'glmPEAR', $path)) {
+ set_include_path(
+ GLM_APP_BASE . 'glmPEAR' . PATH_SEPARATOR . get_include_path()
+ );
+}
+
+if (!in_array(GLM_APP_BASE . 'glmZend', $path)) {
+ set_include_path(
+ GLM_APP_BASE . 'glmZend/1.10.2/library' . PATH_SEPARATOR . get_include_path()
+ );
+}
+
+// Include path to geocode API
+if (!in_array(GLM_APP_BASE . 'geocode', $path)) {
+ set_include_path(
+ GLM_APP_BASE . 'geocode' . PATH_SEPARATOR . get_include_path()
+ );
+}
+
+// }}}
+
+// {{{ autoloader
+// nullify any existing autoloads
+spl_autoload_register(null, false);
+// specify extensions that may be loaded
+spl_autoload_extensions();
+
+// {{{ classLoader()
+
+/**
+ * spl autoloader callback function
+ *
+ * @param string $className Name of the class to autoload
+ *
+ * @return false on error
+ */
+function classLoader($className)
+{
+ switch ($className) {
+ case 'GLM_DB' :
+ require_once BASE . 'classes/class_db.inc';
+ break;
+
+ case 'GLM_TOOLBOX' :
+ require_once BASE . 'classes/class_toolbox.inc';
+ break;
+
+ case 'GLM_TEMPLATE' :
+ require_once BASE . 'classes/class_template.inc';
+ break;
+
+ case 'GLM_EVENTS' :
+ require_once BASE . 'classes/class_events.inc';
+ break;
+
+ case 'guide' :
+ require_once BASE . 'classes/class_visitor_guide_form.inc';
+ break;
+
+ case 'event_form' :
+ require_once BASE . 'classes/class_event_form.inc';
+ break;
+
+ case 'html_quickform_rule_phone' :
+ case 'html_quickform_rule_email' :
+ case 'html_quickform_rule_zip' :
+ case 'html_quickform_rule_state' :
+ case 'html_quickform_rule_banwords' :
+ case 'html_quickform_rule_date' :
+ case 'html_quickform_rule_image' :
+ case 'html_quickform_rule_image2' :
+ case 'html_quickform_rule_memberimage' :
+ case 'html_quickform_rule_memberpackage' :
+ case 'html_quickform_rule_memberlogo' :
+ case 'html_quickform_rule_memberfile' :
+ case 'html_quickform_rule_amenity' :
+ case 'html_quickform_rule_banner' :
+ $path = explode('_', $className);
+ $className = ucfirst(end($path));
+ require_once GLM_APP_BASE . "glmPEAR/HTML/QuickForm/Rule/$className.php";
+ break;
+
+ default :
+ // Since our old naming conventions conflict w/ the pear
+ // naming conventions.
+ // Check to see what we're trying to call by checking if the
+ // file/class exits in the PEAR sturcture.
+ $class = implode('/', explode('_', $className));
+ if (file_exists(GLM_APP_BASE . "glmPEAR/$class.php")) {
+ require_once GLM_APP_BASE . "glmPEAR/$class.php";
+ } elseif (file_exists(GLM_APP_BASE . "glmZend/1.10.2/library/$class.php")) {
+ require_once GLM_APP_BASE . "glmZend/1.10.2/library/$class.php";
+ } elseif (file_exists(GLM_APP_BASE . "geocode/$class.php")) {
+ require_once GLM_APP_BASE . "geocode/$class.php";
+ } elseif (file_exists(GLM_APP_BASE . "$class.php")) {
+ require_once GLM_APP_BASE . "$class.php";
+ } elseif (file_exists(BASE . "$class.php")) {
+ require_once BASE . "$class.php";
+ } elseif (file_exists(BASE . "classes/$className.php")) {
+ require_once BASE . "classes/$className.php";
+ } else {
+ // Add check to search our entire search path for
+ // the desired class.
+ // fixes phpunit dying for missing classes.
+ $includePath = get_include_path();
+ if (strpos($includePath, PATH_SEPARATOR) !== false) {
+ if ( ($i = explode(PATH_SEPARATOR, $includePath))
+ && count($i) > 0
+ ) {
+ foreach ($i as $j) {
+ if (file_exists("{$j}/{$class}.php")) {
+ require_once "{$j}/{$class}.php";
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+ break;
+ }
+}
+
+// }}}
+
+// register the loader functions
+spl_autoload_register('classLoader');
+
+// }}}
+
+set_error_handler(array('Toolkit_Logger', 'errorHandler'));
+if (!date_default_timezone_set('America/Detroit')) {
+ $logger =& Toolkit_Logger::getLogger();
+ $logger->warning('Default time zone not getting set.');
+}
+
+$serverConfig = new Zend_Config_Ini(
+ BASE . 'config/server.ini',
+ strtolower($_ENV['GLM_HOST_ID'])
+);
+//$serverConfig = Toolkit_ServerConfig::getInstance();
+
+$siteConfig = new Zend_Config_Ini(
+ BASE . 'config/site.ini',
+ strtolower($_ENV['GLM_HOST_ID'])
+);
+//$siteConfig = Toolkit_SiteConfig::getInstance();
+
+$applicationConfig = new Zend_Config_Ini(
+ BASE . 'config/application.ini',
+ strtolower($_ENV['GLM_HOST_ID'])
+);
+//$applicationConfig = Toolkit_ApplicationConfig::getInstance();
+
+/**
+ * Home page id of site
+ */
+define('HOME_ID', $siteConfig->home_id);
+/**
+ * Name used in title tag, admin area and emails
+ */
+define('SITENAME', $siteConfig->sitename);
+/**
+ * DB library type
+ */
+define('DB_TYPE', $serverConfig->database->type);
+/**
+ * Default error message
+ */
+define('DB_ERROR_MSG', $serverConfig->database->error->message);
+/**
+ * Default per page number
+ */
+define('ENTRIES_PER_PAGE', $siteConfig->entries_per_page);
+/**
+ * Turn on/off short url
+ */
+define('SHORT_URLS', $siteConfig->short_urls);
+/**
+ * Site has banner ad application?
+ */
+define('BANNERS', $applicationConfig->bannerdb->application);
+/**
+ * Site has Shop application?
+ */
+define('RETAIL_SHOP', $applicationConfig->retailShop->application);
+/**
+ * Shop Application is set for this page
+ */
+define('SHOP_PAGE_ID', null);
+/**
+ * Site has contact db application?
+ */
+define('CONTACT_DB', $applicationConfig->contactdb->application);
+/**
+ * Sets the first year available in the year select lists in
+ */
+define('CONTACTS_FIRST_YEAR', $applicationConfig->contactdb->first_year);
+/**
+ * Used in the email out for contact DB
+ */
+define('PRODUCTION_MODE', $applicationConfig->contactdb->production_mode);
+/**
+ * Turn ON for html emails
+ */
+define('HTML_EMAIL', $applicationConfig->contactdb->html_email);
+/**
+ * Login Id for StreamSend account
+ */
+define('STREAMSEND_LOGIN_ID', $applicationConfig->contactdb->streamsend->login);
+/**
+ * key for StreamSend account
+ */
+define('STREAMSEND_KEY', $applicationConfig->contactdb->streamsend->key);
+/**
+ * StreamSend Account Name
+ */
+define('STREAMSEND_ACCOUNT_NAME', $applicationConfig->contactdb->streamsend->account_name);
+/**
+ * StreamSend Audience Number
+ */
+define('STREAMSEND_AUDIENCE', $applicationConfig->contactdb->streamsend->audience);
+/**
+ * Site uses streamsend module?
+ */
+define(
+ 'STREAMSEND_FORMS_API',
+ $applicationConfig->contactdb->streamsend->application
+);
+/**
+ * Enable the form to send data to constant contact
+ */
+define('CONSTANT_CONTACT', $applicationConfig->constantcontact->application);
+/**
+ * Login for API (required)
+ */
+define('CONSTANT_CONTACT_LOGIN', $applicationConfig->constantcontact->login);
+/**
+ * Password for API (required)
+ */
+define('CONSTANT_CONTACT_PASSWORD', $applicationConfig->constantcontact->password);
+/**
+ * API Key (required)
+ */
+define('CONSTANT_CONTACT_APIKEY', $applicationConfig->constantcontact->apikey);
+/**
+ * API Path (Required)
+ */
+define('CONSTANT_CONTACT_APIPATH', $applicationConfig->constantcontact->apipath);
+define(
+ 'CONSTANT_CONTACT_LIST',
+ serialize($applicationConfig->constantcontact->list->toArray())
+);
+/**
+ * Coupons Database Installed?
+ */
+define('COUPONS', $applicationConfig->coupons->application);
+/**
+ * Site has event db application?
+ */
+define('EVENT_DB', $applicationConfig->eventdb->application);
+/**
+ * Site has CommonApps EventCalendar application?
+ */
+define('COMMON_EVENTS', $applicationConfig->eventdb->commonEvents);
+/**
+ * Page for the event calendar
+ */
+define('EVENT_PAGE', $applicationConfig->eventdb->event_page);
+/**
+ * Site has home page Events?
+ */
+define('HOME_EVENTS', $applicationConfig->eventdb->home_events);
+/**
+ * Site has google search api key?
+ */
+define('GOOGLE_SEARCH', $applicationConfig->google->search->application);
+/**
+ * Site has CommonApps GLMSearch application?
+ */
+define('GLM_SEARCH', $applicationConfig->glmsearch->application);
+define('GLM_SEARCH_SITE', $applicationConfig->glmsearch->site);
+define('GLM_SEARCH_LOGIN', $applicationConfig->glmsearch->login);
+define('GLM_SEARCH_KEY', $applicationConfig->glmsearch->key);
+/**
+ * Site has home page Headlines?
+ */
+define('HOME_HEADLINES', $applicationConfig->headlines->application);
+/**
+ * Site has Event Management
+ */
+define('EVENT_MANAGEMENT', $applicationConfig->event_management->application);
+define('EVENT_MANAGEMENT_HOME_PAGE', $applicationConfig->event_management->home_page);
+define('EVENT_MANAGEMENT_MEMBERS_PAGE', $applicationConfig->event_management->members_only_page);
+/**
+ * Member Database Installed?
+ */
+define('MEMBERS_DB', $applicationConfig->memberdb->application);
+/**
+ * Members login page catid
+ */
+define('MEMBERS_CATEGORY', $applicationConfig->memberdb->login_page);
+/**
+ * Toolbox page id for splash page when members log into members only area
+ */
+define('MEMBERS_ONLY_HOME_PAGE', $applicationConfig->memberdb->members->home_page);
+/**
+ * Toolbox page id for edit profile form in members only area
+ */
+define('MEMBERS_PROFILE_FORM_PAGE', $applicationConfig->memberdb->members->profile_form_page);
+/**
+ * Toolbox page id for coupon module in members only area
+ */
+define('MEMBERS_COUPONS_PAGE', $applicationConfig->memberdb->members->coupons->page);
+/**
+ * Toolbox page id for coupon module in members only area
+ */
+define('MEMBERS_COUPON_NOTIFICATION_EMAIL', $applicationConfig->memberdb->members->coupons->notification_email);
+/**
+ * Toolbox page id for events module in members only area
+ */
+define('MEMBERS_EVENTS_PAGE', $applicationConfig->memberdb->members->events_page);
+define('MEMBERS_EVENTS_NOTIFICATION_EMAIL', $applicationConfig->memberdb->members->events->notification_email);
+/**
+ * Toolbox page id for reports module in members only area
+ */
+define('MEMBERS_REPORTS_PAGE', $applicationConfig->memberdb->members->reports_page);
+/**
+ * Toolbox page id for leads module in members only area
+ */
+define('MEMBERS_LEADS_PAGE', $applicationConfig->memberdb->members->leads_page);
+/**
+ * Toolbox page id for member trip planner page
+ */
+define('MEMBER_SESSION_LIST', $applicationConfig->memberdb->session->list);
+/**
+ * The id of the page for the planner output
+ */
+define('MEMBER_SESSION_PAGE', $applicationConfig->memberdb->session->page);
+/**
+ * The id of the page for the create account form
+ */
+define('MEMBER_SESSION_FORM', $applicationConfig->memberdb->session->form);
+/**
+ * Members uses streamsend module?
+ */
+define('MEMBER_STREAMSEND_API', $applicationConfig->memberdb->streamsend->application);
+/**
+ * Site has Press/Newsletter?
+ */
+define('PRESS_DB', $applicationConfig->news->application);
+/**
+ * Toolbox Page id for the news output
+ */
+define('PRESS_PAGE_ID', $applicationConfig->news->page);
+/**
+ * Site has home page news Press/Newsletter?
+ */
+define('HOME_NEWS', $applicationConfig->news->home);
+/**
+ * Site has photo gallery?
+ */
+define('PHOTO_GALLERY', $applicationConfig->photo_gallery->application);
+/*
+ * Site has rotating images application?
+ */
+define('ROTATING_IMAGES', $applicationConfig->rotating_images->application);
+/**
+ * Grab weather feed for site?
+ */
+define('WEATHER', $applicationConfig->weather->application);
+define('EMPLOYMENT', $applicationConfig->employment->application);
+define('VIDEOS', $applicationConfig->videos->application);
+define('SEASONS', $applicationConfig->seasons->application);
+define('GLM_BLOCKS', $applicationConfig->blocks->application);
+/**
+ * Grab weather feed for site?
+ */
+define('GIFT_CERTIFICATES', $applicationConfig->gift_certificates->application);
+/**
+ * Site is Mobile enabled
+ */
+define('MOBILE_SITE', $siteConfig->mobile_site);
+
+$pathParts = pathinfo($BASE_PATH);
+/**
+ * Server directory ie (www.gaslightmedia.com, demo.gaslightmedia.com)
+ */
+define('SERVER_DIRECTORY', $pathParts['basename']);
+
+$isSecurePage = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on');
+/**
+ * absolute url path for site
+ */
+define('SITE_URL', $serverConfig->site_url);
+/**
+ * coupon url used in printed PDF coupons
+ */
+define('COUPON_SITE_URL', $serverConfig->coupon_site_url);
+/**
+ * Url for the CDN-Hosted Javascript and css for Jquery
+ */
+$jqueryUrl = ($isSecurePage) ? 'https://' : 'http://';
+define(
+ 'JQUERY_CDN_JS',
+ $jqueryUrl . 'ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'
+);
+define(
+ 'JQUERY_UI_CDN_CSS',
+ $jqueryUrl . 'code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css'
+);
+define(
+ 'JQUERY_UI_CDN_JS',
+ $jqueryUrl . 'code.jquery.com/ui/1.10.4/jquery-ui.min.js'
+);
+/**
+ * Link URL to access mobile site home page
+ */
+define('MOBILE_LINK', $serverConfig->mobile->link);
+define('HAVE_MOBILE_HOSTNAME', $serverConfig->mobile->hostname);
+/**
+ * API key for google search AJAX
+ */
+define('GSEARCH_API', $serverConfig->google->search->key);
+/**
+ * site restriction to use for google searches
+*/
+define('GSEARCH_SITE_RESTRICTION', $serverConfig->google->search->site_restriction);
+/**
+ * API key for google maps
+ */
+define('GMAPS_API', $serverConfig->google->maps->key);
+/**
+ * URI to the common GLM application repository
+ */
+define('GLM_APP_BASE_URL', $serverConfig->app->base_url);
+define('GLM_APP_BASE_SECURE_URL', $serverConfig->app->base_secure_url);
+/**
+ * Who to send email address to on production servers when fatal error is encountered
+ */
+define('ERROR_EMAIL_ADDRESS', $serverConfig->error->email);
+if ($serverConfig->error->reporting instanceof Traversable) {
+
+ $values = array();
+ foreach ($serverConfig->error->reporting as $value) {
+ $values[] = $value;
+ }
+ $lambdaFunction = create_function('$a, $b', 'return $a ^ $b;');
+ $level = array_reduce($values, $lambdaFunction, 0);
+} else {
+ $level = $serverConfig->error->reporting;
+}
+/**
+ * Turn off all error reporting
+ */
+error_reporting($level);
+/**
+ * Don't print errors to the screen as part of output
+ */
+ini_set('display_errors', $serverConfig->error->display);
+$fileServerUrl = $isSecurePage
+ ? $serverConfig->file_server->secure
+ : $serverConfig->file_server->unsecure;
+/**
+ * URL of which file server to use
+ */
+define('FILE_SERVER_URL', $fileServerUrl);
+/**
+ * Type of Log subclass to use
+ */
+define('ERROR_LOG_TYPE', $serverConfig->error->type);
+/**
+ * Constant of log store to use
+ */
+define('ERROR_LOG_NAME', constant($serverConfig->error->name));
+/**
+ * Identity reported to the log system
+ */
+define('ERROR_LOG_IDENT', $serverConfig->error->ident);
+/**
+ * Log messages up to and including this level
+ */
+define('ERROR_LOG_LEVEL', constant($serverConfig->error->level));
+/**
+ * additional configuration for ERROR_LOG_TYPE subclass
+ */
+$ERROR_LOG_CONF = array(
+ 'destination' => $serverConfig->error->conf->path
+ . constant($serverConfig->error->conf->server)
+ . "/{$serverConfig->error->conf->file}",
+ 'lineFormat' => $serverConfig->error->conf->line_format,
+);
+
+$BASE_SECURE_URL = "https://$base_url";
+/**
+ * Url used for the secure site
+ *
+ * For some sites it is necessary to change BASE_URL when in secure mode
+ */
+define('BASE_SECURE_URL', "$BASE_SECURE_URL/");
+/**
+ * Media Url Base is https if $_SERVER['HTTPS'] is on
+ * http otherwise
+ */
+$mediaBaseUrl
+ = ($isSecurePage)
+ ? BASE_SECURE_URL
+ : BASE_URL;
+define('MEDIA_BASE_URL', $mediaBaseUrl);
+/**
+ * Media Url Base is https if $_SERVER['HTTPS'] is on
+ * http otherwise
+ */
+$mediaAppBaseUrl
+ = ($isSecurePage)
+ ? GLM_APP_BASE_SECURE_URL
+ : GLM_APP_BASE_URL;
+define('MEDIA_APP_BASE_URL', $mediaAppBaseUrl);
+define('CKEDITOR_JS', MEDIA_APP_BASE_URL . 'ckeditor/4.3.2/ckeditor.js');
+// This needs to be set to the real url ie. http://demo.gaslightmedia.com
+if ($isSecurePage) {
+ $BASE_URL = "http://$base_url";
+}
+
+// Set CURRENT_BASE_URL according to whether site is secure or not.
+if ($isSecurePage) {
+ define('CURRENT_BASE_URL', $BASE_SECURE_URL.'/');
+} else {
+ define('CURRENT_BASE_URL', $BASE_URL.'/');
+}
+
+/**
+ * Database Connection String
+ */
+define('CONN_STR', "host={$serverConfig->database->params->host} user={$serverConfig->database->params->username} dbname={$serverConfig->database->params->dbname}");
+/**
+ * DSN Connection String
+ */
+define('DSN', "{$serverConfig->database->adapter}://{$serverConfig->database->params->username}@{$serverConfig->database->params->host}/{$serverConfig->database->params->dbname}");
+/**
+ * Used for error reporting
+ *
+ * When in development mode, more info is displayed if errors occur.
+ */
+define('DEVELOPMENT', $serverConfig->development);
+/**
+ * Site owners email address
+ */
+define('OWNER_EMAIL', $serverConfig->email->owner);
+/**
+ * email for contact form
+ */
+define('CONTACT_EMAIL', $serverConfig->email->contact);
+/**
+ * Add Your Event Form Email
+ */
+define('ADD_EVENT_EMAIL', $serverConfig->email->addEventForm);
+/**
+ * email for enews signup
+ */
+define('ENEWS_EMAIL', $serverConfig->email->enews);
+/**
+ * email for visitor guide form
+ */
+define('VISITOR_GUIDE_EMAIL', $serverConfig->email->visitor_guide);
+/**
+ * email for Employment Application Form
+ */
+define('EMP_APP_EMAIL', $serverConfig->email->applicationForm);
+/**
+ * From header for admin/Contact mailout.
+ */
+define('FROM_NEWS_EMAIL', $serverConfig->email->from_news);
+define('SERVER_FROM_EMAIL', $serverConfig->email->server_from);
+/**
+ * From headers for admin/MContact
+ */
+define('FROM_MEMBER_NEWS_EMAIL', $serverConfig->email->from_member_news);
+/**
+ * Reply header for admin/MContact
+ */
+define('REPLY_MEMBER_NEWS_EMAIL', $serverConfig->email->reply_member_news);
+/**
+ * which email address should the notifications go to when a member
+ */
+define('MEMBER_RECORD_UPDATES_ADVISOR', $serverConfig->email->member_record_updates_advisor);
+/**
+ * Reply-To email used in the members forgot password email
+ */
+define('MEMBER_FORGOT_PASSWORD_EMAIL_REPLY_TO', $serverConfig->email->member_forgot_password_email_reply_to);
+/**
+ * This is where the first email goes.
+ * To notify the site owner that gift cert is ordered
+ */
+define('GIFTCERT_EMAIL', $serverConfig->email->giftcert);
+/**
+ * Used as the From address
+ */
+define('GIFTCERT_FROM_EMAIL', $serverConfig->email->giftcert_from);
+/**
+ * This email containes sensitive info and must be upnorth.net address
+ */
+define('GIFTCERT_SECURE_EMAIL', $serverConfig->email->giftcert_secure);
+/**
+ * in admin/Contact mailout.phtml file
+ * Reply-To: header
+ */
+define('REPLY_TO', $serverConfig->email->reply_to);
+/**
+ * Dead email address for forms w/ one-way communication
+ */
+define('DO_NOT_REPLY_EMAIL', $serverConfig->email->do_not_reply);
+/**
+ * The email address to send the banner reports to
+ * for the site admin
+ */
+define('BANNER_REPORTS_ADMIN_EMAIL', $serverConfig->email->banner_reports_admin);
+/**
+ * The email address to send banner expiration notices to
+ */
+define('EXPIRING_BANNER_NOTIFICATION_EMAIL', $serverConfig->email->expiring->banner_notification);
+/**
+ * Authorize.net processing parameters
+ * ALSO SEE "Authorize.Net Configuration" SECTION BELOW CONDITIONAL SETTINGS
+ */
+define('AUTH_TEST', $serverConfig->auth->test);
+define('AUTH_SEND_CONF', $serverConfig->auth->send_conf);
+define('AUTH_MERCHANT_EMAIL', $serverConfig->auth->merchant_email);
+define('AUTH_DEBUG', $serverConfig->auth->debug);
+/**
+ * Enable Ticketing System
+ */
+define('TICKETING', $applicationConfig->ticketing->available);
+define("TICKETS_CAT_ID", $applicationConfig->ticketing->catid);
+define("TICKETS_CAT_SEO", $applicationConfig->ticketing->cat_seo);
+
+define('LIBJS_ENV', $serverConfig->resources->environment->javascript);
+define('CSS_ENV', $serverConfig->resources->environment->css);
+
+if ($version = filter_var($serverConfig->resources->version, FILTER_VALIDATE_INT)) {
+ // do nothing - its already set
+} else {
+ $version = mt_rand();
+}
+/**
+ * Site Versioning for cachebusting
+ */
+define('VERSION', $version);
+
+$secureUrl = $isSecurePage ? BASE_SECURE_URL : BASE_URL;
+
+$forceCompile = false;//(DEVELOPMENT || $isSecurePage);
+
+$flexyOptions = array(
+ 'templateDir' => BASE . 'templates',
+ 'compileDir' => BASE . 'templates/compiled',
+ 'forceCompile' => $forceCompile,
+ 'url_rewrite' => "baseurl/::".BASE_URL.",basesecureurl/::$secureUrl,glmappbaseurl/::" . GLM_APP_BASE_URL,
+ 'allowPHP' => true,
+);
+
+$cacheOptions = array(
+ 'cacheDir' => BASE . 'cache/',
+ 'writeControl' => true,
+ 'lifeTime' => (DEVELOPMENT) ? 0 : null,
+ 'readControl' => true,
+ 'fileNameProtection' => false,
+ 'readControlType' => 'md5',
+);
+
+// Global arrays to store resources for apps.
+$topScripts = array();
+$bottomScripts = array();
+$styleSheets = array();
+
+// help guide base (depreciated)
+define('HELP_BASE', 'help/');
+// uploads directory path
+define('UP_BASE', BASE . 'uploads/');
+// the images url path
+define('IMG_BASE', MEDIA_BASE_URL . 'images/');
+
+// Toolbox image paths
+define('ORIGINAL_PATH', BASE . 'images/original/');
+define('RESIZED_PATH', BASE . 'images/resized/');
+define('MIDSIZED_PATH', BASE . 'images/midsized/');
+define('THUMB_PATH', BASE . 'images/thumb/');
+
+// Amenity icon path
+define('AMENITY_PATH', BASE . 'images/amenities/');
+
+$imageURLBase = $isSecurePage ? BASE_SECURE_URL : BASE_URL;
+
+// Toolbox image URLS
+// Now using new Image Server
+/**
+ * Now using new Image Server
+ * http://is0.gaslightmedia.com/admin
+ * setup new owner with owner_id and owner_pw
+ * MUST BE DONE BEFORE uploading any images
+ */
+/**
+* IS_OWNER_ID owner_id from image server config
+ */
+define('IS_OWNER_ID', $serverConfig->file_server->owner_id);
+/**
+ * IS_OWNER_PW owner_pw from image server config
+ */
+define('IS_OWNER_PW', $serverConfig->file_server->owner_password);
+/**
+ * Toolbox image URLS
+ * NOTE: these don't change
+ * There are 4 global "image styles"
+ * original = used for original images no processing
+ * tbs1 = used to be resized
+ * tbs2 = used to be midsized
+ * tbs3 = used to be thumb
+ * check on http://is0.gaslightmedia.com/admin under owner _SYSTEM_
+ * for their sizes
+ * if you need a different size you'll need to create image style for
+ * your owner with new sizes just use one of set style names
+ * tbs1,tbs2,tbs3 (do this before uploading the image will help)
+ */
+define('ORIGINAL', FILE_SERVER_URL.IS_OWNER_ID."/original/");
+define('RESIZED', FILE_SERVER_URL.IS_OWNER_ID."/tbs1/");
+define('MIDSIZED', FILE_SERVER_URL.IS_OWNER_ID."/tbs2/");
+define('THUMB', FILE_SERVER_URL.IS_OWNER_ID."/tbs3/");
+
+// Toolbox image rules
+define('TOOLBOX_ORIGINAL', ORIGINAL);
+define('TOOLBOX_RESIZED', RESIZED);
+define('TOOLBOX_MIDSIZED', MIDSIZED);
+define('TOOLBOX_THUMB', THUMB);
+
+/**
+ * These are defines for the photo gallery images
+ * NOTICE these are now on image server
+ * There are 2 global "image styles"
+ * pgs1 = used to be photo-large
+ * pgs2 = used to be photo-small
+ * check on http://is0.gaslightmedia.com/admin under owner _SYSTEM_
+ * for their sizes
+ */
+define('UPLOADED_FILES', FILE_SERVER_URL.IS_OWNER_ID.'/');
+
+define('PHOTO_LARGE_URL', FILE_SERVER_URL.IS_OWNER_ID."/pgs1/");
+define('PHOTO_SMALL_URL', FILE_SERVER_URL.IS_OWNER_ID."/pgs2/");
+
+/**
+ * Home page headlines thumbnail
+ */
+define('HOMEPAGE_HEADLINE_THUMB', FILE_SERVER_URL.IS_OWNER_ID."/homepageHeadlineThumb/");
+define('HEADLINE_THUMB', FILE_SERVER_URL.IS_OWNER_ID.'/headline/');
+
+// Coupon Image rules
+define('COUPON_THUMB', FILE_SERVER_URL.IS_OWNER_ID.'/couponThumb/');
+
+// Rotating Image rules
+define('ROTATING_IMAGE_THUMB', FILE_SERVER_URL.IS_OWNER_ID.'/rotatingImagesThumb/');
+define('ROTATING_IMAGE_RESIZED', FILE_SERVER_URL.IS_OWNER_ID.'/rotatingImagesResized/');
+
+// Member image rules
+define('MEMBER_ORIGINAL', FILE_SERVER_URL.IS_OWNER_ID."/original/");
+define('MEMBER_RESIZED', FILE_SERVER_URL.IS_OWNER_ID."/memberResized/");
+define('MEMBER_MIDSIZED', FILE_SERVER_URL.IS_OWNER_ID."/memberMidsized/");
+define('MEMBER_THUMB', FILE_SERVER_URL.IS_OWNER_ID."/memberThumb/");
+define('MEMBER_PHOTOS', FILE_SERVER_URL.IS_OWNER_ID."/memberPhotos/");
+define('MEMBER_PACKAGES', FILE_SERVER_URL.IS_OWNER_ID."/memberResized/");
+define('MEMBER_GOOGLE_MAP', FILE_SERVER_URL.IS_OWNER_ID."/memberGoogleMap/");
+define('MEMBER_UPLOADED_FILES', BASE . 'uploads/member_files/');
+define('TRIP_PLANNER_MAP_IMG', FILE_SERVER_URL.IS_OWNER_ID."/tripPlannerMapImg/");
+
+// Banner image rules
+define('BANNER_ORIGINAL', FILE_SERVER_URL.IS_OWNER_ID.'/original/');
+define('HORIZONTAL_BANNER', FILE_SERVER_URL.IS_OWNER_ID.'/horizontalBanner/');
+define('HORIZONTAL_BANNER_THUMB', FILE_SERVER_URL.IS_OWNER_ID.'/horizontalBannerThumb/');
+define('VERTICAL_BANNER', FILE_SERVER_URL.IS_OWNER_ID.'/verticalBanner/');
+define('VERTICAL_BANNER_THUMB', FILE_SERVER_URL.IS_OWNER_ID.'/verticalBannerThumb/');
+
+// Press image rules
+define('PRESS_ORIGINAL', TOOLBOX_ORIGINAL);
+define('PRESS_RESIZED', TOOLBOX_RESIZED);
+define('PRESS_MIDSIZED', TOOLBOX_MIDSIZED);
+define('PRESS_THUMB', TOOLBOX_THUMB);
+
+// Event image rules
+define('EVENT_ORIGINAL', TOOLBOX_ORIGINAL);
+define('EVENT_RESIZED', TOOLBOX_RESIZED);
+define('EVENT_MIDSIZED', TOOLBOX_MIDSIZED);
+define('EVENT_THUMB', TOOLBOX_THUMB);
+
+// Form image rules
+define('FORM_ORIGINAL', TOOLBOX_ORIGINAL);
+define('FORM_RESIZED', TOOLBOX_RESIZED);
+define('FORM_MIDSIZED', TOOLBOX_MIDSIZED);
+define('FORM_THUMB', TOOLBOX_THUMB);
+
+// CKImage image rules
+/**
+ * This is the rule used to create the Maximum Allowed Size image
+ * we allow for CKEditor Images, which is (700x500)
+ *
+ * If the user resizes (edits) the image, it can be smaller
+ */
+define('CKIMAGE', FILE_SERVER_URL.IS_OWNER_ID."/CKImage/");
+define('CKIMAGE_ORIGINAL', TOOLBOX_ORIGINAL);
+define('CKIMAGE_RESIZED', TOOLBOX_RESIZED);
+define('CKIMAGE_MIDSIZED', TOOLBOX_MIDSIZED);
+define('CKIMAGE_THUMB', TOOLBOX_THUMB);
+/**
+ * This is the thumbnail image used in the GLM Image Browser
+ * attached to the new CKEditor
+ */
+define('IMAGE_MANAGER', FILE_SERVER_URL.IS_OWNER_ID."/imgMgr/");
+
+// Amenity image URLS
+define('AMENITY_THUMB', "{$imageURLBase}images/amenities/");
+// Icon image URLS
+define('ICONS_URL', "{$imageURLBase}images/");
+
+//
+// Authorize.Net Configuration
+//
+
+/**
+ * Curl executable
+ */
+define('AUTH_CURL', '/usr/bin/curl');
+/**
+ * Authorization URL
+ */
+define('AUTH_URL', 'https://secure.authorize.net/gateway/transact.dll');
+/**
+ * "TRUE" (use Authorize.net test mode), "FALSE", "LOCAL_TEST", "LOCAL_TEST_ERROR"
+ * Must be "FALSE" for production! - When using "LOCAL_TEST" only approves card '0011001100110011'
+ */
+//define('SI_AUTH_TEST', 'TRUE');
+/**
+ * Authorize.Net Customer Login -- UNIQE FOR EACH CUSTOMER --
+ */
+define('AUTH_LOGIN', 'xxxxxxx');
+/**
+ * Authorize.Net Customer Transaction Key -- UNIQE FOR EACH CUSTOMER --
+ */
+define('AUTH_TRAN_KEY', 'xxxxxxxxxxxxx');
+/**
+ * TRUE to have customer's receive E-Mail confirmation
+ */
+//define('AUTH_SEND_CONF', 'FALSE');
+/**
+ * TRUE to have merchant receive E-Mail convirmation of customer charges
+ */
+//define('AUTH_MERCHANT_EMAIL', 'TRUE');
+/**
+ * MD5 Hash secret used by Authorize.Net to generate MD5 response verification data
+ * If empty - don't check MD5 response
+ */
+define('AUTH_SECRET', '');
+
+// Transaction status types
+
+/**
+ * Unknown state
+ */
+define('AUTH_STATUS_UNKNOWN', 0);
+/**
+ * Declined by Authorize.net
+ */
+define('AUTH_STATUS_DECLINED', 1);
+/**
+ * Authorize.Net error
+ */
+define('AUTH_STATUS_ERROR', 2);
+/**
+ * Approved by Authorize.Net
+ */
+define('AUTH_STATUS_APPROVED', 10);
+/**
+ * Card manually processed
+ */
+define('AUTH_STATUS_MANUAL', 11);
+/**
+ * Paid by Check
+ */
+define('AUTH_STATUS_CHECK', 12);
+/**
+ * On Account
+ */
+define('AUTH_STATUS_ACCOUNT', 13);
+/**
+ * Paid by Other means
+ */
+define('AUTH_STATUS_OTHER_PAID', 14);
+/**
+ * Comp, no charge
+ */
+define('AUTH_STATUS_COMP', 15);
+
+$auth_status_list
+ = AUTH_STATUS_UNKNOWN.'^Unknown Card Status~'
+ . AUTH_STATUS_DECLINED.'^Declined by AuthorizeNet~'
+ . AUTH_STATUS_ERROR.'^AuthorizeNet Approval Error~'
+ . AUTH_STATUS_APPROVED.'^Approved by AuthorizeNet~'
+ . AUTH_STATUS_MANUAL.'^Card Approved Manually~'
+ . AUTH_STATUS_CHECK.'^Paid by Check~'
+ . AUTH_STATUS_ACCOUNT.'^Applied to Account~'
+ . AUTH_STATUS_OTHER_PAID.'^Paid by other means~'
+ . AUTH_STATUS_COMP.'^Comp, no charge';
+
+/*
+ * Load other applications
+ */
+
+if (defined('TICKETING') && TICKETING) {
+ include_once 'ticketing/config.inc';
+}
+
+// [status_US] array of states and their abbr.
+$states_US[''] = '-- Select --';// {{{
+$states_US['AL'] = 'Alabama';
+$states_US['AK'] = 'Alaska';
+$states_US['AZ'] = 'Arizona';
+$states_US['AR'] = 'Arkansas';
+$states_US['CA'] = 'California';
+$states_US['CO'] = 'Colorado';
+$states_US['CT'] = 'Connecticut';
+$states_US['DE'] = 'Delaware';
+$states_US['DC'] = 'District of Columbia';
+$states_US['FL'] = 'Florida';
+$states_US['GA'] = 'Georgia';
+$states_US['HI'] = 'Hawaii';
+$states_US['ID'] = 'Idaho';
+$states_US['IL'] = 'Illinois';
+$states_US['IN'] = 'Indiana';
+$states_US['IA'] = 'Iowa';
+$states_US['KS'] = 'Kansas';
+$states_US['KY'] = 'Kentucky';
+$states_US['LA'] = 'Louisiana';
+$states_US['ME'] = 'Maine';
+$states_US['MD'] = 'Maryland';
+$states_US['MA'] = 'Massachusetts';
+$states_US['MI'] = 'Michigan';
+$states_US['MN'] = 'Minnesota';
+$states_US['MS'] = 'Mississppi';
+$states_US['MO'] = 'Missouri';
+$states_US['MT'] = 'Montana';
+$states_US['NE'] = 'Nebraska';
+$states_US['NV'] = 'Nevada';
+$states_US['NH'] = 'New Hampshire';
+$states_US['NJ'] = 'New Jersey';
+$states_US['NM'] = 'New Mexico';
+$states_US['NY'] = 'New York';
+$states_US['NC'] = 'North Carolina';
+$states_US['ND'] = 'North Dakota';
+$states_US['OH'] = 'Ohio';
+$states_US['OK'] = 'Oklahoma';
+$states_US['OR'] = 'Oregon';
+$states_US['PA'] = 'Pennsylvania';
+$states_US['RI'] = 'Rhode Island';
+$states_US['SC'] = 'South Carolina';
+$states_US['SD'] = 'South Dakota';
+$states_US['TN'] = 'Tennessee';
+$states_US['TX'] = 'Texas';
+$states_US['UT'] = 'Utah';
+$states_US['VT'] = 'Vermont';
+$states_US['VA'] = 'Virginia';
+$states_US['WA'] = 'Washington';
+$states_US['WV'] = 'West Virginia';
+$states_US['WI'] = 'Wisconsin';
+$states_US['WY'] = 'Wyoming';// }}}
+
+// [states] extended states array
+$states['AB'] = 'Alberta';// {{{
+$states['AS'] = 'American Samoa';
+$states['BC'] = 'British Columbia';
+$states['DC'] = 'District of Columbia';
+$states['FM'] = 'Federated States of Micronesia';
+$states['GU'] = 'Guam';
+$states['MB'] = 'Manitoba';
+$states['MH'] = 'Marshall Islands';
+$states['NB'] = 'New Brunswick';
+$states['NF'] = 'Newfoundland';
+$states['MP'] = 'Northern Mariana Islands';
+$states['NT'] = 'Northwest Territories';
+$states['NS'] = 'Nova Scotia';
+$states['ON'] = 'Ontario';
+$states['PW'] = 'Palau';
+$states['PE'] = 'Prince Edward Island';
+$states['PR'] = 'Puerto Rico';
+$states['QC'] = 'Quebec';
+$states['SK'] = 'Saskatchewan';
+$states['VI'] = 'Virgin Islands';
+$states['YT'] = 'Yukon';// }}}
+
+// Merge the 50 US states together with some of the extended
+// provinces / territories and then sort them on their keys
+// Then add the remaining countries and areas at the end
+// of the array.
+$states = $states_US + $states;
+ksort($states);
+$states = $states + array(// {{{
+ 'Asia' => 'Asia',
+ 'Australia' => 'Australia',
+ 'Bahamas' => 'Bahamas',
+ 'Caribbean' => 'Caribbean',
+ 'Costa Rica' => 'Costa Rica',
+ 'South America' => 'South America',
+ 'South Africa' => 'South Africa',
+ 'Europe' => 'Europe',
+ 'Mexico' => 'Mexico',
+);// }}}
+
+// Libraries
+// Replaced with the actual functions instead of includes (2001-12-14)
+
+$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
+);
+
+if ($includeFunctions) {
+ /**
+ * all setup function in setup_functions.phtml
+ */
+ require_once BASE_PATH . "setup_functions.phtml";
+}
+
+/**
+ * Chuck and John H. have setup site monitoring script that will hit a
+ * file every so often and make a db connection to test if that database
+ * connection is good. The aim here it to monitor the sites to see if
+ * they go down and page Chuck/John and Dave We'll check for the setup
+ * script in the root of the site if it is not there and the database
+ * has been setup in this file it will create the file.
+ */
+$SiteCheckFile = BASE . 'GLM_site_check.phtml';
+if (!file_exists($SiteCheckFile) && $_ENV['GLM_HOST_ID'] == 'PRODUCTION') {
+ // get the dbname for the connection
+ $siteCheckArray = explode(" ", CONN_STR);
+ foreach ($siteCheckArray as $scaVar) {
+ parse_str($scaVar, $parsedSettings);
+ if ($parsedSettings['dbname']) {
+ $dbname = $parsedSettings['dbname'];
+ }
+ }
+ if ($dbname) {
+ // we're going to assume that the connection
+ // will be for ds3.gaslightmedia.com
+ $fileContent = "<?php \n"
+ . "/**\n"
+ . " * GLM Standard Site Monitoring Target\n"
+ . " */\n\n"
+ . "define('HOST', 'ds4.gaslightmedia.com');\n"
+ . "define('USER', 'nobody');\n"
+ . "define('DBNAME', '$dbname');\n"
+ . "\n"
+ . "// End of parameters to set for each site\n"
+ . "include '/var/www/templates/Global_site_check.phtml';\n"
+ . '?' . '>';
+ file_put_contents($SiteCheckFile, $fileContent);
+ }
+}
--- /dev/null
+<?php
+/** @header Gaslight Media Toolbox
+ functions that were in the functions.inc
+ */
+ // {{{ setSearchPath()
+
+ /**
+ * This is a copy from the DB singletons
+ * Toolkit_Database.php <-- Primary
+ * classes/class_db.inc <-- Secondary - soon to be removed
+ *
+ * the following packages depend on this function. after all are updated
+ * this function can/should be removed
+ *
+ * Admin/Postcards
+ */
+ function setSearchPath(&$dbh)
+ {
+ // Add schemas to search path.
+ $format = "
+ SELECT set_config(
+ 'search_path',
+ current_setting('search_path') || ',%s',
+ false
+ )";
+
+ $sql = sprintf($format, 'toolbox');
+ db_exec($dbh, $sql);
+
+ $sql = sprintf($format, 'ckimages');
+ db_exec($dbh, $sql);
+
+ if (defined('CONTACT_DB') && CONTACT_DB) {
+ // define banner search path
+ $sql = sprintf($format, 'contacts');
+ db_exec($dbh, $sql);
+ }
+
+ if (defined('BANNERS') && BANNERS) {
+ // define banner search path
+ $sql = sprintf($format, 'banners');
+ db_exec($dbh, $sql);
+ }
+
+ if (defined('ROTATING_IMAGES') && ROTATING_IMAGES) {
+ // define rotating images search path
+ $sql = sprintf($format, 'rotatingImages');
+ db_exec($dbh, $sql);
+ }
+
+ if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) {
+ // define phot gallery search path
+ $sql = sprintf($format, 'photos');
+ db_exec($dbh, $sql);
+ }
+
+ if (defined('EVENT_DB') && EVENT_DB) {
+ // define members search path
+ $sql = sprintf($format, 'events');
+ db_exec($dbh, $sql);
+ }
+
+ if (defined('POSTCARD_DB') && POSTCARD_DB) {
+ // define members search path
+ $sql = sprintf($format, 'postcards');
+ db_exec($dbh, $sql);
+ }
+
+ if (defined('MEMBERS_DB') && MEMBERS_DB) {
+ // define members search path
+ $sql = sprintf($format, 'members');
+ db_exec($dbh, $sql);
+ }
+
+ if (defined('COUPONS') && COUPONS) {
+ // define coupon search path
+ $sql = sprintf($format, 'coupons');
+ db_exec($dbh, $sql);
+ }
+ }
+
+ // }}}
+
+ /**
+ * is_utf8
+ *
+ * @param mixed $string
+ * @access public
+ * @return void
+ */
+ function is_utf8($string)
+ {
+ return preg_match('/^([\x00-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xec][\x80-\xbf]{2}|\xed[\x80-\x9f][\x80-\xbf]|[\xee-\xef][\x80-\xbf]{2}|f0[\x90-\xbf][\x80-\xbf]{2}|[\xf1-\xf3][\x80-\xbf]{3}|\xf4[\x80-\x8f][\x80-\xbf]{2})*$/', $string) === 1;
+ }
+
+ /**
+ * cp1252_to_utf8
+ *
+ * @param mixed $str
+ * @access public
+ * @return void
+ */
+ function cp1252_to_utf8($str)
+ {
+ global $cp1252_map;
+ return strtr(utf8_encode($str), $cp1252_map);
+ }
+
+ /**
+ * myEncode
+ *
+ * @param mixed $string
+ * @access public
+ * @return void
+ */
+ function myEncode($string)
+ {
+ if (is_utf8($string)) {
+ return $string;
+ } else {
+ return cp1252_to_utf8($string);
+ }
+ }
+
+ /**
+ * CreditVal : CreditVal Checks for a valid credit card number doing Luhn check, if no
+ card type is given, attempts to guess. Then, if a list of
+ accepted types is given, determines whether or not we'll
+ accept it
+ * @param $Num: Credit Card Number
+ * @param $Name = '': Type of Card
+ * @param $Accepted='' : Accepted array
+ *
+ * @return bool
+ * @access
+ **/
+ 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_trim(',', $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 < strlen($Num); ++$x) {
+ $digit = substr($Num, $x, 1);
+ if ($x / 2 != floor($x / 2)) {
+ $digit *= 2;
+ if (strlen($digit) == 2)
+ $digit = substr($digit, 0, 1) + substr($digit, 1, 1);
+ }
+ $Total += $digit;
+ }
+ return ($GoodCard && (($Total % 10) == 0)) ? true : false;
+ }
+ // DataBase Library
+
+ /**
+ * db_connect :Creates a connection to database specified $conn_str
+ * @param $conn="" : connection string
+ *
+ * @return index or bool
+ * @access
+ **/
+ function db_connect($conn = '')
+ {
+ switch (DB_TYPE) {
+ case 'postgres' :
+ if ($conn == '')
+ $conn = CONN_STR;
+ $ret = pg_connect($conn);
+ break;
+
+ default:
+ return 0;
+ break;
+ }
+ return $ret;
+ }
+
+ /**
+ * db_close :Closes the connection to database specified by the handle dbd
+ * @param $$dbd : database handle
+ *
+ * @return bool
+ * @access
+ **/
+ function db_close($dbd)
+ {
+ switch (DB_TYPE) {
+ case 'postgres' :
+ $ret = pg_close($dbd);
+ break;
+
+ default:
+ return 0;
+ break;
+ }
+ return $ret;
+ }
+
+ /**
+ NOTICE DON'T USE THIS
+ * db_pconnect :Creates a persistant connection to database specified in $conn_str
+ * @param $$conn="" : connection string
+ *
+ * @return
+ * @access
+ **/
+ function db_pconnect($conn = '')
+ {
+ return false;
+ switch (DB_TYPE) {
+ case 'postgres' :
+ if($conn == '')
+ $conn == CONN_STR;
+ $ret = pg_pconnect($conn);
+ break;
+
+ default:
+ return 0;
+ break;
+ }
+ return $ret;
+ }
+
+ /**
+ * db_exec : Execute an SQL query
+ * @param $dbd: database handle
+ * @param $$qs : Query
+ *
+ * @return int Returns a valid result index on success 0 on failure
+ * @access
+ **/
+ function db_exec($dbd, $qs)
+ {
+ switch (DB_TYPE) {
+ case 'postgres' :
+ $ret = pg_exec($dbd, $qs);
+ break;
+
+ default:
+ return 0;
+ break;
+ }
+ return $ret;
+ }
+
+ /**
+ * db_fetch_array :Stores the data in associative indices, using the field names as
+ * keys.
+ * @param $res: valid database result index
+ * @param $i: row number
+ * @param $$type : database type
+ *
+ * @return array Returns an associative array of key-value pairs
+ * @access
+ **/
+ function db_fetch_array($res, $i, $type)
+ {
+ switch (DB_TYPE) {
+ case 'postgres' :
+ $row = pg_fetch_array($res, $i, $type);
+ break;
+
+ default:
+ return 0;
+ break;
+ }
+ return $row;
+ }
+
+ /**
+ * db_freeresult :Free result memory.
+ * @param $$res : valid database result index
+ *
+ * @return bool - Returns 1 for success 0 for failure
+ * @access
+ **/
+ function db_freeresult($res)
+ {
+ switch (DB_TYPE) {
+ case 'postgres' :
+ $ret = pg_freeresult($res);
+ break;
+
+ default:
+ return 0;
+ break;
+ }
+ return $ret;
+ }
+
+ /**
+ * db_numrows :Determine number of rows in a result index
+ * @param $$res : valid database result index
+ *
+ * @return int - Returns number of rows
+ * @access
+ **/
+ function db_numrows($res)
+ {
+ switch (DB_TYPE) {
+ case 'postgres' :
+ $ret = pg_numrows($res);
+ break;
+
+ default:
+ return -1;
+ break;
+ }
+ return $ret;
+ }
+
+ /************************************************************************
+ * *
+ * BEGIN Auto functions *
+ * *
+ ***********************************************************************/
+
+ /**
+ * db_auto_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
+ * @param $qs: SQL query string
+ * @param $i: row number
+ * @param $$type : PGSQL_ASSOC or PGSQL_BOTH or PSQL_NUM
+ *
+ * @return array - Returns an associative array of key-value pairs
+ * @access
+ **/
+ function db_auto_array($qs, $i, $type)
+ {
+ $dbd = db_connect();
+ if (!$dbd) {
+ return 0;
+ }
+ $res = db_exec($dbd, $qs);
+ if (!$res) {
+ return 0;
+ }
+ $row = db_fetch_array($res, $i, $type);
+ if (!db_freeresult($res)) {
+ return 0;
+ }
+ db_close($dbd);
+ return $row;
+ }
+
+ /**
+ * 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)
+ * @param $qs: SQL query string
+ * @param $$conn="" : Connect String
+ *
+ * @return int - Returns 1 (or oid, if available) for success 0 for failure
+ * @access
+ **/
+ function db_auto_exec($qs, $conn = '')
+ {
+ if ($conn == ''){
+ $conn = CONN_STR;
+ }
+ $dbd = db_connect($conn);
+ if (!$dbd) {
+ return 0;
+ }
+ if (!db_exec($dbd, $qs)) {
+ db_close($dbd);
+ return 0;
+ } else {
+ db_close($dbd);
+ return 1;
+ }
+ }
+
+ /**
+ * 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
+ * @param $qs: SQL query string
+ * @param $CONN_STR: Connect String
+ * @param $$fail_mode=0 : Failure Mode
+ *
+ * @return array Returns an associative array of key-value pairs
+ * @access
+ **/
+ function db_auto_get_data($qs, $conn = CONN_STR, $fail_mode = 0) {
+
+ if (!($dbd = db_connect($conn))) {
+ return false;
+ }
+
+ if (!($res = db_exec($dbd, $qs))) {
+ return false;
+ }
+
+ $totalrows = pg_NumRows($res);
+
+ for ($i = 0 ; $i < $totalrows; ++$i) {
+ $data[$i] = db_fetch_array($res, $i, PGSQL_ASSOC);
+ }
+
+ db_close($dbd);
+ return (isset($data) && $data != '') ? $data : 0;
+ }
+
+ // HTML Libraries
+
+ /**
+ * html_footer :Generates a footer table on the bottom of the page it's called on.
+ and closes out the body and html tags.
+ *
+ * @return void
+ * @access
+ **/
+ function html_footer()
+ {
+ $footer_table_width = '400';
+ $footer_table_align = 'center';
+ ?>
+ <hr>
+ <table width="<?php echo $footer_table_width?>"
+ align="<?php echo $footer_table_align?>"
+ summary="Footer Information" class="footertable" cellspacing="0">
+ <tr>
+ <td align="left" class="footertd">
+ <a href="mailto:<?php echo MASTER_EMAIL;?>"><?php echo MASTER;?></a>
+ </td>
+ <td align="right" class="footertd">
+ <a href="<?php echo FOOTER_URL;?>" target="new">
+ <img src="<?php echo FOOTER_IMG;?>" border=0 alt="FOOTER_IMG"></a>
+ </td>
+ </tr>
+ </table>
+ </body>
+ </html>
+ <?php
+ // We've got to terminate any more output
+ exit;
+ }
+
+ /**
+ * html_error :Generates a footer table on the bottom of the page it's called on.
+ and closes out the body and html tags.
+ * @param $msg: string error message to be displayed
+ * @param $$bail : bool whether or not to exit() after $msg
+ *
+ * @return void
+ * @access
+ **/
+ function html_error($msg, $bail)
+ {
+ ?>
+ <table summary="Error Information" class="errortable" cellspacing="0">
+ <tr class="errortr">
+ <td class="errortd">
+ <div class="errormsg"><?echo "<pre>$msg</pre>"?></div>
+ </td>
+ </tr>
+ </table>
+
+ <?php
+ if ($bail) {
+ html_footer();
+ }
+ }
+
+ /**
+ * html_nav_table :Generates a navigation table on the page it's called on.
+ * @param $nav: associative array with entries like:$nav[text][url]
+ * @param $$w : max width of table
+ *
+ * @return void
+ * @access
+ **/
+ function html_nav_table($nav, $w)
+ {
+ if (is_array($nav)) {
+ $out = '<ul class="admin_nav">';
+ foreach ($nav as $link => $url) {
+ if (is_array($url)) {
+ $out .= '<li><a href="'.$url[0].'" '.$url[1].'>'.$link.'</a></li>';
+ } else {
+ $out .= '<li><a href="'.$url.'">'.$link.'</a></li>';
+ }
+ }
+ $out .= '</ul>';
+ }
+ echo $out;
+ }
+
+ /**
+ * html_header :Opens up the html tags, and includes the style sheet link
+ generates a header table on the top of the page it's called on.
+ * @param $title: Page Title
+ * @param $msg: message to display
+ * @param $$img : image to display
+ *
+ * @return void
+ * @access
+ **/
+ function html_header($title, $msg, $img)
+ {
+ $header_table_width = '400';
+ $header_table_align = 'center';
+ ?>
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+ "http://www.w3.org/TR/html4/loose.dtd">
+ <html>
+ <head>
+ <title><?php echo $title?></title>
+ <link type="text/css" rel=stylesheet href="<?php echo STYLE;?>">
+ </head>
+ <body>
+ <table width="<?php echo $header_table_width?>"
+ align="<?echo $header_table_align?>"
+ summary="Header Information" class="headertable"
+ cellspacing="0" cellpadding="3">
+ <tr class="headertr">
+ <td class="headertd">
+ <?php if($img) : ?>
+ <img src="<?php echo IMG_BASE.$img;?>"
+ alt="<?php echo HEAD;?>" border="0">
+ <?php endif; ?>
+ </td>
+ </tr>
+ <tr>
+ <td class="headertd2" align="center">
+ <div class="headerh2" align="center">
+ <?php echo $msg;?>
+ </div>
+ </td>
+ </tr>
+ </table>
+ <?php
+ }
+
+ /**
+ * form_header :Opens up the form tag, and includes the hidden assoc array as hidden
+ fields.
+ * @param $action: string form action string
+ * @param $method: string Method of form
+ * @param $$hidden = "" : assoc array with $hidden($name => $value)
+ *
+ * @return void
+ * @access
+ **/
+ function form_header($action, $method, $hidden = '')
+ {
+ echo '<form action="'.$action.'" method="'.$method.'"
+ enctype="multipart/form-data">';
+ if ($hidden != '' && is_array($hidden)) {
+ foreach ($hidden as $k => $v) {
+ echo '<input type="hidden" name="'.$k.'" value="'.$v.'">';
+ }
+ }
+ }
+
+ /**
+ * text_box :Creates a input box for text with 35 as default size
+ * @param $name: string name of text box
+ * @param $value: string value of text box
+ * @param $$size = 35 : string size of text box
+ *
+ * @return void
+ * @access
+ **/
+ function text_box($name, $value, $size = 35) {
+ echo '<td class="navtd2"><input type="text" name="'.$name.'"
+ value="'.htmlspecialchars($value).'" size="'.$size.'"></td>';
+ }
+
+ /**
+ * form_footer :Closes up the form tag, and includes the submit button
+ * @param $name: string form action string
+ * @param $$suppress = 0: string Method of form
+ * @param $$cs : int colspan for td
+ *
+ * @return void
+ * @access
+ **/
+ function form_footer($name, $suppress = 0, $cs)
+ {
+ echo '<tr><td colspan="'.$cs.'" align=center>
+ <input type="SUBMIT" name="Command" value="'.$name.'">';
+ if ($suppress == 1) {
+ echo '<input type="SUBMIT" name="Command" value="Delete">';
+ }
+ echo '</td>';
+ }
+
+ /**
+ * file_upload
+ * this will replace the older version and that of img_upload which calls this with extra
+ * restricted of true
+ *
+ * @param mixed $form_field
+ * @param mixed $file_name
+ * @param mixed $destination_path
+ * @access public
+ * @return string
+ */
+ function file_upload($form_field, $file_name, $destination_path, $restricted = false)
+ {
+ $file_name_in_use = false;
+ $file_name = preg_replace('/[!@#$%^&()+={};:\'\"\/ ]/', '-', $file_name);
+ if ($restricted) {
+ $size = getImageSize($form_field);
+ if (!in_array($size[2], array(1, 2, 3))) {
+ echo '<p style="background-color:red;color:white;">' .
+ 'The file you uploaded was of an incorect type,
+ please only upload .gif,.png or .jpg files' .
+ '<BR CLEAR=ALL>' .
+ '</p>' .
+ "Hit your browser's back button to continue" .
+ '<p>';
+ $error[0] = 'ERROR';
+ return $error;
+ }
+ }
+ if (file_exists($destination_path . $file_name)) {
+ $file_name_in_use = true;
+ }
+ if ($file_name_in_use == true) {
+ $new_file_name = mktime() . $file_name;
+ $new_file_location = $destination_path . $new_file_name;
+ copy($form_field, $new_file_location);
+ $file_upload = $new_file_name;
+ $file_upload_array = array( $new_file_name, $new_file_location);
+ } else {
+ $new_file_name = $file_name;
+ $new_file_location = $destination_path.$new_file_name;
+ copy($form_field, $new_file_location);
+ $file_upload = $new_file_name;
+ $file_upload_array = array($new_file_name, $new_file_location);
+ }
+ if (is_file($new_file_location)) {
+ chmod($new_file_location, 0666);
+ }
+ return ($restricted) ? $file_upload_array : $file_upload;
+ }
+
+ // Misc. Functions
+
+ /**
+ * http_strip :Strips the http:// part from start of string
+ * @param $&$string : $string
+ *
+ * @return string $stirng minus http:// in front
+ * @access
+ **/
+ function http_strip(&$string)
+ {
+ $test_string = strtolower($string);
+ if(substr($test_string, 0, 7) == 'http://') {
+ $string = substr($string, 7);
+ }
+ }
+
+ /**
+ * footer : used for admin page footer to close out the top function
+ *
+ * @return void
+ * @access
+ **/
+ function footer()
+ {
+ echo "\n\t</body>\n</html>";
+ }
+
+ /**
+ * top :Output the starting html and admin table tags
+ * @param $message: The title
+ * @param $hp: The help file to use
+ * @param $$hp2 = NULL : The help file to use (links to gaslightmedia.com)
+ *
+ * @return void
+ * @access
+ **/
+ function top($message, $hp, $hp2 = NULL)
+ {
+ if ($hp2 != '') {
+ $help_guide = '<div id="glm-manual">';
+ /*
+ $help_guide = '<div id="glm-manual"><a id="manual-html"
+ href="http://www.gaslightmedia.com/manuals/html/'.$hp2.'.html"
+ target="_blank">Online Help Guide</a> ';
+ */
+ $help_guide .= '<a id="manual-pdf"
+ href="http://www.gaslightmedia.com/manuals/pdf/'.$hp2.'.pdf"
+ target="_blank">Printable Help Guide</a></div>';
+ }
+ $out = '
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+ <html>
+ <head>
+ <title>Untitled</title>
+ <meta http-equiv="content-type" content="text/html;charset=utf-8">
+ <link rel="stylesheet" type="text/css" href="../main.css">
+ <script type="text/javascript" src="'.GLM_APP_BASE_URL.'libjs/jquery/jquery-1.4.2.min.js"></script>
+ </head>
+ <body>
+ <h1>'.$message.'</h1>
+ ' . $help_guide;
+ echo $out;
+ }
+
+ /**
+ * top2 : alias to top()
+ * @param $message: message title
+ * @param $hp: help file
+ * @param $$hp2 = NULL : gaslight help file
+ *
+ * @return
+ * @access
+ **/
+ function top2($message, $hp,$hp2 = NULL) {
+ // make this an alias to top()
+ // by calling top instead of adding extra code
+ top($message, $hp, $hp2);
+
+ }
+
+ /********************************************************************************
+ *
+ * DO NOT EDIT THIS SECTION
+ *
+ ********************************************************************************/
+
+ if ($DEBUG) {
+ echo '<CENTER>
+ <TABLE BORDER=0 CELLPADDING=3 CELLSPACING=1 WIDTH=600 BGCOLOR="#000000" ALIGN="CENTER">
+ <TR VALIGN="middle" BGCOLOR="#9999CC">
+ <TD COLSPAN="2" ALIGN="center"><H1>Portable Site Data - setup.phtml </H1></TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>CVS Version Id:</B></TD>
+ <TD ALIGN="left">$Id: setup_functions.phtml,v 1.7 2010/06/17 12:50:52 jamie Exp $</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>SITENAME</B></TD>
+ <TD ALIGN="left">'.SITENAME.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>BASE</B></TD>
+ <TD ALIGN="left">'.BASE.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>UP_BASE</B></TD>
+ <TD ALIGN="left">'.UP_BASE.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>HELP_BASE</B></TD>
+ <TD ALIGN="left">'.HELP_BASE.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>IMG_BASE</B></TD>
+ <TD ALIGN="left">'.IMG_BASE.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>URL_BASE</B></TD>
+ <TD ALIGN="left">'.URL_BASE.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>CONN_STR</B></TD>
+ <TD ALIGN="left">'.CONN_STR.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>STYLE</B></TD>
+ <TD ALIGN="left">'.STYLE.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>ORIGINAL_PATH</B></TD>
+ <TD ALIGN="left">'.ORIGINAL_PATH.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>RESIZED_PATH</B></TD>
+ <TD ALIGN="left">'.RESIZED_PATH.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>MIDSIZED_PATH</B></TD>
+ <TD ALIGN="left">'.MIDSIZED_PATH.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>THUMB_PATH</B></TD>
+ <TD ALIGN="left">'.THUMB_PATH.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>ORIGINAL</B></TD>
+ <TD ALIGN="left">'.ORIGINAL.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>RESIZED</B></TD>
+ <TD ALIGN="left">'.RESIZED.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>MIDSIZED</B></TD>
+ <TD ALIGN="left">'.MIDSIZED.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>THUMB</B></TD>
+ <TD ALIGN="left">'.THUMB.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>$CALLED_FROM_DIR</B></TD>
+ <TD ALIGN="left">'.$CALLED_FROM_DIR.' </TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>$BASE_PATH</B></TD>
+ <TD ALIGN="left">'.$BASE_PATH.'</TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>$BASE_URL</B></TD>
+ <TD ALIGN="left"><A HREF="'.$BASE_URL.'">'.$BASE_URL.'</A></TD>
+ </TR>
+ <TR VALIGN="baseline" BGCOLOR="#CCCCCC">
+ <TD BGCOLOR="#CCCCFF" ><B>$BASE_SECURE_URL</B></TD>
+ <TD ALIGN="left">'.$BASE_SECURE_URL.'</TD>
+ </TR>
+ </TABLE>
+
+ <P>
+ <HR WIDTH="600">
+ <P>
+ </CENTER>
+ ';
+ }
+
+ /**
+ * date_entry : Generate the select boxes for date entry
+ * month-day-year as drop down select
+ * @param $month:
+ * @param $day:
+ * @param $year:
+ * @param $month_name: name of select month
+ * @param $day_name: name of select day
+ * @param $$year_name : name of select year
+ *
+ * @return
+ * @access
+ **/
+ 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 = '<select id="'.$month_name.'" name="'.$month_name.'" '.$onChange.'>';
+ for ($i = 1; $i < 13; ++$i) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= '0';
+ }
+ $date .= $i.'"';
+ if ($i == $month) {
+ $date .= ' selected';
+ }
+ $date .= ">$i";
+ }
+ $date .= '</select>';
+ $date .= '<select id="'.$day_name.'" name="'.$day_name.'" '.$onChange.'>';
+ for ($i = 1; $i < 32; ++$i) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= "0";
+ }
+ $date .= $i.'"';
+ if($i == $day) {
+ $date .= ' selected';
+ }
+ $date .= ">$i";
+ }
+ $date .= '</select>';
+ $date .= '<select id="'.$year_name.'" name="'.$year_name.'" '.$onChange.'>';
+ for ($i = 2000; $i < 2023; ++$i) {
+ $date .= '<option value="'.$i.'"';
+ if ($i == $year) {
+ $date .= ' selected';
+ }
+ $date .= ">$i";
+ }
+ $date .= '</select>';
+ return $date;
+ }
+
+ /**
+ * contact_date_entry : build select boxes for date entry going backwords in years
+ * @param $month:
+ * @param $day:
+ * @param $year:
+ * @param $month_name: name of select month
+ * @param $day_name: name of select day
+ * @param $$year_name : name of select year
+ *
+ * @return void
+ * @access
+ **/
+ function contact_date_entry($month, $day, $year, $month_name, $day_name, $year_name)
+ {
+ $cur_date = getdate();
+
+ if ($month == '') {
+ $month = $cur_date['mon'];
+ }
+ if ($day == '') {
+ $day = $cur_date['mday'];
+ }
+ if ($year == '') {
+ $year = $cur_date['year'];
+ }
+ $date = '<select name="'.$month_name.'">';
+ for ($i = 1; $i < 13; ++$i) {
+ $date .= '<option value="';
+ if ($i < 10) {
+ $date .= '0';
+ }
+ $date .= $i.'"';
+ if ($i == $month) {
+ $date .= ' selected';
+ }
+ $date .= ">$i";
+ }
+ $date .= '</select>';
+ $date .= '<select name="'.$day_name.'">';
+ for ($i = 1; $i < 32; ++$i) {
+ $date .= '<option value="';
+ if($i < 10) {
+ $date .= '0';
+ }
+ $date .= $i.'"';
+ if ($i == $day) {
+ $date .= ' selected';
+ }
+ $date .= ">$i";
+ }
+ $date .= '</select>';
+ $date .= '<select name="'.$year_name.'">';
+ $ystart = $cur_date['year'] - 10;
+ for ($i = $ystart; $i <= $year; ++$i) {
+ $date .= '<option value="'.$i.'"';
+ if ($i == $year) {
+ $date .= ' selected';
+ }
+ $date .= ">$i";
+ }
+ $date .= '</select>';
+ return $date;
+ }
+
+ /**
+ * time_entry : build select boxes for time entry
+ * @param $H:
+ * @param $m:
+ * @param $F:
+ * @param $H_name: name of select hour
+ * @param $m_name: name of select min
+ * @param $$F_name : name of select sec
+ *
+ * @return
+ * @access
+ **/
+ function time_entry($H, $m, $F, $H_name, $m_name, $F_name)
+ {
+ $cur_date = getdate();
+ if ($H == '') {
+ $H = $cur_date['hours'];
+ }
+ if ($m == '') {
+ $m = $cur_date['minutes'];
+ }
+ if ($H > 12) {
+ $F = 'PM';
+ $H = $H - 12;
+ }
+ $time = "Hr:<select name=\"$H_name\" size=\"1\">";
+ for ($i = 1; $i <= 12; ++$i) {
+ $time .= "<option value=\"";
+ if ($i < 10) {
+ $time .= "0";
+ }
+ $time .= "$i\"";
+ if ($i == $H) {
+ $time .= " selected";
+ }
+ $time .= ">$i\n";
+ }
+ $time .= "</select>\n";
+ $time .= "Min:<select name=\"$m_name\" size=\"1\">";
+ for ($i = 0; $i < 60; $i = $i + 15) {
+ $time .= "<Option value=\"";
+ if ($i < 10) {
+ $time .= "0";
+ }
+ $time .= "$i\"";
+ if ($i == $m) {
+ $time .= " selected";
+ }
+ $time .= ">";
+ if ($i < 10) {
+ $time .= "0";
+ }
+ $time .= "$i\n";
+ }
+ $time .= "</select>";
+ $time .= "<select name=\"$F_name\" size=\"1\">";
+ $time .= "<option value=\"AM\"";
+ if ($F == "AM") {
+ $time .= " selected";
+ }
+ $time .= ">AM\n";
+ $time .= "<option value=\"PM\"";
+ if ($F == "PM") {
+ $time .= " selected";
+ }
+ $time .= ">PM\n";
+ $time .= "</select>\n";
+ return $time;
+ }
+
+ /**
+ * get_parentid: get the (highest level) parent category for this id
+ * @param $id: id from bus_category table
+ *
+ * @return int parent
+ * @access
+ **/
+ function get_parentid($id)
+ {
+ static $parentshow;
+ if ($id == 0) {
+ return 0;
+ }
+ if (!is_array($parentshow)) {
+ $sql = "
+ SELECT parent
+ FROM bus_category
+ WHERE id = $id";
+ $parentrow = db_auto_get_data($qs);
+ }
+ if ($parentrow[0]['parent'] == 0) {
+ return $id;
+ } else {
+ return get_parentid($parentrow[0]['parent']);
+ }
+ }
+
+ /**
+ * build_picklist:Builds a pick list from an array
+ * @param $fieldname: fieldname field name for select
+ * @param $data: data array of data
+ * @param $selected: selected witch element is selected
+ * @param $$type = "standard": type Standard,multi
+ * @param $$auto = 0: auto
+ * @param $$width = NULL : width width controlled by css
+ *
+ * @return void
+ * @access
+ **/
+ 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 = "<select name=\"".$fieldname."\" multiple size=\"10\" ".$autosubmit.">\n";
+ while( list($key, $val) = each($data) ) {
+ if( in_array($key,$sel) ) {
+ $select = " selected ";
+ }
+ else
+ $select = "";
+ $str .= " <option value=\"$key\"".$select.">$val\n";
+ }
+ break;
+ case "simple":
+ $str = "<select name=\"$fieldname\" ".$autosubmit.">\n";
+ for( $i=0 ; $i<count($data) ; $i++ ) {
+ $select = (in_array($data[$i],$sel)) ? " selected ":"";
+ $str .= " <option value=\"".$data[$i]."\"".$select.">".$data[$i]."\n";
+ }
+ break;
+
+ case "standard":
+ default:
+ $str = "<select name=\"$fieldname\" ".$autosubmit.">\n";
+ while( list($key, $val) = each($data) ) {
+ $select = (in_array($key,$sel)) ? " selected ":"";
+ $str .= " <option value=\"$key\"".$select.">$val\n";
+ }
+ break;
+ }
+ $str .= "</select>\n";
+
+ return $str;
+
+ }
+
+ /**
+ * create_page_links:Create prev and next links
+ * to page through the results.
+ * @param $totalnum: The total result of the query
+ * @param $num: The total result for the page
+ * @param $$start=0: The starting num defaults to 0
+ * @param $params: variables to add to the url
+ * @param $ENTRIES_PER_PAGE: number of items on page defaults to the ENTRIES_PER_PAGE
+ *
+ * @return string of links
+ * @access
+ **/
+ function create_page_links($totalnum,$num,$start=0,$params,$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 = "<span class=\"accenttext\">[</span><a class=\"small\"
+ href=\"$GLOBALS[PHP_SELF]?start=".$last."&$params\">PREVIOUS PAGE</a><span
+ class=\"accenttext\"> ]</span>";
+ if($end < $totalnum)
+ $next = "<span class=\"accenttext\">[</span><a class=\"small\"
+ href=\"$GLOBALS[PHP_SELF]?start=".$end."&$params\">NEXT PAGE</a><span
+ class=\"accenttext\"> ]</span>";
+ else
+ $next = "";
+ $starting = $start + 1;
+ $last_c = $start + $num;
+ $links = '<center><span class="pagetitle">Listings Displayed: </span><span
+ class="accenttext">'.$starting.' to '.$last_c.'</span>
+ <span class="pagetitle"> of '.$totalnum.'<br></span> '.$prev. ' <span
+ class="pagetitle"></span> '.$next.'<BR></span></center>';
+ return $links;
+ }
+?>
--- /dev/null
+\r
+/*======== UNIVERSAL STYLES ========*/\r
+body {\r
+ background: #eddbcc;\r
+ font-family: arial, sans-serif;\r
+ font-size: 13px;\r
+ text-align: center;\r
+ margin: 0;\r
+ padding: 0;\r
+ }\r
+img {\r
+ border: 0;\r
+ }\r
+ul, li {\r
+ list-style-type: none;\r
+ margin: 0;\r
+ padding: 0;\r
+ display: block;\r
+ }\r
+ \r
+#wrapper {\r
+ margin: 0 auto;\r
+ text-align: left;\r
+ width: 990px;\r
+ background: url(assets/bgRepeat.png) repeat-y white;\r
+ }\r
+#wrapperInner {\r
+ height: 1%;\r
+ overflow: hidden;\r
+ background: url(assets/bgInside.jpg) no-repeat;\r
+ }\r
+ \r
+/*======== HEADER ========*/\r
+#top {\r
+ height: 150px;\r
+ position: relative;\r
+ }\r
+#logo {\r
+ position: absolute;\r
+ left: 330px;\r
+ top: 65px;\r
+ }\r
+#nav {\r
+ margin: 0 20px;\r
+ height: 1%;\r
+ overflow: hidden;\r
+ }\r
+#nav li {\r
+ float: left;\r
+ }\r
+#nav a {\r
+ display: block;\r
+ padding: 14px 23px 14px 13px;\r
+ text-decoration: none;\r
+ font-size: 14px;\r
+ background: url(assets/divider.png) no-repeat right center;\r
+ }\r
+#nav a:link {\r
+ color: #115280;\r
+ }\r
+#nav a:visited {\r
+ color: #115280;\r
+ }\r
+#nav a:hover {\r
+ color: #947235;\r
+ text-decoration: underline;\r
+ }\r
+#nav a:active {\r
+ color: #115280;\r
+ }\r
+\r
+/*======== HOME PAGE STYLES ========*/ \r
+#home #wrapperInner {\r
+ background-image: url(assets/bg.jpg);\r
+ }\r
+#main {\r
+ margin: 0 50px;\r
+ }\r
+#home #category {\r
+ margin-right: 350px;\r
+ }\r
+/*======== INSIDE PAGE STYLES ========*/\r
+#breadcrumbs {\r
+ font-size: 11px;\r
+ font-weight: normal;\r
+ text-transform: uppercase;\r
+ margin-left: 14px;\r
+ color: #44432b;\r
+\r
+}\r
+#breadcrumbs a {\r
+ color: #000;\r
+ text-decoration: none;\r
+ font-weight: bold;\r
+ margin: 0 3px;\r
+}\r
+#breadcrumbs a:hover { color: #ababab; }\r
+\r
+#column {\r
+ width: 200px;\r
+ float: left;\r
+ }\r
+#subnav {\r
+ margin: 16px 19px;\r
+ background: url(assets/subnavBg.jpg) no-repeat white;\r
+ }\r
+#subnav h2 {\r
+ padding: 17px 0 7px 14px;\r
+ color: #947235;\r
+ font-size: 18px;\r
+ margin: 0;\r
+ }\r
+#subnav ul {\r
+ }\r
+#subnav a {\r
+ display: block;\r
+ text-decoration: none;\r
+ padding: 7px 14px;\r
+ }\r
+#subnav a:link {\r
+ color: #947235;\r
+ }\r
+#subnav a:visited {\r
+ color: #947235;\r
+ }\r
+#subnav a:hover {\r
+ color: #FFF;\r
+ background: #8da0ab;\r
+ }\r
+#subnav a:active {\r
+ color: #947235;\r
+ }\r
+#inside #main {\r
+ float: left;\r
+ width: 720px;\r
+ margin: 0 0 0 30px;\r
+ }\r
+ \r
+/*======== TOOLBOX STYLES ========*/\r
+#toolbox h1, #toolbox h2 {\r
+ font-family: 'century gothic', arial, helvetica, sans-serif;\r
+ font-weight: normal;\r
+ font-size: 20px;\r
+ }\r
+\r
+#paragraphLinks a{\r
+ text-decoration: none;\r
+ padding: 2px 7px;\r
+}\r
+#paragraphLinks a:link{\r
+ color: #947235;\r
+}\r
+#paragraphLinks a:visited {\r
+ color: #947235;\r
+ }\r
+#paragraphLinks a:hover {\r
+ color: #FFF;\r
+ background: #8da0ab;\r
+ }\r
+#paragraphLinks a:active {\r
+ color: #947235;\r
+ }.imageleft {\r
+ float: left;\r
+ margin: 0 10px 10px 0;\r
+ }\r
+.imageright {\r
+ float: right;\r
+ margin: 0 0 10px 10px;\r
+ }\r
+.imagecaption {\r
+ font-size:10px;\r
+ color: #516d88;\r
+ }\r
+.listing {\r
+ clear: both;\r
+ }\r
+ \r
+/*======== FOOTER ========*/\r
+#footer {\r
+ background: url(assets/footerBg.png) no-repeat;\r
+ height: 57px;\r
+ clear: both;\r
+ }\r
+#footer p {\r
+ padding-top: 23px;\r
+ margin: 0;\r
+ font-family: 'century gothic' helvetica, sans-serif;\r
+ font-size: 13px;\r
+ text-align: center;\r
+ color: white;\r
+ font-weight: bold;\r
+ }\r
+#accreditations {\r
+ position: relative;\r
+ height: 100px;\r
+ }\r
+#accreditations li {\r
+ position: absolute;\r
+ background-image: url(assets/accreditationsBg.png);\r
+ text-indent: -9000px;\r
+ }\r
+#aAAD {\r
+ top: 10px;\r
+ left: 175px;\r
+ background-position: 0 0;\r
+ width: 74px;\r
+ height: 73px;\r
+ }\r
+#aABD {\r
+ top: 10px;\r
+ left: 315px;\r
+ background-position: -74px 0;\r
+ width: 72px;\r
+ height: 73px;\r
+ }\r
+#aACMS {\r
+ top: 20px;\r
+ left: 458px;\r
+ background-position: -146px 0;\r
+ width: 161px;\r
+ height: 73px;\r
+ }\r
+#aASDS {\r
+ top: 20px;\r
+ left: 680px;\r
+ background-position: -307px 0;\r
+ width: 140px;\r
+ height: 73px;\r
+ }\r
+ \r
+#copyright{\r
+ text-align:center;\r
+ background:#EDDBCC;\r
+ clear:both;\r
+ font-size:10px;\r
+ padding: 20px 0;\r
+ } \r
--- /dev/null
+<div id="sitemap">
+ <ol>
+ <li flexy:foreach="nav,main">
+ <h2><a href="{main[url]:h}">{main[label]:h}</a></h2>
+ {if:main[subs]}
+ <?php
+ $t->chunks = array_chunk($main['subs'], 3, true);
+ ?>
+ <div class="row" flexy:foreach="chunks,chunky">
+ <ol>
+ <li flexy:foreach="chunky,chunk">
+ <a href="{chunk[url]:h}">{chunk[label]:h}</a>
+ {if:chunk[subs]}
+ <ol>
+ <li flexy:foreach="chunk[subs],subs,sChunk">
+ <a href="{sChunk[url]:h}">{sChunk[label]:h}</a>
+
+ {if:sChunk[subs]}
+ <ol>
+ <li flexy:foreach="sChunk[subs],subs2,sChunk2">
+ <a href="{sChunk2[url]:h}">{sChunk2[label]:h}</a>
+ </li>
+ </ol>
+ {end:}
+ </li>
+ </ol>
+ {end:}
+ </li>
+ </ol>
+ </div>
+ {end:}
+ </li>
+ </ol>
+</div>
\ No newline at end of file
--- /dev/null
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<title>{pageTitle:h}</title>
+<meta http-equiv="content-type" content="text/html;charset=utf-8">
+<meta name="description" content="{metaTags:h}">
+<meta http-equiv="imagetoolbar" content="no">
+<meta http-equiv="imagetoolbar" content="false">
+{styles:h}
+{topScripts:h}
+</head>
+<body id="inside"><!-- body id home on homepage only , #inside for inside pages-->
+<div id="wrapper">
+ <div id="wrapperInner">
+ <div id="top">
+ <a href="baseurl/index.php">
+ <img id="logo" src="baseurl/assets/logo.png" width="520" height="50">
+ </a>
+ </div><!-- /#top -->
+ <ul id="nav">
+ <li><a href="#">Home</a></li>
+ <li><a href="#">Services</a></li>
+ <li><a href="#">Patient Information</a></li>
+ <li><a href="#">About Us</a></li>
+ <li><a href="#">Location</a></li>
+ <li id="lastli"><a href="#">Contact Us</a></li>
+ </ul>
+ <div id="column">
+ <div id="subnav"><!-- only if there are subpages -->
+ <h2>Services</h2>
+ <ul>
+ <li><a href="#">Navigation Name</a></li>
+ <li><a href="#">Halloisann hu</a></li>
+ <li><a href="#">Lorem Ipsum</a></li>
+ <li><a href="#">Navigator Tools</a></li>
+ <li><a href="#">Nav</a></li>
+ <li><a href="#">Navigation Name</a></li>
+ <li><a href="#">Halloisann hu</a></li>
+ <li><a href="#">Lorem Ipsum</a></li>
+ <li><a href="#">Navigator Tools</a></li>
+ <li></li>
+ </ul>
+ </div><!-- /#subnav -->
+ </div><!-- /#column -->
+ <div id="main">
+ <div id="toolbox">
+ <div id="category">
+ <h1>Page Header</h1>
+ <div class="imageright">
+ <img src="baseurl/assets/toolboxTMP.gif" width="325" height="218" alt="toolboxTMP (26K)">
+ <div class="imagecaption">This is the imagecaption</div>
+ </div><!-- /..imageright -->
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ </div><!-- /#category -->
+ <div class="listing">
+ <h2>Header</h2>
+ <div class="imageleft">
+ <img src="baseurl/assets/toolboxTMP.gif" width="325" height="218" alt="toolboxTMP (26K)">
+ <div class="imagecaption">This is the imagecaption</div>
+ </div><!-- /..imageleft -->
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ </div><!-- /.listin\g -->
+ <div class="listing">
+ <h2>Header</h2>
+ <div class="imageright">
+ <img src="baseurl/assets/toolboxTMP.gif" width="325" height="218" alt="toolboxTMP (26K)">
+ <div class="imagecaption">This is the imagecaption</div>
+ </div><!-- /..imageright -->
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ <p>Located in the exact center of Northern Michigan on the 45th parallel, Gaylord is unique because of its stunning surroundings, up north ambience and easy commuting access. </p>
+ </div><!-- /.listin\g -->
+ </div><!-- /#toolbox -->
+ </div><!-- /#main -->
+ <div id="footer">
+ <p>Dermatology Associates of Northern Michigan, P.C. 2240 Mitchell Park Petoskey, MI 49770 · 231-487-2230</p>
+ </div>
+ <ul id="accreditations">
+ <li id="aAAD">AAD</li>
+ <li id="aABD">ABD</li>
+ <li id="aACMS">ACMS</li>
+ <li id="aASDS">ASDS</li>
+ </ul>
+ <div id="copyright">
+ Copyright©<?php echo date('Y');?> {siteName:h} - Produced by <a href="http://www.gaslightmedia.com">Gaslight Media</a>, All Rights Reserved.
+ </div><!-- /#copyright -->
+ </div><!-- /#wrapperInner" -->
+</div><!-- /#wrapper -->
+{bottomScripts:h}
+</body>
+</html>