From: Steve Sutton Date: Fri, 6 Jun 2014 14:01:09 +0000 (-0400) Subject: initial setup of soolocks X-Git-Tag: v1.0~1 X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/?a=commitdiff_plain;h=70aec97a89c02f703acb70c9073bd0b7b87f629c;p=web%2FSooLocks.git initial setup of soolocks --- 70aec97a89c02f703acb70c9073bd0b7b87f629c diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..460675a --- /dev/null +++ b/.htaccess @@ -0,0 +1,138 @@ + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + +ErrorDocument 404 /404.html +RewriteEngine On +AddDefaultCharset utf-8 + +RewriteBase /www.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 ## +############### + diff --git a/Toolkit/BaseControllerAbstract.php b/Toolkit/BaseControllerAbstract.php new file mode 100644 index 0000000..176c7f3 --- /dev/null +++ b/Toolkit/BaseControllerAbstract.php @@ -0,0 +1,50 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +/** + * Toolkit_BaseControllerAbstract + * + * Creates object of toolkit registry + * + * @category Toolkit + * @package Toolkit_BaseControllerAbstract + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_BaseControllerAbstract +{ + /** + * Description of $registry + * @var Toolkit_Registry + * @access protected + */ + protected $registry; + + /** + * Class constructor + * + * Creates object of Toolkit Registry + * + * @param Toolkit_Registry $registry Toolkit Registry + */ + public function __construct(Toolkit_Registry $registry) + { + $this->registry = $registry; + } +} +?> diff --git a/Toolkit/BreadCrumbsFactory.php b/Toolkit/BreadCrumbsFactory.php new file mode 100644 index 0000000..6ca0be2 --- /dev/null +++ b/Toolkit/BreadCrumbsFactory.php @@ -0,0 +1,85 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_BreadCrumbsFactory + * + * Description of Toolkit_BreadCrumbsFactory + * + * @category Toolkit + * @package Members_MembersOnly + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_BreadCrumbsFactory +{ + /** + * Description of $_gatewayFactory + * @var Toolkit_Toolbox_GatewayFactoryAbstract + * @access private + */ + private $_gatewayFactory; + + /** + * Class constructor + * + * @param Toolkit_Toolbox_GatewayFactoryAbstract $factory Gateway Factory + * + * @return void + * @access public + */ + public function __construct( + Toolkit_Toolbox_GatewayFactoryAbstract $factory + ) { + $this->_gatewayFactory = $factory; + } + + /** + * Description for createBreadCrumbsHelper + * + * @return \Toolkit_Template_BreadCrumbs + * @access public + */ + public function createBreadCrumbsHelper() + { + $gateway = $this->_gatewayFactory->createGateway(); + if (isset($_GET['member_id']) + && ctype_digit((string)$_GET['member_id']) + ) { + $breadCrumbs = new Toolkit_Members_BreadCrumbs( + $gateway, + Toolkit_Database::getInstance() + ); + } elseif ($gateway instanceof Toolkit_Toolbox_PageGatewayDraft) { + // Need to have a publish gateway so we can get parent pages + $publishGateway = new Toolkit_Toolbox_PageGatewayPublish( + Toolkit_Database::getInstance() + ); + + $breadCrumbs = new Toolkit_Template_DraftBreadCrumbs( + $publishGateway, + $gateway + ); + } else { + $breadCrumbs = new Toolkit_Template_BreadCrumbs($gateway); + } + + return $breadCrumbs; + } +} +?> diff --git a/Toolkit/CKImages/Connector.php b/Toolkit/CKImages/Connector.php new file mode 100644 index 0000000..f97d172 --- /dev/null +++ b/Toolkit/CKImages/Connector.php @@ -0,0 +1,400 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Connector.php,v 1.15 2010/07/20 01:19:50 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + + +/** + * Connects the CKImage browser to the server for image manipulation + * + * @category CKImages + * @package Toolkit_CKImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + */ +class Toolkit_CKImages_Connector +{ + // {{{ setDbh() + + /** + * Sets the database handler for the object to use + * + * @param PDO $pdo PHP Data Object + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ createFolder() + + /** + * Creates a new folder + * + * @return void + * @access public + */ + public function createFolder() + { + // get the folder id + $folder = filter_var( + $_GET['name'], + FILTER_SANITIZE_STRING, + FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH + ); + if ($parent = filter_var($_GET['folder'], FILTER_VALIDATE_INT)) { + // do nothing, $parent set and validated + // from the $_GET['folder'] variable + } else { + $parent = 1; + } + + // if the parentFolder variable is set and valid, then override the + // existing parent folder value + if ($newParent = filter_var($_GET['parentFolder'], FILTER_VALIDATE_INT)) { + $parent = $newParent; + } + + // unset unneeded param values + unset($_GET['command'], $_GET['name'], $_GET['parentFolder']); + + try { + $sql = " + INSERT INTO ckeditor_folders(name, parent) + VALUES (:name, :parent)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $folder, PDO::PARAM_INT); + $stmt->bindParam(':parent', $parent, PDO::PARAM_INT); + $stmt->execute(); + header('Location:' . MEDIA_BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ deleteFile() + + /** + * Deletes a file from the image server for client + * + * @param Toolkit_FileServer_ImageAdapter $ia Image Server Object + * + * @return void + * @access public + */ + public function deleteFile(Toolkit_FileServer_ImageAdapter $ia) + { + $getImg = filter_input(INPUT_GET, 'img'); + // Get offset where target img starts at + $start = strrpos($getImg, '/') + 1; + // get the image name + $img = substr($getImg, $start); + // unset unneeded param values + unset($_GET['command'], $_GET['img']); + + $ia->delete($img); + + try { + $sql = " + DELETE FROM ckeditor_images + WHERE name_on_disk = :nod"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':nod', $img, PDO::PARAM_STR); + $stmt->execute(); + header('Location:' . MEDIA_BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ deleteFolder() + + /** + * Deletes a folder and any sub folders + * + * Moves all containing images to home folder so they are not + * inadvertently deleted + * + * @return void + * @access public + */ + public function deleteFolder() + { + // get the folder id + $folder = $_GET['folder']; + if ($folder == 1) { + unset($_COOKIE['glm_image_browser_open'], $_COOKIE['glm_image_browser_selected']); + header('Location:' . MEDIA_BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + exit(); + } + // unset unneeded param values + unset($_GET['command'], $_GET['tgt']); + $_GET['folder'] = 1; + + try { + $tree = Toolkit_Common::getHierarchicalTreeStructure( + $this->dbh, + 'ckeditor_folders', + 'id', + 'parent', + 'id', + $folder, + 0, + false + ); + + $sql = " + UPDATE ckeditor_images + SET folder = 1 + WHERE folder = :folder"; + + $imgStmt = $this->dbh->prepare($sql); + + $sql = " + DELETE FROM ckeditor_folders + WHERE id = :folder"; + $fldrStmt = $this->dbh->prepare($sql); + while (list($tgt) = each($tree)) { + $imgStmt->bindParam(':folder', $tgt, PDO::PARAM_INT); + $imgStmt->execute(); + + $fldrStmt->bindParam(':folder', $tgt, PDO::PARAM_INT); + $fldrStmt->execute(); + } + // These cookies are defined in the libjs/image_selector.js file + // when the tree is created. + unset($_COOKIE['glm_image_browser_open'], $_COOKIE['glm_image_browser_selected']); + header('Location:' . MEDIA_BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ browseImages() + + /** + * Creates the browser window + * + * @param HTML_Template_Flexy $tEngine Flexy Rendering Engine Object + * + * @return string HTML page to browse images + * @access public + */ + public function browseImages(HTMl_Template_Flexy $tEngine) + { + $page = new stdClass(); + $page->baseUrl = MEDIA_BASE_URL; + $page->glmAppBaseUrl = MEDIA_APP_BASE_URL; + $page->originalPath = CKIMAGE; + $page->imageManager = IMAGE_MANAGER; + + if ($folderId = filter_input(INPUT_GET, 'folder', FILTER_VALIDATE_INT)) { + $folder = "&folder=$folderId"; + } else { + $folder = ''; + } + + $ckEditorFuncNum + = filter_input(INPUT_GET, 'CKEditorFuncNum', FILTER_VALIDATE_INT); + $ckEditor = filter_input(INPUT_GET, 'CKEditor'); + $langCode = filter_input(INPUT_GET, 'langCode'); + + $form = new HTML_QuickForm( + 'quick_upload', + 'post', + MEDIA_BASE_URL . "Toolkit/CKImages/controller.php?CKEditor=$ckEditor&CKEditorFuncNum=$ckEditorFuncNum&langCode=$langCode&command=UploadFile$folder" + ); + $form->addElement('file', 'upload'); + $page->quickUploadForm = $form->toHtml(); + + $folders = new Toolkit_CKImages_Folders($this->dbh); + $page->folders = $folders->getFolders(0); + + try { + $ckEditorFolderId = $folderId ? $folderId : 1; + $sql = " + SELECT * + FROM ckeditor_images + WHERE folder = :folder + ORDER BY id ASC"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':folder', $ckEditorFolderId, PDO::PARAM_INT); + $stmt->execute(); + + $images = $stmt->fetchAll(PDO::FETCH_ASSOC); + // loop thru images and reset their sizes + $isa = new Toolkit_FileServer_ImageAdapter(); + if (is_array($images) && !empty($images)) { + foreach ($images as &$img) { + if ( $img['original_width'] > 700 + || $img['original_height'] > 500 + ) { + // get real size for the CKImage Style + $imgData = $isa->getImageSize(CKIMAGE . $img['name_on_disk']); + $img['original_width'] = $imgData[0]; + $img['original_height'] = $imgData[1]; + } + } + } + $page->images = $images; + $page->CKEditorFuncNum = $ckEditorFuncNum; + + $tEngine->compile('thumbnails.html'); + $tEngine->outputObject($page); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ handleUpload() + + + /** + * Handles inserting the upload into the database + * + * @param string $imageName image to insert + * @param array $dimensions dimensions of the image + * + * @return object Return description (if any) ... + * @access protected + */ + protected function handleUpload($imageName, array $dimensions) + { + if ( !$dimensions['oWidth'] + || !$dimensions['oHeight'] + ) { + return false; + } + try { + if ($folder = filter_input(INPUT_GET, 'folder', FILTER_VALIDATE_INT)) { + // do nothing, $folder is already set and validated + } else { + $folder = 1; + } + $sql = " + INSERT INTO ckeditor_images (file_name, name_on_disk, folder, + original_width, original_height) + VALUES (:fname, :nod, :folder, :width, :height)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':fname', + $_FILES['upload']['name'], + PDO::PARAM_STR + ); + $stmt->bindParam(':nod', $imageName, PDO::PARAM_STR); + $stmt->bindValue(':folder', $folder, PDO::PARAM_INT); + $stmt->bindValue(':width', $dimensions['oWidth'], PDO::PARAM_INT); + $stmt->bindValue(':height', $dimensions['oHeight'], PDO::PARAM_INT); + + + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ quickUpload() + + + /** + * send uploaded image to image server + * + * @param Toolkit_FileServer_ImageAdapter $ia Image Server + * + * @return void + * @access public + */ + public function quickUpload(Toolkit_FileServer_ImageAdapter $ia) + { + try { + ob_start(); + $image = $ia->upload('upload'); + ob_end_clean(); + } catch (RangeException $e) { + Toolkit_Logger::logException('Runtime Error', $e); + throw new Toolkit_CKImages_Exception('Error uploading image'); + } + + $dimensions = $ia->getImageSize(CKIMAGE . $image['name']); + list($i['oWidth'], $i['oHeight'],) = $dimensions; + $this->handleUpload($image['name'], $i); + + unset($_GET['command']); + header('Location:' . MEDIA_BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } + + // }}} + + // {{{ uploadFile() + + + /** + * send uploaded image to image server and select that file to be used + * + * @param Toolkit_FileServer_ImageAdapter $ia Image server object + * + * @return void + * @access public + */ + public function uploadFile(Toolkit_FileServer_ImageAdapter $ia) + { + if ($ckEditorFuncNum = filter_input(INPUT_GET, 'CKEditorFuncNum', FILTER_VALIDATE_INT)) { + // Do nothing, $ckEditorFuncNum set and validated + } else { + $ckEditorFuncNum = 1; + } + echo ''; + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/Database/Import.php b/Toolkit/CKImages/Database/Import.php new file mode 100755 index 0000000..756e7cb --- /dev/null +++ b/Toolkit/CKImages/Database/Import.php @@ -0,0 +1,145 @@ +dbh = $pdo; + $this->pathToImages = BASE . 'images/ht_images/'; + $this->urlPathToImages = HT_IMAGES_URL; + $this->is = new Toolkit_Image_Server(); + } + // }}} + // {{{ addFolderToDatabase() + function addFolderToDatabase($folder, $parent) + { + static $stmt; + if (!$stmt) { + $sql = " + INSERT INTO ckeditor_folders + (name, parent) + VALUES + (:name, :parent) + RETURNING id"; + $stmt = $this->dbh->prepare($sql); + } + try { + $stmt->bindParam(":name", $folder, PDO::PARAM_STR); + $stmt->bindParam(":parent", $parent, PDO::PARAM_STR); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + // }}} + // {{{ addImageToDatabase() + function addImageToDatabase($file, $folder) + { + static $stmt; + if (!$stmt) { + $sql = " + INSERT INTO ckeditor_images + (file_name, name_on_disk, original_width, original_height, folder) + VALUES + (:file_name, :name_on_disk, :original_width, :original_height, :folder)"; + $stmt = $this->dbh->prepare($sql); + } + try { + $stmt->bindParam(":file_name", $file['file_name'], PDO::PARAM_STR); + $stmt->bindParam(":name_on_disk", $file['name_on_disk'], PDO::PARAM_STR); + $stmt->bindParam(":original_width", $file['original_width'], PDO::PARAM_STR); + $stmt->bindParam(":original_height", $file['original_height'], PDO::PARAM_STR); + $stmt->bindParam(":folder", $folder, PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + }// }}} + // {{{ processFilesArray + function processFilesArray($files, $parent = 1) + { + //echo '
'.print_r($files, true).'
'; + foreach ($files as $folderName => $file) { + if (is_array($file)) { + $fKey = key($file); + $folderToAdd = preg_replace("%/$%", "", $fKey); + //echo '
'.print_r($folderToAdd, true).'
'; + $folder = $this->addFolderToDatabase($folderToAdd, $parent); + //echo '
'.print_r($folder, true).'
'; + //var_dump($files[$folderName][$fKey]); + // echo '
'.print_r($file[$folderName][$fKey], true).'
'; + $processedFile[] = $this->processFilesArray($files[$folderName][$fKey], $folder); + } else { + $processedFile[] = $this->sendToImageServer($file, $parent); + } + } + return $processedFile; + } + // }}} + // {{{ readImageDir() + function readImageDir($path = '') + { + $dirName = $this->pathToImages . preg_replace("%/$%", "", $path); + //var_dump($dirName);echo '
'; + $d = dir($dirName); + while (false !== ($entry = $d->read())) { + if (!preg_match("%^\.|^CVS%", $entry)) { + $entryPath = $this->pathToImages . $path . $entry; + //var_dump($entryPath); echo '
'; + if ($dirCheck = is_dir($entryPath)) { + $files[$path][] = $this->readImageDir($path . $entry . '/'); + } else if ($fileCheck = is_file($entryPath)) { + $files[$path][] = $path . $entry; + } + } + } + return $files; + } + // }}} + //{{{ runImport() + function runImport() + { + $files = $this->readImageDir(); + echo '
'.print_r($files, true).'
'; + $processedFiles = $this->processFilesArray($files['']); +// echo '
'.print_r($processedFiles, true).'
'; + } + //}}} + // {{{ sendToImageServer() + function sendToImageServer($file, $folder) + { + $file_name = basename($file); + $size = getImageSize($this->pathToImages . $file); + try { + $urlToImage = $this->urlPathToImages . '/' . str_replace(' ', '%20', $file); + $name_on_disk = $this->is->imageUpload( + $urlToImage + ); +// var_dump($name_on_disk); +// var_dump($this->urlPathToImages); +// exit; + } catch(PEAR_Exception $e) { + var_dump($file); + var_dump($urlToImage); + var_dump($e); + exit; + } + $image = array( + 'name_on_disk' => $name_on_disk, + 'file_name' => $file_name, + 'original_width' => $size[0], + 'original_height' => $size[1], + ); + $this->addImageToDatabase($image, $folder); + } + // }}} +} +?> diff --git a/Toolkit/CKImages/Database/application.sql b/Toolkit/CKImages/Database/application.sql new file mode 100644 index 0000000..d3abc1e --- /dev/null +++ b/Toolkit/CKImages/Database/application.sql @@ -0,0 +1,21 @@ +CREATE SCHEMA ckimages; +GRANT ALL ON SCHEMA ckimages TO nobody; + +-- +-- Tables +-- +\i ./tables/ckeditor_folders.sql +\i ./tables/ckeditor_images.sql + +-- +-- Procedures +-- + +-- +-- Modules +-- + +-- +-- Data +-- +\i ./data/applicationData.sql diff --git a/Toolkit/CKImages/Database/data/applicationData.sql b/Toolkit/CKImages/Database/data/applicationData.sql new file mode 100644 index 0000000..e4159a5 --- /dev/null +++ b/Toolkit/CKImages/Database/data/applicationData.sql @@ -0,0 +1,2 @@ +INSERT INTO ckimages.ckeditor_folders(id, name, parent) VALUES(1, 'Home', 0); +SELECT setval('"ckimages".ckeditor_folders_id_seq', 2, false); diff --git a/Toolkit/CKImages/Database/importHtImages.php b/Toolkit/CKImages/Database/importHtImages.php new file mode 100755 index 0000000..5aaa481 --- /dev/null +++ b/Toolkit/CKImages/Database/importHtImages.php @@ -0,0 +1,10 @@ +runImport(); +?> diff --git a/Toolkit/CKImages/Database/phpImageEditorUpdates.sql b/Toolkit/CKImages/Database/phpImageEditorUpdates.sql new file mode 100644 index 0000000..28b86c2 --- /dev/null +++ b/Toolkit/CKImages/Database/phpImageEditorUpdates.sql @@ -0,0 +1,2 @@ +ALTER TABLE ckimages.ckeditor_images + ADD COLUMN original_image TEXT; diff --git a/Toolkit/CKImages/Database/removeApplication.sql b/Toolkit/CKImages/Database/removeApplication.sql new file mode 100644 index 0000000..4cd6978 --- /dev/null +++ b/Toolkit/CKImages/Database/removeApplication.sql @@ -0,0 +1,9 @@ +-- +-- This will drop everything in the ckimages schema +-- Nothing better be in here except ckeditor related object +-- or it will be dropp +-- +-- The force is strong w/ this one, use it wisely. +-- + +DROP SCHEMA IF EXISTS ckimages CASCADE; diff --git a/Toolkit/CKImages/Database/tables/ckeditor_folders.sql b/Toolkit/CKImages/Database/tables/ckeditor_folders.sql new file mode 100644 index 0000000..1331175 --- /dev/null +++ b/Toolkit/CKImages/Database/tables/ckeditor_folders.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS ckimage.ckeditor_folders CASCADE; + +CREATE TABLE ckimages.ckeditor_folders +(id SERIAL, + name TEXT NOT NULL, + parent INTEGER DEFAULT 1 NOT NULL, + PRIMARY KEY (id)); + +GRANT ALL ON ckimages.ckeditor_folders_id_seq TO nobody; +GRANT ALL ON ckimages.ckeditor_folders TO nobody; diff --git a/Toolkit/CKImages/Database/tables/ckeditor_images.sql b/Toolkit/CKImages/Database/tables/ckeditor_images.sql new file mode 100644 index 0000000..a693799 --- /dev/null +++ b/Toolkit/CKImages/Database/tables/ckeditor_images.sql @@ -0,0 +1,19 @@ +DROP TABLE IF EXISTS ckimages.ckeditor_images CASCADE; + +CREATE TABLE ckimages.ckeditor_images +(id SERIAL, + create_date DATE DEFAULT CURRENT_DATE, + file_name text NOT NULL, + name_on_disk text NOT NULL, + original_width TEXT NOT NULL, + original_height TEXT NOT NULL, + original_image TEXT, + folder INTEGER DEFAULT 1 + REFERENCES ckimages.ckeditor_folders (id) + ON UPDATE CASCADE + ON DELETE SET DEFAULT, + PRIMARY KEY (id) +); + +GRANT ALL ON ckimages.ckeditor_images_id_seq TO nobody; +GRANT ALL ON ckimages.ckeditor_images TO nobody; diff --git a/Toolkit/CKImages/Exception.php b/Toolkit/CKImages/Exception.php new file mode 100644 index 0000000..3ea1bbd --- /dev/null +++ b/Toolkit/CKImages/Exception.php @@ -0,0 +1,3 @@ + diff --git a/Toolkit/CKImages/Factory.php b/Toolkit/CKImages/Factory.php new file mode 100644 index 0000000..a693896 --- /dev/null +++ b/Toolkit/CKImages/Factory.php @@ -0,0 +1,83 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Factory.php,v 1.1 2009/09/24 14:43:02 jamie Exp $ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ + + +/** + * CKImage Factory + * + * @category CKImages + * @package Toolkit_CKImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ +class Toolkit_CKImages_Factory +{ + // {{{ properties + + /** + * array of instances + * @var array + * @access public + * @static + */ + public static $instances = array(); + + // }}} + // {{{ init() + + /** + * initialize the factory + * + * @return void + * @access public + * @static + */ + public static function init() + { + } + + // }}} + // {{{ &instance() + + /** + * Get a single instance of an object + * + * @param string $class Class name to create + * + * @return mixed instantiated object + * @access public + * @static + */ + public static function &instance($class) + { + $class = "Toolkit_CKImages_$class"; + + if (empty(Toolkit_CKImages_Factory::$instances)) { + Toolkit_CKImages_Factory::$instances[$class] = new $class; + } + + return Toolkit_CKImages_Factory::$instances[$class]; + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/Folders.php b/Toolkit/CKImages/Folders.php new file mode 100644 index 0000000..2e24e47 --- /dev/null +++ b/Toolkit/CKImages/Folders.php @@ -0,0 +1,243 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Folders.php,v 1.6 2009/10/27 14:39:27 jamie Exp $ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ + +/** + * Handles create a UL list to simulate a folder hierarchy + * + * @category CKImages + * @package Toolkit_CKImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ +class Toolkit_CKImages_Folders +{ + // {{{ properties + + + /** + * Levels deep we are into the hierarchy + * @var integer + * @access private + */ + private $_lvlsOpen = 0; + + /** + * The previous level we were at + * @var integer + * @access private + */ + private $_prevLvl = 0; + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * + * @return void + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ closeFolder() + + + /** + * Closes a folder level + * + * @return string closing ul tag + * @access protected + */ + protected function closeFolder() + { + return "\n"; + } + + // }}} + // {{{ closeNode() + + + /** + * Closes a node + * + * @return string closing li tag + * @access protected + */ + protected function closeNode() + { + return "\n\t"; + } + + // }}} + // {{{ createFolder() + + + /** + * Creates a folder level + * + * @return string opening ul tag + * @access protected + */ + protected function createFolder() + { + return "\n
    "; + } + + // }}} + // {{{ createLink() + + + /** + * Creates a folder link so we can browse to each folder + * + * @param array $row Folder information + * + * @return string anchor link for folder + * @access protected + */ + protected function createLink(array $row) + { + $format = '%s'; + + $link = sprintf( + $format, + ($_GET['folder'] == $row['id']) ? 'clicked' : null, + $_GET['CKEditor'], + $_GET['CKEditorFuncNum'], + $_GET['langCode'], + $row['id'], + $row['name'] + ); + + return $link; + } + + // }}} + + // {{{ fetchFoldersArray() + + + /** + * Fetches a tree hierarchy of the folder structure into a linear array + * + * @param integer $start node to start at + * + * @return array folder structure with levels + * @access protected + */ + protected function fetchFoldersArray($start) + { + return Toolkit_Common::getHierarchicalTreeStructure( + $this->dbh, + 'ckeditor_folders', + 'id', + 'parent', + 'id', + $start + ); + } + + // }}} + + // {{{ getFolders() + + + /** + * Gets the folders ul list + * + * @param integer $parent start at a certain level + * + * @return string list of folders + * @access public + */ + public function getFolders($parent = 0) + { + $folders = $this->fetchFoldersArray($parent); + try { + $sql = " + SELECT * + FROM ckeditor_folders + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + foreach ($folders as $i => $j) { + $stmt->bindParam(':id', $i, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($j == $this->_prevLvl) { + $tree .= $this->openNode($row); + $tree .= $this->createLink($row); + $this->_prevLvl = $j; + } elseif ($j > $this->_prevLvl) { + ++$this->_lvlsOpen; + $tree .= $this->createFolder(); + $tree .= $this->openNode($row); + $tree .= $this->createLink($row); + $this->_prevLvl = $j; + } elseif ($j < $this->_prevLvl) { + do { + $tree .= $this->closeNode(); + $tree .= $this->closeFolder(); + } while (--$this->_lvlsOpen > $j); + $tree .= $this->closeNode(); + $tree .= $this->openNode($row); + $tree .= $this->createLink($row); + $this->_prevLvl = $this->_lvlsOpen; + } + } + $tree .= $this->closeFolder(); + return $tree; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ openNode() + + + /** + * Opens a branch or leaf node + * + * @param array $row Folder information + * + * @return string opening li tag + * @access protected + */ + protected function openNode(array $row) + { + return "\n\t
  • "; + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/ImageUpdater.php b/Toolkit/CKImages/ImageUpdater.php new file mode 100644 index 0000000..b0faaa4 --- /dev/null +++ b/Toolkit/CKImages/ImageUpdater.php @@ -0,0 +1,95 @@ +_dbh = $dbh; + } + + // }}} + + // {{{ load() + + public function load($image) + { + try { + $sql = " + SELECT * + FROM ckeditor_images + WHERE name_on_disk = :image"; + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':image', $image, PDO::PARAM_STR); + $stmt->setFetchMode(PDO::FETCH_INTO, $this); + $stmt->execute(); + $this->_imageData = $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_CKImages_Exception( + "Error fetching image row for image `$image`" + ); + } + } + + // }}} + // {{{ update() + + public function update(Toolkit_FileServer_ImageAdapter $ia) + { + if ( !is_array($this->_imageData) + || empty($this->_imageData) + ) { + throw new RuntimeException( + 'You must load an image first before trying to update' + ); + } + + $targetImage = $this->_imageData['name_on_disk']; + + $path = BASE . "Toolkit/CKImages/editedImages/$targetImage"; + $newImage = $ia->uploadImageFile($path); + list($w, $h, ) = $ia->getImageSize(CKIMAGE_ORIGINAL . $newImage['name']); + + try { + $sql = " + UPDATE ckeditor_images + SET original_image = COALESCE(original_image, name_on_disk), + file_name = :image_name, + name_on_disk = :newFileName, + original_width = :newWidth, + original_height = :newHeight + WHERE name_on_disk = :originalFileName + OR original_image = :originalFileName"; + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':newFileName', $newImage['name'], PDO::PARAM_STR); + $stmt->bindParam(':image_name', $_REQUEST['image_name'], PDO::PARAM_STR); + $stmt->bindParam(':newWidth', $w, PDO::PARAM_INT); + $stmt->bindParam(':newHeight', $h, PDO::PARAM_INT); + $stmt->bindParam(':originalFileName', $targetImage, PDO::PARAM_STR); + $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_CKImages_Exception( + "Error updating image `{$this->_imageData['name_on_disk']}`" + ); + } + + // If we have updated the file previously + // then remove the old update - b/c it will now be orphaned. + if ($targetImage == $this->_imageData['original_image']) { + $ia->delete($this->_imageData['name_on_disk']); + } + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/assets/.keepme b/Toolkit/CKImages/assets/.keepme new file mode 100644 index 0000000..e69de29 diff --git a/Toolkit/CKImages/assets/night-fate-stock2.jpg b/Toolkit/CKImages/assets/night-fate-stock2.jpg new file mode 100755 index 0000000..93fc375 Binary files /dev/null and b/Toolkit/CKImages/assets/night-fate-stock2.jpg differ diff --git a/Toolkit/CKImages/browser.php b/Toolkit/CKImages/browser.php new file mode 100644 index 0000000..f266df2 --- /dev/null +++ b/Toolkit/CKImages/browser.php @@ -0,0 +1,49 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: browser.php,v 1.4 2010/06/04 10:48:50 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * bootstrap + */ +require_once '../../setup.phtml'; + +// make sure the image directories exists for editor +$imgDirs = array( + BASE . 'Toolkit/CKImages/editedImages', + BASE . 'Toolkit/PHPImageEditor/editimagesoriginal', + BASE . 'Toolkit/PHPImageEditor/editimagespng', + BASE . 'Toolkit/PHPImageEditor/editimagesworkwith', +); +$oldMask = umask(0); +foreach ($imgDirs as $dir) { + if (!is_dir($dir)) { + mkdir($dir, 0770, true); + } +} +umask($oldMask); + +Toolkit_CKImages_Factory::init(); +$connector = Toolkit_CKImages_Factory::instance('Connector'); +$connector->setDbh(Toolkit_Database::getInstance()); +$flexyOpts = $GLOBALS['flexyOptions']; +$flexyOpts['templateDir'] = BASE . 'Toolkit/CKImages/templates/'; +$flexyOpts['compileDir'] = BASE . 'Toolkit/CKImages/templates/compiled/'; +$tEngine = new HTML_Template_Flexy($flexyOpts); + +$connector->browseImages($tEngine); +?> diff --git a/Toolkit/CKImages/controller.php b/Toolkit/CKImages/controller.php new file mode 100644 index 0000000..e99537e --- /dev/null +++ b/Toolkit/CKImages/controller.php @@ -0,0 +1,53 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: controller.php,v 1.3 2010/06/04 11:32:36 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * bootstrap + */ +require_once '../../setup.phtml'; + +Toolkit_CKImages_Factory::init(); +$controller = Toolkit_CKImages_Factory::instance('Connector'); +$controller->setDbh(Toolkit_Database::getInstance()); + +switch ($_GET['command']) { +case 'CreateFolder' : + $controller->createFolder(); + break; + +case 'DeleteFile' : + $controller->deleteFile(new Toolkit_FileServer_ImageAdapter()); + break; + +case 'DeleteFolder' : + $controller->deleteFolder(); + break; + +case 'Upload' : + $controller->uploadFile(new Toolkit_FileServer_ImageAdapter()); + break; + +case 'UploadFile' : + $controller->quickUpload(new Toolkit_FileServer_ImageAdapter()); + break; + +default : + die('not yet implemented'); + $controller->throwError(); + break; +} +?> diff --git a/Toolkit/CKImages/imageFetch.php b/Toolkit/CKImages/imageFetch.php new file mode 100644 index 0000000..0c41ae8 --- /dev/null +++ b/Toolkit/CKImages/imageFetch.php @@ -0,0 +1,44 @@ +prepare($sql); + $stmt->bindParam(':id', $_GET['file'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + +// $fileToFetch = empty($row['original_image']) +// ? $row['name_on_disk'] +// : $row['original_image']; + $fileToFetch = $row['name_on_disk']; +} catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); +} +set_time_limit(0); + +// file to save the info +$fp = fopen(dirname(__FILE__) . "/editedImages/$fileToFetch", 'w+'); + +// file we are downloading +$ch = curl_init(CKIMAGE_ORIGINAL . $fileToFetch); +curl_setopt($ch, CURLOPT_TIMEOUT, 50); +curl_setopt($ch, CURLOPT_FILE, $fp); +curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); +curl_exec($ch); +curl_close($ch); +fclose($fp); + +$path = urlencode(BASE . "Toolkit/CKImages/editedImages/$fileToFetch"); +$image_name = urlencode($row['file_name']); +header('Location: ' . MEDIA_BASE_URL . "Toolkit/PHPImageEditor/index.php?imagesrc=$path&image_name=$image_name"); +?> diff --git a/Toolkit/CKImages/libjs/image_selector.js b/Toolkit/CKImages/libjs/image_selector.js new file mode 100644 index 0000000..930bce2 --- /dev/null +++ b/Toolkit/CKImages/libjs/image_selector.js @@ -0,0 +1,142 @@ +var IMAGE_SELECTOR = +{ + parentFolder: null, + + init: function() + { + $('.tLeft').tipsy({gravity: 'sw'}); + $('.tCenter').tipsy({gravity: 's'}); + $('.tRight').tipsy({gravity: 'se'}); + $('.tDelete').tipsy({gravity: 'se'}); + + $('a.CKImageEdit').click(function(event) { + var $newWindow = window.open( + $(this).attr('href'), + '', + 'width=775,height=775', + true + ); + + $newWindow.focus(); + return false; + }); + + tree1 = new tree_component(); + tree1.init($("#folders"), { + cookies : { + prefix : "glm_image_browser", + opts : { path : '/' } + }, + ui : { + animation : 500 + } + }); + + // Make the tree default to all opened + $('#folders li.closed') + .toggleClass('open') + .toggleClass('closed'); + + $('#folders a').click(IMAGE_SELECTOR.viewFolder); + + // Stop clicks on the LI elements, so the folders branches + // will not close. + $('#folders li').click(function(event) { + event.stopImmediatePropagation(); + }); + + $('div.thumb span.CKImageUse').click(function() { + var img = $(this).parent().siblings('img'); + var funcNum = $('#CKEditorFuncNum').text(); + + window.opener.CKEDITOR.tools.callFunction(funcNum, img.attr('rel')); + window.close(); + }); + + $('div.thumb span.CKImageDelete').click(function(event) { + event.preventDefault(); + if (confirm('Are you sure you want to delete this image?')) { + var img = $(this).parent().siblings('img').attr('rel'); + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=DeleteFile&img=' + img); + + window.location.href = href; + } + }); + + $('#imageDialog').dialog({ + bgiframe : true, + autoOpen : false, + resizable: false, + modal : true, + buttons : { + Cancel : function() { + $(this).dialog('close'); + }, + 'Upload Selected File' : function() { + if ($('#imageDialog form input[type=file]').val()) { + $('.ui-dialog-buttonpane button').attr('disabled', true); + $('#imageDialog form').trigger('submit'); + } else { + alert('You need to select a file first'); + } + } + } + }); + + $('#upload').click(function() { + $('#imageDialog').dialog('open'); + }); + + $('#newFolder').submit(IMAGE_SELECTOR.createFolder); + $('#folderDialog').dialog({ + bgiframe : true, + autoOpen : false, + resizable: false, + modal : true, + buttons: { + Cancel : function() { + $('#folderName').removeClass('ui-state-error'); + $(this).dialog('close'); + }, + 'Create' : IMAGE_SELECTOR.createFolder + } + }); + $('#folderNew').click(function() { + $('#folderDialog').dialog('open'); + }); + $('#folderDelete').click(function() { + if (confirm('Are you sure you want to delete this folder?')) { + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=DeleteFolder'); + + window.location.href = href; + } + }); + }, + + createFolder: function(event) + { + event.preventDefault(); + // don't submit empty folder + var folderName = $('#folderName'); + var val = folderName.val(); + if (val == '') { + alert('You need to type a folder name first'); + return false; + } else { + $('.ui-dialog-buttonpane button').attr('disabled', true); + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=CreateFolder&name=' + $('#folderName').val()); + if (IMAGE_SELECTOR.parentFolder != null) { + href += '&parentFolder=' + IMAGE_SELECTOR.parentFolder; + IMAGE_SELECTOR.parentFolder = null; + } + window.location.href = href; + } + }, + + viewFolder: function(event) + { + location.href = $(this).attr('href'); + } +}; + +$(document).ready(IMAGE_SELECTOR.init); diff --git a/Toolkit/CKImages/styles.css b/Toolkit/CKImages/styles.css new file mode 100755 index 0000000..86cab7a --- /dev/null +++ b/Toolkit/CKImages/styles.css @@ -0,0 +1,153 @@ +body { + font-family: arial, sans-serif; + font-size: 11px; + background: url(assets/night-fate-stock2.jpg) no-repeat fixed;/* #E3E3C7; */ + margin: 0; + padding: 0; +} +#wrapper { + width: 750px; + height: 1%; + overflow: hidden; + margin: 10px 0px 5px 10px; +} +h1 { + font-size: 24px; + margin: 0; + padding: 10px; + background: rgba(255, 255, 255, 0.8); + position: fixed; + } + +#toolbar { + background: #F1F1E3; + width: 140px; + border: 1px solid #D5D59D; + float: left; + padding: 8px; + margin-right: 20px; + margin-top: 60px; + position: fixed; + } +#toolbar > ul { + border-bottom: 1px solid #333; + padding: 0 0 6px 0; + margin: 0 0 6px 0; + } +#toolbar > ul, #toolbar > ul li { + list-style: none; + display: block; +} +#toolbar > ul li { + padding: 2px 2px 2px 26px; + line-height: 18px; + border: 1px solid #F1F1E3; + margin: 0; + background-position: 2px center; + background-repeat: no-repeat; + text-decoration: underline; + cursor: hand; + cursor: pointer; +} +#toolbar > ul li:hover { + border: 1px solid #D5D59D; + text-decoration: none; +} +#toolbar #upload { + background-image: url(//app.gaslightmedia.com/assets/icons/add.png); +} +#toolbar #folderNew { + background-image: url(//app.gaslightmedia.com/assets/icons/folder_add.png); +} +#toolbar #folderDelete { + background-image: url(//app.gaslightmedia.com/assets/icons/folder_delete.png); +} +.tree ul { + margin: 0; + padding-top: 1px; +} +.tree li a { + background-image: url(//app.gaslightmedia.com/assets/icons/folder.png); +} +.tree li.open { + background: none; + } +#pred_1 { + padding-left: 3px; + padding-top: 3px; +} +.tree li li.open { + background: transparent url(//app.gaslightmedia.com/libjs/jsTree/source/images/li.gif) no-repeat scroll 7px 7px; +} +/* Main Section */ +#photo-gallery { + height: 1%; + overflow: hidden; + padding-top: 10px; + margin: 50px 0 0 180px; + } +.thumb { + width: 120px; + height: 160px; + float: left; + margin: 0 20px 20px 0; + background: #F1F1E3; + background: rgba(241, 241, 227, 0.5); + font-size: 10px; + border-radius:5px; + -moz-border-radius:5px; + -webkit-border-radius:5px; + border: 1px solid #D5D59D; + } +.rowTop { + height: 1%; + overflow: hidden; +} +.thumb img { + display: block; + margin: 0px 10px 2px 10px; + border: 1px dotted #ccc; + clear: left; +} + +.CKImageFunctions { + margin: 10px 5px; + } +.CKImageFunctions a, +.CKImageFunctions span { + display: block; + line-height: 16px; + margin: 0 5px 0 5px; + text-decoration: underline; + width: 16px; + height: 16px; + text-indent: -9000px; + float: left; + } + +/* cursor */ +.CKImageUse, .CKImageEdit, .CKImageDelete { + cursor: hand; + cursor: pointer; + } + +.CKImageUse {background: url(//app.gaslightmedia.com/assets/icons/accept.png) no-repeat; } +.CKImageEdit {background: url(//app.gaslightmedia.com/assets/icons/image_edit.png) no-repeat; } +.CKImageView {background: url(//app.gaslightmedia.com/assets/icons/image.png) no-repeat;} +.CKImageDelete {background: url(//app.gaslightmedia.com/assets/icons/image_delete.png) no-repeat;} + +.CKImageName { + display: none; +} + + +.CKImageProperties { + margin: 3px auto; + text-align: center; +} +.CKImageDate { + display: none; +} +#menuFolder, #menuImage, #column { + display: none; +} diff --git a/Toolkit/CKImages/templates/thumbnails.html b/Toolkit/CKImages/templates/thumbnails.html new file mode 100755 index 0000000..d8eaa64 --- /dev/null +++ b/Toolkit/CKImages/templates/thumbnails.html @@ -0,0 +1,70 @@ + + + +Thumbnail Images + + + + + + + + +

    GLM Image Browser

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

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

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

    The system has encountered an un-recoverable error!

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

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

    '; + + $htmlMsg = "$msg"; + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom(self::$from); + $mimeMail->setSubject($subject); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $body = $mimeMail->get(); + $headers = $mimeMail->headers(); + + $mail->send(self::$admin, $headers, $body); + } + + // }}} + // {{{ multiDimArrayLocate() + + /** + * Locates an array value in a multi-dimensional array + * + * @param array $array The Array which holds the value you need. + * @param mixed $text The value that you are looking for. + * + * @return mixed The search result. + */ + public function multiDimArrayLocate($array, $text) + { + if (!is_array($array)) { + return; + } + $arrayResult = array(); + foreach ($array as $k => $v) { + if (is_array($v)) { + $temp[$k] = self::multiDimArrayLocate($v, $text); + if ($temp[$k]) { + $arrayResult[$k] = $temp[$k]; + } + } else { + if ($v == $text) { + $arrayResult[$k] = $v; + } + } + } + return $arrayResult; + } + + // }}} + + // {{{ processQuery() + //The type hint of the argument is incorrect for the type + //definition of the @param tag with argument $dbh in processQuery() + /** + * Performs the sql insert statement + * + * If using a Postgresql driver for the PDO, metadata is used when + * binding parameters to the prepared statement. + * + * @param PDO $dbh Database handler object + * @param string $tableName table used in query + * @param string $sql sql query string + * @param array $values associative array of key/value pairs that will + * be used to bind to the sql query string + * + * @return boolean result of the execute statement on the database + * @access public + * @static + */ + public static function processQuery( + PDO $dbh, + $tableName, + $sql, + array $values = null + ) { + $dbType = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); + if ($dbType == 'pgsql') { + $md = Toolkit_Common::getTableMetaData($dbh, $tableName); + } + $stmt = $dbh->prepare($sql); + foreach ($values as $k => &$v) { + if ($dbType == 'pgsql') { + $metaData = $md[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } elseif ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // as empty values '', are not considered unique + if ( empty($v) + && $dataType !== PDO::PARAM_BOOL + && $dataType !== PDO::PARAM_INT + ) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } else { + $stmt->bindParam(":$k", $v); + } + } + + return $stmt->execute(); + } + + // }}} + // {{{ prepareQuery() + + /** + * Prepares the sql statement + * + * If using a Postgresql driver for the PDO, metadata is used when + * binding parameters to the prepared statement. + * + * @param PDO &$dbh Database handler object + * @param string $tableName table used in query + * @param string $sql sql query string + * @param array $values associative array of key/value pairs that will + * be used to bind to the sql query string + * + * @return PDOStatement if successfully prepares statement + * @access public + * @static + */ + public static function prepareQuery( + PDO &$dbh, + $tableName, + $sql, + array $values = null + ) { + $dbType = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME); + if ($dbType == 'pgsql') { + $md = Toolkit_Common::getTableMetaData($dbh, $tableName); + } + $stmt = $dbh->prepare($sql); + foreach ($values as $k => &$v) { + if ($dbType == 'pgsql') { + $metaData = $md[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } elseif ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // as empty values '', are not considered unique + if ( empty($v) + && $dataType !== PDO::PARAM_BOOL + && $dataType !== PDO::PARAM_INT + ) { + $v = null; + $dataType = PDO::PARAM_NULL; + } elseif ($v === '' && $dataType === PDO::PARAM_INT) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + + $stmt->bindParam(":$k", $v, $dataType); + } else { + $stmt->bindParam(":$k", $v); + } + } + + return $stmt; + } + + // }}} + + // {{{ recursiveArraySearch() + + /** + * Recursive multi-dimensional array search + * + * @param string $n Needle + * @param array $h Haystack + * + * @return mixed search result - false if not found + * @access public + * @static + */ + public static function recursiveArraySearch($n, array $h) + { + foreach ($h as $i => $j) { + $curr = $i; + if ( $n === $j + || (is_array($j) && self::recursiveArraySearch($n, $j) !== false) + ) { + return $curr; + } + } + + return false; + } + + // }}} + + // {{{ show() + + /** + * Renders the calling class to the screen + * + * @access public + * @return string calls the toHTML function of calling class + */ + public function show() + { + echo $this->toHTML(); + } + + // }}} +} diff --git a/Toolkit/Database.php b/Toolkit/Database.php new file mode 100644 index 0000000..f6e6521 --- /dev/null +++ b/Toolkit/Database.php @@ -0,0 +1,268 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Database.php,v 1.8 2010/05/25 14:09:12 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Database Singleton class + * + * Used to create a one and only one instance of a databsae PDO object. + * Only uses the PHP PDO. Later additions may be worked on the + * use master/slave database setups. Hopefully! + * + * @category Database + * @package Database + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Database +{ + // {{{ properties + + /** + * Master database handler object + * + * Handles insert/update/delete requests + * + * @var PDO + * @access private + */ + private $_masterDbh; + + /** + * Slave database handler object + * + * Handles read requests + * + * @var PDO + * @access private + */ + private $_slaveDbh; + + /** + * Class instance + * + * @var Toolkit_Database + * @access private + */ + private static $_instance; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * Make the database handler connection for the class + * + * @param boolean $master Whether Use connection for master of slave + * + * @access private + */ + private function __construct($master) + { + try { + $dsn = 'pgsql:' . CONN_STR; + // Keep the fetch mode set to FETCH_BOTH, we use + // associative arrays throughout our apps, but some PEAR lib + // apps require numerical indicies to work correctly. + // i.e. (DataGrids working w/ PDO's) + $driverOptions = array( + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_BOTH, + ); + $this->_masterDbh = new PDO($dsn, null, null, $driverOptions); + $this->_masterDbh->setAttribute( + PDO::ATTR_ERRMODE, + PDO::ERRMODE_EXCEPTION + ); + $this->_setDateStyle($this->_masterDbh); + $this->_setSearchPath($this->_masterDbh); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ __clone() + + /** + * Clone magic method + * + * Don't allow cloning of instances of this class + * which could potentially duplicate system resources + * and make extra DB connections + * + * @return void + * @access private + */ + private function __clone() + { + // Do nothing so we don't create duplicate resources + } + + // {{{ _setDateStyle() + + /** + * Set the default date style + * @param PDO $dbh + */ + private function _setDateStyle(PDO &$dbh) + { + $dbh->query("SET DATESTYLE TO 'SQL, US'"); + } + + // }}} + // {{{ _setSearchPath() + + /** + * Set the search path for schemas + * @param PDO $dbh + */ + private function _setSearchPath(PDO &$dbh) + { + // Add schemas to search path. + $sql = " + SELECT set_config( + 'search_path', + current_setting('search_path') || ', ' || :schema, + false + )"; + + $stmt = $dbh->prepare($sql); + $stmt->bindValue(':schema', 'toolbox', PDO::PARAM_STR); + $stmt->execute(); + + $stmt->bindValue(':schema', 'ckimages', PDO::PARAM_STR); + $stmt->execute(); + + if (defined('RETAIL_SHOP') && RETAIL_SHOP) { + $stmt->bindValue(':schema', 'retail_shop', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('GLM_BLOCKS') && GLM_BLOCKS) { + // define seasonator search path + $stmt->bindValue(':schema', 'blocks', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('CONTACT_DB') && CONTACT_DB) { + // define banner search path + $stmt->bindValue(':schema', 'contacts', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('BANNERS') && BANNERS) { + // define banner search path + $stmt->bindValue(':schema', 'banners', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('ROTATING_IMAGES') && ROTATING_IMAGES) { + // define rotating images search path + $stmt->bindValue(':schema', 'rotatingImages', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) { + // define phot gallery search path + $stmt->bindValue(':schema', 'photos', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('POSTCARD_DB') && POSTCARD_DB) { + // define phot gallery search path + $stmt->bindValue(':schema', 'postcards', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('EVENT_DB') && EVENT_DB) { + // define members search path + $stmt->bindValue(':schema', 'events', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('MEMBERS_DB') && MEMBERS_DB) { + // define members search path + $stmt->bindValue(':schema', 'members', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('COUPONS') && COUPONS) { + // define coupon search path + $stmt->bindValue(':schema', 'coupons', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('PRESS_DB') && PRESS_DB) { + // define press/archive search path + $stmt->bindValue(':schema', 'press', PDO::PARAM_STR); + $stmt->execute(); + } + if (defined('EMPLOYMENT') && EMPLOYMENT) { + // define press/archive search path + $stmt->bindValue(':schema', 'employment', PDO::PARAM_STR); + $stmt->execute(); + } + if (defined('VIDEOS') && VIDEOS) { + // define videos search path + $stmt->bindValue(':schema', 'videos', PDO::PARAM_STR); + $stmt->execute(); + } + if (defined('EVENT_MANAGEMENT') && EVENT_MANAGEMENT) { + // define event management search path + $stmt->bindValue(':schema', 'reservations', PDO::PARAM_STR); + $stmt->execute(); + } + + if (defined('SEASONS') && SEASONS) { + // define seasonator search path + $stmt->bindValue(':schema', 'seasons', PDO::PARAM_STR); + $stmt->execute(); + } + } + + // }}} + + // {{{ getInstance() + + /** + * Get an instance of this class + * + * If this object hasn't been instantiated once already + * then create the object and return the dbh. + * Otherwise just return the already instantiated dbh. + * + * @param boolean $master Whether Use connection for master or slave + * + * @return PDO $_instance database handler instance + * @access public + * @static + */ + public static function getInstance($master = true) + { + settype($master, 'bool'); + + if (!(self::$_instance instanceof self)) { + self::$_instance = new self($master); + } + + return $master + ? self::$_instance->_masterDbh + : self::$_instance->_slaveDbh; + } + + // }}} +} diff --git a/Toolkit/FileServer/AdapterAbstract.php b/Toolkit/FileServer/AdapterAbstract.php new file mode 100644 index 0000000..36e214a --- /dev/null +++ b/Toolkit/FileServer/AdapterAbstract.php @@ -0,0 +1,416 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: AdapterAbstract.php,v 1.6 2010/06/04 11:33:54 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + + +/** + * Validation Secret + */ +define('IS_VALIDATE_SECRET', 'Glm0IS1secreT'); + +/** + * URL to file server, this is dynamic based on the server + * so can be setup for any sandbox + */ +define('IS_SUBMIT_URL', FILE_SERVER_URL . 'submit.phtml'); + +/** + * Adapter class for linking to the file server + * + * @category Toolkit + * @package FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +abstract class Toolkit_FileServer_AdapterAbstract +{ + // {{{ properties + + /** + * ID of owner that was setup in the file server + * + * This is defined via the file server web interface + * @var string + * @access protected + */ + protected $ownerID; + + /** + * Owners password that was setup for them + * + * This is defined via the file server web interface + * @var string + * @access protected + */ + protected $ownerPW; + + /** + * XML to send to the file server + * @var unknown + * @access protected + */ + protected $xml; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param string $owner File Server owner + * @param string $pword File Server owner password + */ + public function __construct($owner = IS_OWNER_ID, $pword = IS_OWNER_PW) + { + $this->ownerID = $owner; + $this->ownerPW = $pword; + } + + // }}} + + // {{{ buildFileServerXML() + + /** + * buildFileServerXML + * + * Create the xml for the FileServerRequest + * + * @param string $fName File name to upload or delete + * @param string $type Upload, Delete or URL + * + * @return string xml content + * @access protected + */ + protected function buildFileServerXML($fName, $type) + { + $xml = new DOMDocument('1.0'); + $xml->formatOutput = true; + + $fileServerRequest = $xml->createElement('FileServerRequest'); + $fileServerRequest->setAttribute('version', '1.0'); + + // access request + $accessRequest = $xml->createElement('AccessRequest'); + $owner = $xml->createElement('Owner'); + $ownerID = $xml->createElement('OwnerID', $this->ownerID); + $ownerPW = $xml->createElement('OwnerPW', $this->ownerPW); + + $owner->appendChild($ownerID); + $owner->appendChild($ownerPW); + + $accessRequest->appendChild($owner); + + $fileServerRequest->appendChild($accessRequest); + + $file = $this->getFileElement($xml, $type, $fName); + + $fileServerRequest->appendChild($file); + $validStr = md5($this->ownerID . $this->ownerPW . IS_VALIDATE_SECRET); + + $validation = $xml->createElement('Validation', $validStr); + $fileServerRequest->appendChild($validation); + $xml->appendChild($fileServerRequest); + + return $xml->saveXML($xml); + } + + // }}} + + // {{{ delete() + + /** + * Delete a file from the file server + * + * @param string $name File name + * + * @return string file name + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function delete($name) + { + // don't do anything if on development server + if (defined('DEVELOPMENT') && DEVELOPMENT == true) { + return true; + } + $ch = curl_init(); + + $fileData = array( + 'request' => $this->buildFileServerXML($name, 'Delete') + ); + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument; + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + return $message; + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + + // }}} + + // {{{ getFileElement() + + + /** + * Gets the file element used in the XML sent to the file server + * + * @param DOMDocument $xml DOM object used to build the xml string + * @param string $type Type of manipulation (Upload, URL, Delete) + * @param string $fName File name + * + * @return DOMElement $file File xml element + * @access protected + */ + abstract protected function getFileElement( + DOMDocument $xml, + $type, + $fName + ); + + // }}} + // {{{ getErrorMessage() + + /** + * Gets an appropriate error message for file upload errors + * + * @param integer Error code + * + * @return string Error message + * @access protected + */ + protected function getErrorMessage($code) + { + switch ($code) { + case UPLOAD_ERR_INI_SIZE : + $message = 'The Uploaded file exceeds the upload max filesize directive in php.ini'; + break; + + case UPLOAD_ERR_FORM_SIZE : + $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; + break; + + case UPLOAD_ERR_PARTIAL : + $message = 'The uploaded file was only partially uploaded'; + break; + + case UPLOAD_ERR_NO_FILE : + $message = 'No file was uploaded'; + break; + + case UPLOAD_ERR_NO_TMP_DIR : + $message = 'Missing a temporary folder'; + break; + + case UPLOAD_ERR_CANT_WRITE : + $message = 'Failed to write file to disk'; + break; + + case UPLOAD_ERR_EXTENSION : + $message = 'A PHP extension stopped the file upload'; + break; + + default : + $message = 'Unknown error uploading file'; + break; + } + + return $message; + } + + // }}} + + // {{{ upload() + + /** + * Upload a file to the File Server + * + * @param string $name $_FILES index key that holds the file data + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function upload($name) + { + $fileType = null; + if (preg_match('/^http/', $name)) { + $fileType = 'URL'; + } elseif (isset($_FILES[$name]) && is_array($_FILES[$name])) { + $fileType = 'Upload'; + } + + if ($_FILES[$name]['error'] != 0) { + $message = $this->getErrorMessage($_FILES[$name]['error']); + throw new Toolkit_FileServer_Exception( + $message, + $_FILES[$name]['error'] + ); + } + + if (is_null($fileType)) { + return false; + } else { + $request = $this->buildFileServerXML($name, $fileType); + $ch = curl_init(); + if ($fileType == 'URL') { + $fileData = array( + 'request' => $request + ); + } else { + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $fileData = array( + 'request' => $request, + 'file_upload' => new CurlFile( + $_FILES[$name]['tmp_name'], + $_FILES[$name]['type'], + $_FILES[$name]['name']), + 'file_upload_name' => $_FILES[$name]['name'] + ); + } else { + $fileData = array( + 'request' => $request, + 'file_upload' => "@{$_FILES[$name]['tmp_name']}", + 'file_upload_name' => $_FILES[$name]['name'] + ); + } + } + + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POST => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument(); + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $storedName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $storedSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $mediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + $extension = end(explode('.', $storedName)); + return array( + 'name' => $storedName, + 'size' => $storedSize, + 'type' => $mediaType, + 'extension' => $extension, + ); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + } + + // }}} + + // {{{ xmlPathContent() + + /** + * Extract a XML node value + * + * @param DOMDocument $dom DOM object holding the XML + * @param string $content Node name to extract content from + * + * @return mixed Node value on success, false if can't find the value + * @access protected + */ + protected function xmlPathContent(DOMDocument $dom, $content) + { + $xPath = new DOMXPath($dom); + $nodeList = $xPath->query($content); + if ($nodeList->length > 0) { + $node = $nodeList->item(0); + return $node->nodeValue; + } + + return false; + } + + // }}} +} diff --git a/Toolkit/FileServer/Exception.php b/Toolkit/FileServer/Exception.php new file mode 100644 index 0000000..8739c0f --- /dev/null +++ b/Toolkit/FileServer/Exception.php @@ -0,0 +1,5 @@ + diff --git a/Toolkit/FileServer/FileAdapter.php b/Toolkit/FileServer/FileAdapter.php new file mode 100644 index 0000000..d59601d --- /dev/null +++ b/Toolkit/FileServer/FileAdapter.php @@ -0,0 +1,101 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: FileAdapter.php,v 1.4 2010/05/25 14:02:28 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * File Adapter + * + * Used for linking to the file server for file uploading, storage and deletion + * + * @category Toolkit + * @package FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_FileServer_FileAdapter extends Toolkit_FileServer_AdapterAbstract +{ + // {{{ getFileElement() + + /** + * Creates the file element for the XML string + * + * @param DOMDocument $xml XML object used to build the string + * @param string $type Type of action to take on the file (Upload, Delete) + * @param string $fName file name to delete + * + * @return DOMElement $file File xml element + * @access protected + * @throws RuntimeException + */ + protected function getFileElement(DOMDocument $xml, $type, $fName) + { + $file = $xml->createElement('File'); + + switch ($type) { + case 'Upload' : + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'Submit'); + $fieldName = $xml->createElement('FieldName', 'file_upload'); + + $fileName = filter_var($_FILES[$fName]['name'], FILTER_SANITIZE_STRING); + $nameParts = explode('.', $fileName); + $extension = end($nameParts); + $fieldName = $xml->createElement('Extension', end($nameParts)); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($fieldName); + break; + + case 'URL': + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'URL'); + $src = $xml->createElement('Src', $fName); + + $nameParts = explode('.', $fName); + $extension = end($nameParts); + $fieldName = $xml->createElement('Extension', end($nameParts)); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($src); + $file->appendChild($fieldName); + break; + + case 'Delete' : + $action = $xml->createElement('FileAction', 'Delete'); + $file->appendChild($action); + + $fileName = $xml->createElement('FileName', $fName); + $file->appendChild($fileName); + break; + + default : + throw new RuntimeException("Invalid XML type - `$type`."); + break; + } + + return $file; + } + + // }}} +} diff --git a/Toolkit/FileServer/ImageAdapter.php b/Toolkit/FileServer/ImageAdapter.php new file mode 100644 index 0000000..6db761e --- /dev/null +++ b/Toolkit/FileServer/ImageAdapter.php @@ -0,0 +1,259 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: ImageAdapter.php,v 1.5 2010/06/04 11:34:31 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Image Adapter + * + * Used for linking to the file server for image uploading, storage and deletion + * + * @category Toolkit + * @package FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_FileServer_ImageAdapter extends Toolkit_FileServer_AdapterAbstract +{ + // {{{ getAllowedMimeTypes() + + /** + * Get the mime types that are allowed to be uploaded + * + * @return array allowed mime types + */ + public function getAllowedMimeTypes() + { + return array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/gif', + 'image/png', + ); + } + + // }}} + // {{{ getFileElement() + + /** + * Creates the file element for the XML string + * + * @param DOMDocument $xml XML object used to build the string + * @param string $type Type of action to take on the file (Upload, Delete) + * @param string $fName file name to delete + * + * @return DOMElement $file File xml element + * @access protected + * @throws RuntimeException + */ + protected function getFileElement(DOMDocument $xml, $type, $fName) + { + $file = $xml->createElement('File'); + + switch ($type) { + case 'Upload' : + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'Submit'); + $fieldName = $xml->createElement('FieldName', 'file_upload'); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($fieldName); + break; + + case 'URL': + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'URL'); + $src = $xml->createElement('Src', $fName); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($src); + break; + + case 'Delete': + $action = $xml->createElement('FileAction', 'Delete'); + $file->appendChild($action); + + $fileName = $xml->createElement('FileName', $fName); + $file->appendChild($fileName); + break; + + default : + throw new RuntimeException("Invalid XML type - `$type`."); + break; + } + + return $file; + } + + // }}} + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws Exception + */ + public function getImageSize($image) + { + $options = array('allowed_schemes' => array('http','https')); + if (!Validate::uri($image, $options)) { + throw new Exception('Invalid URI for the image'); + } + + $ch = curl_init(); + $curlOptions = array( + CURLOPT_URL => "{$image}/info", + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + if (!@simplexml_load_string($response)) { + $logger = Toolkit_Logger::getLogger(); + $logger->warning("$response - $image"); + } + + $wPattern = '/(.*)<\/width>/'; + preg_match($wPattern, $response, $matches); + $width = $matches[1]; + $hPattern = '/(.*)<\/height>/'; + preg_match($hPattern, $response, $matches); + $height = $matches[1]; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + // {{{ uploadImageFile() + + /** + * Upload a file to the File Server + * + * @param string $fname full path to image file + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function uploadImageFile($fname) + { + if (!file_exists($fname)) { + throw new RuntimeException("could not find file `$fname`"); + } + + $request = $this->buildFileServerXML(basename($fname), 'Upload'); + + $ch = curl_init(); + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $fileData = array( + 'request' => $request, + 'file_upload' => new CurlFile( + $_FILES[$fname]['tmp_name'], + $_FILES[$fname]['type'], + $_FILES[$fname]['name']), + 'file_upload_name' => basename($fname) + ); + } else { + $fileData = array( + 'request' => $request, + 'file_upload' => "@$fname", + 'file_upload_name' => basename($fname) + ); + } + + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument(); + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $storedName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $storedSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $mediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + return array( + 'name' => $storedName, + 'size' => $storedSize, + 'type' => $mediaType, + ); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + + // }}} +} +?> diff --git a/Toolkit/FileServer/Mock/ImageAdapter.php b/Toolkit/FileServer/Mock/ImageAdapter.php new file mode 100644 index 0000000..ed9307d --- /dev/null +++ b/Toolkit/FileServer/Mock/ImageAdapter.php @@ -0,0 +1,125 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: ImageAdapter.php,v 1.1 2010/07/29 16:30:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Mock Image Adapter + * + * Mocks uploading and deleting images from the image server + * This script prevents unneeded resources from being uploaded + * or deleted from the file server + * + * @category FileServer + * @package Toolkit_FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_FileServer_Mock_ImageAdapter + extends Toolkit_FileServer_ImageAdapter +{ + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws Exception + */ + public function getImageSize($image) + { + $width = $height = 1; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + // {{{ uploadImageFile() + + /** + * Upload a file to the File Server + * + * @param string $fname full path to image file + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function uploadImageFile($fname) + { + return array( + 'name' => 'is00-mock-image.jpg', + 'size' => 100, + 'type' => 'image/jpeg', + ); + } + + // }}} + // {{{ upload() + + /** + * Upload a file to the File Server + * + * @param string $name $_FILES index key that holds the file data + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function upload($name) + { + return array( + 'name' => 'is00-mock-image.jpg', + 'size' => 100, + 'type' => 'image/jpeg', + ); + } + + // }}} + // {{{ delete() + + /** + * Delete a file from the file server + * + * @param string $name File name + * + * @return string file name + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function delete($name) + { + return true; + } + + // }}} +} +?> diff --git a/Toolkit/Form.php b/Toolkit/Form.php new file mode 100644 index 0000000..ab3d79e --- /dev/null +++ b/Toolkit/Form.php @@ -0,0 +1,143 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Form.php,v 1.6 2009/08/31 17:43:48 jamie Exp $ + * @link http://demo.gaslightmedia.com/ + */ + +/** + * Minimum form object method definitions + * + * Each form must at least define some elements and setup the rules for + * that form. They must also create a method which handless extracting + * the form object into an html string suitable to be displayed onto a + * page. + * + * @category Toolkit + * @package Form + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com/ + */ +interface Toolkit_Form +{ + // {{{ configureElements() + + /** + * Defines all elements to be used in a form + * + * Creates an array of elements and passes them off to the setupElements + * function wich adds each element to the form object. + * + * + * public function configureElements() + * { + * $e = array(); + * + * $e[] = array( + * 'type' => 'text', + * 'req' => false + * 'name' => 'text_field', + * 'display' => 'Text Label', + * ); + * $e[] = array( + * 'type' => 'checkbox', + * 'req' => false + * 'name' => 'checkbox_field', + * 'display' => 'Checkbox Label', + * ); + * + * // ... More Element Definitions + * + * $this->setupElements($e); + * } + * + * + * @access public + * @return void + */ + //public function configureElements(); + + // }}} + // {{{ configureForm() + + /** + * Calls all the configuration methods to configure a form for use + * + * @access public + * @return void + */ + //public function configureForm(); + + // }}} + // {{{ configureRules() + + /** + * Defines all element rules to be used for validation in the form + * + * At the bare minimum, this function needs to be called to setup the + * form rules, even if no extra rules are defined. Because it still + * creates all the required rules that are defined w/ each element. + * + * + * public function configureRules() + * { + * $r = array(); + * + * $r[] = array( + * 'element' => 'text_field', + * 'message' => 'ERROR: 10 characters max!', + * 'type' => 'maxlength', + * 'format' => 10, + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false, + * ); + * $r[] = array( + * 'element' => 'text_field', + * 'message' => 'ERROR: Numric characters only!', + * 'type' => 'numeric', + * 'format' => null, + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false, + * ); + * + * // ... More Rule Definitions + * + * $this->setupRules($r); + * } + * + * + * @access public + * @return void + */ + public function configureRules(); + + // }}} + // {{{ toHtml() + + /** + * Get an html string that contains the form + * + * Check if the form needs to be validated (ie. it was submitted) + * Check if submitted data needs to be processed + * + * @access public + * @return string an html string that contains the entire form + */ + public function toHtml(); + + // }}} +} diff --git a/Toolkit/FormBuilder.php b/Toolkit/FormBuilder.php new file mode 100644 index 0000000..4eb5592 --- /dev/null +++ b/Toolkit/FormBuilder.php @@ -0,0 +1,1264 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: FormBuilder.php,v 1.48 2010/08/05 14:19:47 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Allow the inclusion of the Element Grid plugin for QuickForms + */ +require_once 'HTML/QuickForm/ElementGrid.php'; + +/** + * Handle QuickForm CAPTCHA's + */ +require_once 'HTML/QuickForm/CAPTCHA/Image.php'; + +/** + * Require PEAR QuickForm class + */ +require_once 'HTML/QuickForm.php'; + +require_once 'HTML/QuickForm/Rule/Zip.php'; +require_once 'HTML/QuickForm/Rule/Phone.php'; +require_once 'HTML/QuickForm/Rule/Banwords.php'; +require_once 'HTML/QuickForm/Rule/State.php'; + +/** + * Base functionality for creating HTML_Quickforms + * + * @category Toolkit + * @package FormBuilder + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +abstract class Toolkit_FormBuilder extends HTML_QuickForm +{ + // {{{ properties + + /** + * Holds if the form has been validated + * + * once the form is validated, store the result of the validation + * in this variable. That way, if multiple validations are attempted + * we don't have to reprocess all the data + * + * @var boolean + * @access protected + */ + protected $validated = false; + + /** + * Global form captcha question element + * + * @var object + * @access protected + */ + protected $captchaQuestion; + + /** + * Global form captcha answer from user + * + * @var object + * @access protected + */ + protected $captchaAnswer; + + /** + * Form submitted data used when emailing form results + * + * @var array + * @access protected + */ + protected $formData = array(); + + /** + * Automatically create validation rules for any date elements + * + * This will only work if the date element is in m-d-Y format + * + * @var boolean + * @access protected + */ + protected $autoValidateDateElements = true; + + /** + * How do we want to validate the form + * + * Possible options are [server, client] + * + * @var string + * @access protected + */ + protected $validationType = 'server'; + + /** + * Some special forms dont utlize this stylesheet + * Allow classes to override this setting so it doesn't + * get included + * + * @var boolean + * @access protected + */ + protected $includeContactStyleSheet = true; + + /** + * What do you want the error msg to be if the form doesn't validate + * + * @var string + * @access protected + */ + protected $errorMsg + = '
    + Warning: The form was not sent, please review the errors below. +
    '; + + /** + * What do you want the success msg to be if the form validates successfully + * + * @var string + * @access protected + */ + protected $successMsg + = '
    + The information below has been successfully submitted. +
    '; + + /** + * Whether uploaded files should be processed too (if present) + * + * @var string + * @access protected + */ + protected $mergeFiles = true; + + /** + * Include a captcha on the form or not + * + * @var boolean + * @access protected + */ + protected $useCaptcha; + + /** + * The default templates to inject into the form renderer + * + * @var string + * @access protected + */ + protected $template; + + /** + * The default rules to register for validating + * + * We have to register these rules, or any others we want, before + * we are able to use them in our forms. + * + * These rules can be removed in subclasses before the rules are configured + * if you want to omit any of them from validating input - just remember + * to not call them in your configured rules! + * + * Phone: validates input against US and CA style phone #'s + * + * $rules[] = array('element' => 'phone', + * 'message' => 'ERROR: Invalid Phone Format!', + * 'type' => 'phone', + * 'format' => null, + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * Zip: Validates input against US and CA zip codes, if DB check is + * set to true, validate zip codes against all the zip codes in the + * DB. + * + * $rules[] = array('element' => 'zip', + * 'message' => 'ERROR: Invalid Zip!', + * 'type' => 'zip', + * 'format' => array('requireDBCheck' => true), + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * Banwords: Make sure each each doesn't contain a banned word. Checking + * against a DB of banned words. + * + * State: Validate input against US and CA region / province codes. If DB + * check is set to true, validate region / province against all the + * regions / provinces in the DB. + * + * $rules[] = array('element' => 'state_id', + * 'message' => 'ERROR: Invalid State / Province!', + * 'type' => 'state', + * 'format' => array('requireDBCheck' => true), + * 'validation' => $this->validationType, + * 'reset' => true, + * 'force' => false); + * + * + * @var array + * @access protected + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Zip.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Phone.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Banwords.php + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/State.php + */ + protected $registeredRules = array('phone', 'zip', 'state'); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for
    tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + * @todo Remove assigning the dbh the global dbh and setup a PDO + * to be passed in from a parameter - this will allow for easier + * PHPUnit testing + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + // T_VARIABLE error when passing this server + // var in on the constructors params. + $action = empty($action) ? $_SERVER['REQUEST_URI'] : $action; + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->template = BASE . 'Toolkit/Forms/templates/tables/'; + $this->dbh = Toolkit_Database::getInstance(); + + if ($this->includeContactStyleSheet) { + $baseURL = MEDIA_BASE_URL; + $GLOBALS['styleSheets'][] = $baseURL . 'css/contactform.css'; + } + } + + // }}} + + // {{{ addCharLimit() + + /** + * adds a maxlength character limitation to an element + * + * @param string $element The name of the element to add + * the char limit to + * @param integer $limit The number of characters allowed + * + * @return void + * @access public + */ + public function addCharLimit($element, $limit) + { + $this->addRule( + $element, + "ERROR: $limit characters max!", + 'maxlength', + $limit, + 'server' + ); + // Add a maxlength attribute to the field on the form + // which will help prevent users from sending over 100 chars + // to the server in the first place. + if ($this->getElementType($element) == 'text') { + $e =& $this->getElement($element); + $e->setMaxLength($limit); + } + } + + // }}} + // {{{ apiVersion() + + /** + * Returns the current FormBuilder API version + * + * @since 1.10 + * @access public + * @return float + */ + public function version() + { + return 1.1; + } + + // }}} + + // {{{ checkDateInput() + + /** + * Checks the validation of a m-d-Y date + * + * This function will only be called if the autoValidateDateElements + * property is set to true. + * + * @param array $value Date element from form. + * + * @return boolean + * @access public + * @see Toolkit_FormBuilder->autoValidateDateElements + */ + public function checkDateInput($value) + { + if ( empty($value['m']) + || empty($value['d']) + || empty($value['Y']) + ) { + return false; + } + return checkdate($value['m'], $value['d'], $value['Y']); + } + + // }}} + // {{{ cleanElements() + + /** + * Removes elements from form + * + * Loops through elements and if any names end in '_rmv' they are removed + * from the form object. + * + * Dynamically finds all elements on a form and removes any that + * end in '_rmv'. This can be really usefull if you want to display + * from results after the form was successfully submitted and validated, + * but don't need to display any extra form elements initially displayed + * on the form (like email confirmation fields, or static instruction + * elements). + * + * @param array $elements Form elements. + * + * @return void + * @access protected + */ + protected function cleanElements($elements) + { + if (is_array($elements)) { + foreach ($elements as $e) { + if ($e['type'] == 'group') { + $this->cleanGroup($e['name']); + } elseif (preg_match('/^.+_rmv$/', $e['name'])) { + $this->removeElement($e['name']); + } + } + } + } + + // }}} + // {{{ cleanForm() + + /** + * Removes elements from form + * + * Dynamically finds all elements on a form and removes any that + * end in '_rmv'. This can be really usefull if you want to display + * from results after the form was successfully submitted and validated, + * but don't need to display any extra form elements initially displayed + * on the form (like email confirmation fields, or static instruction + * elements). + * + * @return void + * @access protected + */ + protected function cleanForm() + { + $formArray = $this->toArray(); + if (array_key_exists('sections', $formArray)) { + foreach ($formArray['sections'] as $k) { + if (preg_match('/^.+_rmv$/', $k['name'])) { + $this->removeElement($k['name']); + } + $this->cleanElements($k['elements']); + } + } else { + $this->cleanElements($formArray['elements']); + } + } + + // }}} + // {{{ cleanGroup() + + /** + * Removes any elements from a group that have names that end in '_rmv' + * + * @param string $name The name of the group element + * + * @return void + * @access protected + */ + protected function cleanGroup($name) + { + $e =& $this->getElement($name); + $g =& $e->getElements(); + $i = 0; + while ($name = $e->getElementName($i++)) { + if (preg_match('/^.+_rmv/', $name)) { + unset($g[($i - 1)]); + } + } + } + + // }}} + // {{{ createGridElement() + + /** + * Creates a grid element for the form + * + * Written so this can be overridden easily in subclasses later if needed! + * + * @param string $elementType QuickForm ElementGrid element definition + * + * @return mixed ElementGrid element. + * @access protected + */ + protected function &createGridElement($elementType) + { + $args = func_get_args(); + return call_user_func_array(array($this, 'createElement'), $args); + + } + + // }}} + + // {{{ getErrorMessage() + + public function getErrorMessage() + { + return $this->errorMsg; + } + + // }}} + // {{{ prepElement() + + /** + * Make sure all the element array indexes are set + * + * @param array &$e Element to prep + * + * @return void + * @access protected + */ + protected function prepElement(&$e) + { + if (!isset($e['opts'])) { + $e['opts'] = ''; + } + if (!isset($e['att'])) { + $e['att'] = ''; + } + if (!isset($e['val'])) { + $e['val'] = ''; + } + if (!isset($e['display'])) { + $e['display'] = ''; + } + if (!isset($e['label'])) { + $e['label'] = ''; + } + if (!isset($e['noCharLimit'])) { + $e['noCharLimit'] = false; + } + } + + // }}} + + // {{{ registerRules() + + /** + * Registers custom form rules you can use when validating + * + * If the registeredRule token is an array, any QF rule can be + * registered. This is useful if you want to register rules + * from outside classes + * e.g. (Validate, Validate_US, Validate_CA, etc...). + * + * This will set up a rule called 'checkEmail' which uses the + * Validate::email() function. + * you can still pass in parameters to this rule if you pass them in + * via the 'format' option when you are defining your rules. + * + * class exampleClass + * { + * $registeredRules = array( + * array( + * 'checkEmail', + * 'callback', + * 'email', + * 'Validate' + * ) + * ); + * + * // ... Rest of your class code + * + * public function configureRules() + * { + * $r = array(); + * + * $r[] = array( + * 'element' => 'process_email', + * 'message' => 'ERROR: Invalid email format!', + * 'type' => 'checkEmail', + * 'format' => array('use_rfc822' => true), + * 'validation' => $this->validationType, + * 'reset' => false, + * 'force' => false + * ); + * + * $this->setupRules($r); + * } + * + * // ... Rest of your class code + * } + * + * + * If the registeredRule is a string, the corresponding rule in the + * glmPEAR/HTML/QuickForm/Rule/ directory will be registered with + * the form. + * + * This will set up the 'phone' rule already defined in the + * glmPEAR/HTML/QuickForm/Rule directory which validates both + * US and Canadian phone numbers + * + * class exampleClass + * { + * $registeredRules = array('phone'); + * + * // ... Rest of your class code + * + * public function configureRules() + * { + * $r = array(); + * + * $r[] = array( + * 'element' => 'phone', + * 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + * 'type' => 'phone', + * 'format' => null, + * 'validation' => $this->validationType, + * 'reset' => false, + * 'force' => false + * ); + * + * $this->setupRules($r); + * } + * + * // ... Rest of your class code + * } + * + * + * @return void + * @access protected + */ + protected function registerRules() + { + if (is_array($this->registeredRules)) { + foreach ($this->registeredRules as $r) { + if (is_array($r)) { + call_user_func_array(array(&$this, 'registerRule'), $r); + } else { + // Don't nedd to register rules more than once + if (!$this->isRuleRegistered($r)) { + $this->registerRule($r, null, "HTML_QuickForm_Rule_$r"); + } + } + } + } + } + + // }}} + + // {{{ setAutoValidateDateElements() + + /** + * Set if we need to auto validate the Date Elements + * + * @param boolean $validate true/false to auto validate date elements + * + * @return void + * @access public + */ + public function setAutoValidateDateElements($validate) + { + $this->autoValidateDateElements = $validate; + } + + // }}} + // {{{ setFormData() + + /** + * Sets the submitted values from the form + * + * Set these values into an internal variable so they will be accessible + * anywhere we need them in the form. + * + * @param array $exclude (optional) Any element names you don't want + * included. Since this is primarily used in + * emailing, this is helpful to exclude any data + * we don't want before the array is generated. + * + * @return void + * @access protected + */ + protected function setFormData(array $exclude = array()) + { + $values = $this->getSubmitValues(); + foreach ($values as $k => $v) { + if ($this->elementExists($k)) { + $e =& $this->getElement($k); + if (!in_array($e->getName(), $exclude)) { + switch ($e->getType()) { + case 'date' : + list($m, $d, $y) = array_values($e->getValue()); + // If all the date fields are empty, then don't add + // the output to the formData. + if (!(empty($m[0]) && empty($d[0]) && empty($y[0]))) { + $this->formData[$e->getName()]['label'] + = $e->getLabel(); + + $oldDate = $e->getValue(); + $newDate = Toolkit_Common::arrayFlatten( + $oldDate, + 0, + $newDate + ); + + $this->formData[$e->getName()]['element'] + = implode(' / ', $newDate); + unset($oldDate, $newDate); + } + break; + + case 'group': + $e->freeze(); + $this->formData[$e->getName()]['label'] = $e->getLabel(); + $this->formData[$e->getName()]['element'] = $e->toHtml(); + break; + + case 'select' : + $this->formData[$e->getName()]['label'] = $e->getLabel(); + + $values = $e->getValue(); + foreach ($values as $v) { + $this->formData[$e->getName()]['element'] .= $v; + } + break; + + default : + $this->formData[$e->getName()]['label'] = $e->getLabel(); + $this->formData[$e->getName()]['element'] = $e->getValue(); + break; + } + } + } + } + } + + // }}} + // {{{ setupConstants() + + /** + * Sets the form constant values + * + * @param array $constants Associative array of form constant values. + * + * @return void + * @access protected + */ + protected function setupConstants($constants) + { + $this->setConstants($constants); + } + + // }}} + // {{{ setupDefaults() + + /** + * Sets the form default values + * + * @param array $defaults Associative array of form default values. + * + * @return void + * @access protected + */ + protected function setupDefaults($defaults) + { + $this->setDefaults($defaults); + } + + // }}} + // {{{ setupElements() + + /** + * Sets up all the elements to the form + * + * Takes a multi-dimensional array of form elements and uses them + * to set up the form objects elements + * + * @param array $elements Multi-Dimensional array of form elements. + * + * @return void + * @access protected + */ + protected function setupElements($elements) + { + if (!is_array($elements)) { + return; + } + foreach ($elements as &$e) { + $this->prepElement($e); + switch ($e['type']) { + case 'group' : + if (is_array($e['group']) && !empty($e['group'])) { + // Special rendering for grouped elements. + unset($field); + foreach ($e['group'] as $g) { + $this->prepElement($g); + $field[] =& HTML_QuickForm::createElement( + $g['type'], + $g['name'], + $g['display'], + $g['opts'], + $g['att'], + $g['val'] + ); + } + $source =& $this->addGroup( + $field, + $e['name'], + $e['label'], + $e['seperator'], + $e['appendName'] + ); + } + break; + + case 'elementGrid' : + $source =& $this->addElement( + $e['type'], + $e['name'], + $e['display'], + $e['opts'], + $e['att'], + $e['val'] + ); + unset($columnNames); + + // Loop through the rows (r) and columns (c) + // to add each of the elements to our grid. + foreach ($e['group'] as $k => $r) { + unset($set, $rowTitle); + foreach ($r as $c) { + $columnNames[$c['display']] = $c['display']; + + $set[] =& $this->createGridElement( + $c['type'], + $c['name'], + null, + $c['opts'], + $c['att'] + ); + } + $rowTitle = is_int($k) ? ' ' : $k; + $source->addRow($set, $rowTitle); + } + + $source->setColumnNames($columnNames); + break; + + default : + // Render all elements except groups + try { + $source =& $this->addElement( + $e['type'], + $e['name'], + $e['display'], + $e['opts'], + $e['att'], + $e['val'] + ); + + if (PEAR::isError($source)) { + var_dump($source); + throw new Exception ('PEAR QuickForm Element Error'); + } + } catch (HTML_QuickForm_Error $e) { + Toolkit_Common::dieGracefully(null, $e); + } catch (Exception $e) { + Toolkit_Common::handleError($e); + } + + if ($e['type'] == 'advmultiselect') { + $source->setLabel($e['labels']); + } + if ($e['name'] == 'categories') { + $res = $source->loadArray($this->categories); + if (PEAR::isError($res)) { + Toolkit_Common::dieGracefully(null, $res); + } + } + if ($e['type'] == 'header') { + $this->formHeaders[$e['display']] = $e; + } + + if ($e['name'] == 'captcha_rmv') { + $this->captchaAnswer =& $source; + } + + if ($e['name'] == 'captcha_question') { + $this->captchaQuestion =& $source; + } + break; + } + } + $this->formElements = $elements; + } + + // }}} + // {{{ setupFilters() + + /** + * Sets any filters needed for the form elements when submitting + * + * @param array $filters Element filters. + * + * @return void + * @access protected + */ + protected function setupFilters($filters) + { + foreach ($filters as $f) { + $res = $this->applyFilter($f['element'], $f['filter']); + + if (PEAR::isError($res)) { + Toolkit_Common::handleError($res); + } + } + } + + // }}} + // {{{ setupRules() + + /** + * Apply rules to the form + * + * 100 & 1000 char length limitations are automatically assigned to + * text/textarea elements to help reduce load limitations on the server. + * -request per Chuck in a conference call on (5/22/2009 @ 12:15pm) + * + * Applies rules that are defined in child classes to the form elements + * group rules can be kind of tricky, since you can't apply a rule + * directly to an element inside of a rule you have to define + * the rule inside a nest of array's and then add a group rule. + * the array will contain all the elements inside the group you wish + * to apply rules to. + * + * You can assign as many rules as you would like to individual elements, + * and you aren't required to make the array associative, although it is + * easier to see whats going on. + * + * see: http://pear.activeventure.com/package/package.html.html-quickform.html-quickform.addgrouprule.html + * for another example. + * + * // Define the rules for each element in the group. + * $num_rule = array( + * 'ERROR: Must contain a valid decimal number!', + * 'numeric' + * ); + * // Collect together the rules for each element. + * $lat_rules = array('lat' => array($num_rule)); + * $lon_rules = array('lon' => array($num_rule)); + * $r[] = array( + * 'element' => 'latitude', + * 'message' => 'ERROR:', + * 'type' => 'group', + * 'format' => $lat_rules, + * 'validation' => $this->validationType, + * 'reset' => false, + * 'force' => false + * ); + * + * + * To make a group required but not require every element in the group + * you can use the addGroupRule function again + * for example: say you have a group of checkboxes and you only only + * require 1 be checked. a simple group rule such as the following + * will handle this. + * N.B. notice the extra "howMany" index. + * + * $r[] = array( + * 'element' => 'element_name', + * 'message' => 'ERROR: Error to display!', + * 'type' => 'required', + * 'format' => null, + * 'howMany' => 1, + * 'validation'=> $this->validationType, + * 'reset' => true, + * 'force' => false, + * ); + * + * + * @param array $rules Multi-Dimensional array of rules for form elements. + * + * @return void + * @access protected + */ + protected function setupRules(array $rules = null) + { + $this->registerRules(); + $preRegisteredRules = $this->getRegisteredRules(); + if (is_array($this->formElements)) { + foreach ($this->formElements as $e) { + // Put length limitations on text and textarea fields + if ($e['type'] == 'text' && !$e['noCharLimit']) { + $this->addCharLimit($e['name'], 100); + } elseif ($e['type'] == 'textarea' && !$e['noCharLimit']) { + $this->addCharLimit($e['name'], 1000); + } elseif ($e['type'] == 'group') { + // We need to apply these same limitations to the + // text and textarea fields inside of groups + $r = array(); + if (is_array($e['group'])) { + foreach ($e['group'] as $i) { + // Loop through group elements and if they are + // text/textarea fields then put the field into + // a rule array that we will assign to the group + if ($i['type'] == 'text' && !$i['noCharLimit']) { + $r[$i['name']][] = array( + 'ERROR: 100 characters max!', + 'maxlength' + ); + } elseif ($i['type'] == 'textarea' && !$i['noCharLimit']) { + $r[$i['name']][] = array( + 'ERROR: 1000 characters max!', + 'maxlength' + ); + } + } + } + if (!empty($r)) { + $this->addGroupRule($e['name'], $r); + } + } + if ($this->validationType == 'client') { + $label = $e['display']; + } + if ($e['req']) { + if ($e['type'] == 'group') { + foreach ($e['group'] as $ge) { + if ($ge['req']) { + $rule[$ge['name']][] = array( + 'ERROR: You must complete this field!', + 'required', + null, + $this->validationType); + } + } + $this->addGroupRule($e['name'], $rule); + unset($rule); + } elseif ($e['type'] == 'date') { + if (!empty($e['error'])) { + // Custom error message for the date element. + $error = $e['error']; + } else { + // Default error message for the date element. + $error = 'ERROR: You must enter a date!'; + } + $this->addGroupRule( + $e['name'], + $error, + 'required', + 3, + $this->validationType + ); + if ($this->autoValidateDateElements) { + $this->addRule( + $e['name'], + 'ERROR: Date is invalid!', + 'callback', + array(&$this, 'checkDateInput') + ); + } + } else { + $this->addRule( + $e['name'], + "$label ERROR: You must complete this field!", + 'required', + null, + $this->validationType + ); + } + } + } + } + if (is_array($rules)) { + foreach ($rules as $r) { + if (!is_array($r['element'])) { + $group = ($this->getElementType($r['element']) == 'group'); + } + if ($group) { + $this->addGroupRule( + $r['element'], + $r['message'], + $r['type'], + $r['format'], + $r['howMany'], + $r['validation'], + $r['reset'] + ); + } elseif (in_array($r['type'], $preRegisteredRules)) { + $this->addRule( + $r['element'], + $r['message'], + $r['type'], + $r['format'], + $r['validation'], + $r['reset'], + $r['force'] + ); + } + } + } + } + + // }}} + // {{{ setupRenderers() + + /** + * Sets up renderers for form objects + * + * Uses the default form renderer to allow templates to be injected + * into the form object before displaying on a page. This allows + * changing the face of the form w/ out any backend adjustment. + * + * Files that can be created for templates are + * + * Examples: + * # Element.tpl + * + * + * + * + * * + * + * + * + * + * + *
    {error}
    + * + * {element} + * + * + *
    + * + * # Form.tpl + * + *
    + * + * + * {content} + *
    + * + *
    + *
    + * + * # GroupElement.tpl + * + * + * + * {element} + * + * * + * + * {label} + * + * + * + * + * # Group.tpl + * + * + * + * {content} + * + *
    + *
    + * + * # Header.tpl + * + * + * + * {header} + * + * + * + * + * # RequiredNote.tpl + * + * * Denotes required field + * + * + * @param array $groups any groups that need to be rendered + * via the groupElementTemplate and groupTemplate + * + * @return void + * @access protected + */ + protected function setupRenderers(array $groups = array()) + { + $renderer =& $this->defaultRenderer(); + if (is_dir($this->template)) { + if ($dh = opendir($this->template)) { + while (($file = readdir($dh)) !== false) { + // Ignore current dir and parent dir. + if ($file != '..' && $file != '.' && $file != 'CVS') { + $baseName = reset(explode('.', $file)); + // Ignores swp files. + if (!empty($baseName)) { + $method = "set{$baseName}Template"; + $template = file_get_contents($this->template . $file); + if ( $method != 'setGroupTemplate' + && $method != 'setGroupElementTemplate' + ) { + if (method_exists($renderer, $method)) { + $renderer->$method($template); + } + } else { + // apply the templates to any defined groups + foreach ($groups as $k) { + $renderer->$method($template, $k); + } + } + } + } + } + closedir($dh); + } + } + + // Set the default how the captcha's should look + // can be overridden in subclasses + if ($this->useCaptcha) { + $required = '*'; + $error = '
    {error}
    '; + $renderer->setElementTemplate( + ' + + {element} + ', + 'captcha_question' + ); + $renderer->setElementTemplate( + ' + '.$required.' + '.$error.'{element} + What is this? + + ', + 'captcha_rmv' + ); + } + } + + // }}} + // {{{ useCaptcha() + + /** + * Set if we need to use a captcha in this form or not + * + * @param boolean $useCaptcha true/false to use a captcha with the form + * + * @return void + * @access public + */ + public function useCaptcha($useCaptcha) + { + $this->useClueTip(); + $this->useCaptcha = $useCaptcha; + } + + // }}} + // {{{ useClueTip() + + /** + * Set if we need to use the JS cluetip + * + * @param boolean $useCaptcha include cluetip resources or not + * + * @return void + * @access public + */ + public function useClueTip() + { + $GLOBALS['styleSheets'][] + = MEDIA_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.css'; + $GLOBALS['bottomScripts'][] + = MEDIA_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.js'; + $GLOBALS['bottomScripts'][] + = MEDIA_APP_BASE_URL . 'libjs/cluetip/lib/jquery.hoverIntent.js'; + $GLOBALS['bottomScripts'][] + = MEDIA_APP_BASE_URL . 'libjs/cluetip/lib/jquery.bgiframe.min.js'; + $GLOBALS['bottomScripts'][] + = MEDIA_APP_BASE_URL . 'libjs/contactform.js'; + } + + // }}} + // {{{ show() + + /** + * Shows the form + * + * @return void + * @access public + */ + public function show() + { + Toolkit_Common::show(); + } + + // }}} + // {{{ validate() + + public function validate() + { + if (!$this->validated) { + $this->validated = parent::validate(); + } + + return $this->validated; + } + + // }}} +} diff --git a/Toolkit/Forms/Rules/Date.php b/Toolkit/Forms/Rules/Date.php new file mode 100644 index 0000000..e5a53c8 --- /dev/null +++ b/Toolkit/Forms/Rules/Date.php @@ -0,0 +1,93 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_Date + * + * Description of Toolkit_Forms_Rules_Date + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_Date extends HTML_QuickForm_Rule +{ + /** + * Validate if a string is a valid date + * + * If element is part of a group, then you can pass in the group name + * under the options parameter, that way you can find the date values + * + * You must pass in at least the format of the date in an array. + * array('format' => '%m-%d-%Y') is the default + * + * @param string $value the date array to validate + * @param array $options options used to dictate validation of the date + * + * @return bool if the string could correctly be validated as a date. + * @access public + * @see Validate::date() + */ + function validate($value, array $options) + { + $month = !isset($options['group']) + ? $value['m'] + : $value[$options['group']]['m']; + $day = !isset($options['group']) + ? $value['d'] + : $value[$options['group']]['d']; + $year = !isset($options['group']) + ? $value['Y'] + : $value[$options['group']]['Y']; + + if (isset($options['allowEmpty']) + && $options['allowEmpty'] + && empty($month) + && empty($day) + && empty($year) + ) { + return true; + } + + unset($options['group'], $options['allowEmpty']); + + $day = str_pad($day, 2, '0', STR_PAD_LEFT); + $month = str_pad($month, 2, '0', STR_PAD_LEFT); + + return Validate::date("$month-$day-$year", $options); + } + + /** + * gets validation script + * + * @return array + */ + function getValidationScript() + { + return array('', true); + } +} + +HTML_QuickForm::registerRule( + 'Date', + 'rule', + 'Toolkit_Forms_Rules_Date', + BASE . 'Toolkit/Forms/Rules/Date.php' +); +?> diff --git a/Toolkit/Forms/Rules/Image.php b/Toolkit/Forms/Rules/Image.php new file mode 100644 index 0000000..86eec64 --- /dev/null +++ b/Toolkit/Forms/Rules/Image.php @@ -0,0 +1,209 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_Image + * + * Description of Toolkit_Forms_Rules_Image + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_Image extends HTML_QuickForm_Rule +{ + // {{{ validate() + + /** + * Handle image uploading rules + * + * The options array is required and has specific key values + * that must be present. + * + * form : (HTML_Quickform) form object - so we can insert + * the new image name back back into the forms + * submit values. + * fieldName : (string) name of the upload field - this is + * generally the same name as the field we're + * calling the rule on. + * imageField : (string) name of the field that stores the + * filename of the image that was uploaded + * is : (Toolkit_FileServer_ImageAdapter) + * image server instance + * deleteExistingImage : (boolean) Whether to delete any old image from + * the image server before uploading the new image + * injectImage : (array) + * tgtElement : (string) Name of the field that will hold the preview + * of the image - This is usually a static element + * path : (optional) Path to the image - defaults to FORM_THUMB + * imgTag : (optional) Format of the image tag - defaults to + * where %s is the path + image + * + * + * Full Example: + * + * $r[] = array( + * 'element' => 'file_rmv', + * 'message' => 'ERROR: Error uploading image!', + * 'type' => 'Image', + * 'format' => array( + * 'form' => $this, + * 'fieldName' => 'file_rmv', + * 'imageField' => 'image', + * 'is' => new Toolkit_FileServer_ImageAdapter(), + * 'deleteExistingImage' => true, + * 'injectImage' => array( + * 'tgtElement' => 'current_image_rmv', + * 'imgTag' => '', + * 'path' => FORM_THUMB + * ) + * ), + * 'validation' => $this->validationType, + * 'reset' => false, + * 'force' => false + * ); + * + * @param string $value the $_FILES['xxxx'] array + * @param array $options upload options + * + * @return bool if the image was successfully uploaded or not + * @access public + */ + function validate($value, array $options) + { + // No image uploaded - return true + // this can be a valid state, if the field is required - then a + // required rule should be used and will catch before this rule + // is even applied. + if (empty($value['tmp_name'])) { + return true; + } + + if (!isset($options['fieldName'])) { + throw new RuntimeException( + 'Missing `fieldName` key in options' + ); + } + if ( isset($options['is']) + && ($options['is'] instanceof Toolkit_FileServer_ImageAdapter) + ) { + $is = $options['is']; + } else { + throw new RuntimeException( + 'Missing `is` key in options for Image Server instance' + ); + } + + if ( isset($options['form']) + && ($options['form'] instanceof HTML_QuickForm) + ) { + $form =& $options['form']; + } else { + throw new RuntimeException( + 'Missing `form` key in options' + ); + } + + if (isset($options['imageField'])) { + $imageField = $options['imageField']; + } else { + throw new RuntimeException( + 'Missing `imageField` key in options' + ); + } + + if ( isset($options['injectImage']) + && !is_array($options['injectImage']) + ) { + if (!is_array($options['injectImage'])) { + throw new RuntimeException( + '`injectImage` must be an array of options' + ); + } + } elseif ( isset($options['injectImage']) + && is_array($options['injectImage']) + && !isset($options['injectImage']['tgtElement']) + ) { + throw new RuntimeException( + 'The `injectImage` array needs a `tgtElement` index to inject the new image into' + ); + } + + if ( isset($options['deleteExistingImage']) + && $options['deleteExistingImage'] + ) { + $existingImage =& $form->getSubmitValue($imageField); + if (!empty($existingImage)) { + $is->delete($existingImage); + } + } + + try { + $uploadedImage = $is->upload($options['fieldName']); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + return false; + } + + if (isset($options['injectImage'])) { + $imgTag = isset($options['injectImage']['imgTag']) + ? $options['injectImage']['imgTag'] + : ''; + + $path = isset($options['injectImage']['path']) + ? $options['injectImage']['path'] + : FORM_THUMB; + + $htmlImg = sprintf($imgTag, $path . $uploadedImage['name']); + $tgt = $options['injectImage']['tgtElement']; + $currImg =& $form->getElement($tgt); + $currImg->setValue($htmlImg); + } + + $fileName =& $form->getElement($imageField); + $fileName->setValue($uploadedImage['name']); + $form->_submitValues[$imageField] = $uploadedImage['name']; + + return true; + } + + // }}} + + // {{{ getValidationScript() + + /** + * gets validation script + * + * @return array + */ + function getValidationScript() + { + return array('', true); + } + + // }}} +} + +HTML_QuickForm::registerRule( + 'Image', + 'rule', + 'Toolkit_Forms_Rules_Image', + BASE . 'Toolkit/Forms/Rules/Image.php' +); +?> diff --git a/Toolkit/Forms/Rules/ShortUrl.php b/Toolkit/Forms/Rules/ShortUrl.php new file mode 100644 index 0000000..823f14c --- /dev/null +++ b/Toolkit/Forms/Rules/ShortUrl.php @@ -0,0 +1,81 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_ShortUrl + * + * Description of Toolkit_Forms_Rules_ShortUrl + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_ShortUrl extends HTML_QuickForm_Rule +{ + // {{{ validate() + + /** + * Validate if a string is a valid short url + * + * Short URLs can only contain alpha numeric characters plus + * dash and underscore. They must also not be the same name as a file + * on the server. + * + * @param string $value short url to validate + * + * @return bool if the string could correctly be validated as a short url + * @access public + */ + public function validate($value) + { + $hasValidCharacters = !preg_match('/[^-a-zA-Z0-9_]/', $value); + // Short URLs that are the same as an existing file ie: (index.php) + // cause .htaccess to throw errors + $fileDoesNotExist = !file_exists(BASE . $value); + // Short URLs that are the same as an existing file basename + // ie: (index) cause .htaccess to throw errors + list($path, $suffix) = explode('.', $value); + $files = array_filter(glob(BASE . "$path*"), 'is_file'); + $baseNameDoesNotExist = ($files !== false && empty($files)); + return $hasValidCharacters && $fileDoesNotExist && $baseNameDoesNotExist; + } + + // }}} + // {{{ getValidationScript() + + /** + * gets validation script + * + * @return array + */ + public function getValidationScript() + { + return array('', true); + } + + // }}} +} + +HTML_QuickForm::registerRule( + 'ShortUrl', + 'rule', + 'Toolkit_Forms_Rules_ShortUrl', + BASE . 'Toolkit/Forms/Rules/ShortUrl.php' +); +?> diff --git a/Toolkit/Forms/Rules/Url.php b/Toolkit/Forms/Rules/Url.php new file mode 100644 index 0000000..4216c24 --- /dev/null +++ b/Toolkit/Forms/Rules/Url.php @@ -0,0 +1,80 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_Forms_Rules_Url + * + * Description of Toolkit_Forms_Rules_Url + * + * @category Toolkit + * @package Forms/Rules + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Forms_Rules_Url extends HTML_QuickForm_Rule +{ + // {{{ validate() + + /** + * Validate if a string is a valid url + * + * @param string $value url to validate + * @param array $options set to null + * + * @return bool if the string could correctly be validated as a url + * @access public + */ + public function validate($value, array $options = null) + { + $validateFilter = FILTER_VALIDATE_URL; + + if (is_null($options)) { + return (bool) filter_var($value, $validateFilter); + } + + $lambdaFunction = create_function('$a, $b', 'return $a | $b;'); + $flags = array_reduce($options, $lambdaFunction, 0); + + return (bool) filter_var($value, $validateFilter, $flags); + + } + + // }}} + // {{{ getValidationScript() + + /** + * gets validation script + * + * @return array + */ + public function getValidationScript() + { + return array('', true); + } + + // }}} +} + +HTML_QuickForm::registerRule( + 'Url', + 'rule', + 'Toolkit_Forms_Rules_Url', + BASE . 'Toolkit/Forms/Rules/Url.php' +); +?> diff --git a/Toolkit/Forms/templates/tables/Element.tpl b/Toolkit/Forms/templates/tables/Element.tpl new file mode 100644 index 0000000..595457b --- /dev/null +++ b/Toolkit/Forms/templates/tables/Element.tpl @@ -0,0 +1,14 @@ + + + + * + + + + + +
    {error}
    + + {element} + + diff --git a/Toolkit/Forms/templates/tables/Form.tpl b/Toolkit/Forms/templates/tables/Form.tpl new file mode 100644 index 0000000..8ed6c2f --- /dev/null +++ b/Toolkit/Forms/templates/tables/Form.tpl @@ -0,0 +1,11 @@ +
    + +
    + {hidden} +
    + {requiredNote} + + {content} +
    + +
    \ No newline at end of file diff --git a/Toolkit/Forms/templates/tables/Group.tpl b/Toolkit/Forms/templates/tables/Group.tpl new file mode 100644 index 0000000..cdd24cf --- /dev/null +++ b/Toolkit/Forms/templates/tables/Group.tpl @@ -0,0 +1,5 @@ + + + {content} + +
    diff --git a/Toolkit/Forms/templates/tables/GroupElement.tpl b/Toolkit/Forms/templates/tables/GroupElement.tpl new file mode 100644 index 0000000..1a4ba27 --- /dev/null +++ b/Toolkit/Forms/templates/tables/GroupElement.tpl @@ -0,0 +1,9 @@ + + + {element} + + * + + {label} + + diff --git a/Toolkit/Forms/templates/tables/Header.tpl b/Toolkit/Forms/templates/tables/Header.tpl new file mode 100644 index 0000000..64ac244 --- /dev/null +++ b/Toolkit/Forms/templates/tables/Header.tpl @@ -0,0 +1,5 @@ + + + {header} + + diff --git a/Toolkit/Forms/templates/tables/RequiredNote.tpl b/Toolkit/Forms/templates/tables/RequiredNote.tpl new file mode 100644 index 0000000..8d61480 --- /dev/null +++ b/Toolkit/Forms/templates/tables/RequiredNote.tpl @@ -0,0 +1 @@ +
    * Denotes required field
    diff --git a/Toolkit/IController.php b/Toolkit/IController.php new file mode 100644 index 0000000..534e21b --- /dev/null +++ b/Toolkit/IController.php @@ -0,0 +1,36 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ + +/** + * Toolkit_IController + * + * Object Mapper pattern class for the Video PDO Table. Creates + * Toolkit_Video_Video objects by values or by id + * + * @category Toolkit + * @package Controller + * @author Steve Sutton + * @copyright 2012 Gaslight media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +interface Toolkit_IController +{ + /** + * default action for the controller + * + * @return string + */ + public function indexAction(); +} diff --git a/Toolkit/IMapper.php b/Toolkit/IMapper.php new file mode 100644 index 0000000..aa440b2 --- /dev/null +++ b/Toolkit/IMapper.php @@ -0,0 +1,36 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Toolkit_IMapper + * + * Interface for creation of mapper classes + * + * @category Toolkit + * @package Mapper + * @author Steve Sutton + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +interface Toolkit_IMapper +{ + /** + * createByValues + * + * @param Array $values array of values to set for the new object + * + * @return object + */ + public function createByValues($values); +} +?> diff --git a/Toolkit/INavigation.php b/Toolkit/INavigation.php new file mode 100644 index 0000000..0c85d77 --- /dev/null +++ b/Toolkit/INavigation.php @@ -0,0 +1,52 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +/** + * Toolkit_INavigation + * + * Interface + * + * @category Toolkit + * @package Toolkit_INavigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +interface Toolkit_INavigation +{ + /** + * Class constructor + * + * @param HTML_Menu $menu Menu + * @param HTML_Menu_Renderer $rEngine Menu Renderer + */ + public function __construct( + HTML_Menu $menu, + HTML_Menu_Renderer $rEngine + ); + + /** + * Render page navigation + * + * @param array $navigation Navigation + * @param unknown $type Type + * + * @return void + */ + public function renderPageNav(array $navigation, $type); +} +?> diff --git a/Toolkit/ITable.php b/Toolkit/ITable.php new file mode 100644 index 0000000..fb777b8 --- /dev/null +++ b/Toolkit/ITable.php @@ -0,0 +1,57 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Interface for Table objects + * + * @category Toolkit + * @package Table + * @author Steve Sutton + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +interface Toolkit_ITable +{ + /** + * setId + * + * @param Int $id Table primary key + * + * @return Object + */ + public function setId($id); + /** + * save + * + * @param PDO $dbh Database Connection + * + * @return void + */ + public function save(PDO $dbh); + /** + * insert + * + * @param PDO $dbh Database Connection + * + * @return Object + */ + public function insert(PDO $dbh); + /** + * update + * + * @param PDO $dbh Database Connection + * + * @return Object + */ + public function update(PDO $dbh); +} diff --git a/Toolkit/Image/Converter.php b/Toolkit/Image/Converter.php new file mode 100644 index 0000000..8b4b859 --- /dev/null +++ b/Toolkit/Image/Converter.php @@ -0,0 +1,262 @@ + + * @copyright 2010 Steve Sutton + * @license Gaslight Media + * @version CVS: $Id: Converter.php,v 1.2 2010/07/29 14:56:50 matrix Exp $ + * @link http://pear.php.net/package/Toolkit_Image + * @see References to other sections (if any)... + */ + +/** + * Toolkit_Image_Converter + * + * Long description (if any) ... + * + * @category Toolkit + * @package Image + * @author Steve Sutton + * @copyright 2010 Steve Sutton + * @license Gaslight Media + * @version Release: @package_version@ + * @link http://pear.php.net/package/Toolkit_Image + * @see References to other sections (if any)... + */ +class Toolkit_Image_Converter extends Toolkit_FormBuilder +{ + + /** + * Description for $is + * @var object + * @access protected + */ + protected $is; + + /** + * Description for $dbh + * @var object + * @access protected + */ + protected $dbh; + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param PDO $pdo Databse Handler + * @param Toolkit_Image_Server $is Parameter description (if any) ... + * @param string $formName Parameter description (if any) ... + * @param string $method Parameter description (if any) ... + * @param string $action Parameter description (if any) ... + * @param string $target Parameter description (if any) ... + * @param unknown $attributes Parameter description (if any) ... + * @param boolean $trackSubmit Parameter description (if any) ... + * + * @return void + * @access public + */ + function __construct( + PDO $pdo, + Toolkit_Image_Server $is, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + $this->dbh = $pdo; + $this->is = $is; + $action = empty($action) ? $_SERVER['REQUEST_URI'] : $action; + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function configureForm() + { + $this->setupElements(); + $this->setupRules(); + $this->setupDefaults(); + $this->setupConstants(); + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return void + * @access public + */ + function processData($values) + { + echo '
    '.print_r($values, true).'
    '; + $sql = " + UPDATE {$values['table_name']} + SET {$values['img_field_name']} = :new_img + WHERE {$values['primary_key']} = :id"; + $updateImg = $this->dbh->prepare($sql); + try { + $sql = " + SELECT * + FROM {$values['table_name']} + WHERE {$values['img_field_name']} != '' + AND {$values['img_field_name']} IS NOT NULL + AND {$values['img_field_name']} != 'ERROR' + AND {$values['img_field_name']} !~ '^is' + AND {$values['img_field_name']} !~ '^fs' + "; + $stmt = $this->dbh->prepare($sql); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + if ($row[$values['primary_key']]) { + echo '
    '
    +                        . print_r(
    +                            $values['original_url']
    +                            . '/' . $row[$values['img_field_name']],
    +                            true
    +                        ) . '
    '; + $newImage = $this->is->imageUpload($values['original_url']. '/' . $row[$values['img_field_name']]); + $updateImg->bindParam(":new_img", $newImage, PDO::PARAM_STR); + $updateImg->bindParam(":id", $row[$values['primary_key']], PDO::PARAM_STR); + $updateImg->execute(); + } + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupElements() + { + $e[] = array( + 'type' => 'header', + 'name' => 'header_rmv', + 'display' => 'Converter' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'original_url', + 'display' => 'Original Path URL without ending /' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'table_name', + 'display' => 'Table Name' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'img_field_name', + 'display' => 'Image Field Name' + ); + $e[] = array( + 'type' => 'text', + 'name' => 'primary_key', + 'display' => 'Primary Key' + ); + $e[] = array( + 'type' => 'submit', + 'name' => 'submit', + 'display' => 'Submit' + ); + parent::setupElements($e); + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupConstants() + { + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupDefaults() + { + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + function setupRules() + { + } + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + function toHtml() + { + if ($this->validate()) { + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + //$output = $this->successMsg; + //$output .= parent::toHTML(); + } + } else if ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + $output = parent::toHtml(); + } + return $output; + } +} +?> diff --git a/Toolkit/Image/Server.php b/Toolkit/Image/Server.php new file mode 100755 index 0000000..c56daca --- /dev/null +++ b/Toolkit/Image/Server.php @@ -0,0 +1,385 @@ + + * @copyright 2008 Steve Sutton + * @license Gaslight Media + * @version CVS: $Id: Server.php,v 1.19 2010/05/25 14:02:45 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Description for define + */ +define('IS_VALIDATE_SECRET', 'Glm0IS1secreT'); + +/** + * Description for define + */ +define('IS_SUBMIT_URL', FILE_SERVER_URL . 'submit.phtml'); + +/** + * Toolkit_Image_Server + * + * Class for implementation of the image server process Chuck has + * setup for is0.gaslightmedia.com + * Uses Curl PHP Library to upload images to the server + * + * @category Toolkit + * @package Image + * @author Steve Sutton + * @copyright 2008 Steve Sutton + * @license Gaslight Media + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Image_Server +{ + // {{{ properties + + /** + * OwnerID for the Image Server User + * @var string + * @access protected + */ + protected $OwnerID; + + /** + * Owner Password + * @var string + * @access protected + */ + protected $OwnerPW; + + /** + * DOMDocument Object + * @var unknown + * @access protected + */ + protected $xml; + + // }}} + + // {{{ __construct() + + /** + * __construct + * + * @return void + * @access public + */ + function __construct() + { + $this->OwnerID = IS_OWNER_ID; + $this->OwnerPW = IS_OWNER_PW; + } + + // }}} + + // {{{ buildImageServerXML() + + /** + * buildImageServerXML + * + * Create the xml for the FileServerRequest + * + * @param string $fileName File to upload or delete + * @param unknown $type Upload or Delete + * + * @return string xml content + * @access public + */ + function buildImageServerXML($fileName, $type) + { + $xml = new DOMDocument('1.0'); + $xml->formatOutput = true; + $FileServerRequest = $xml->createElement('FileServerRequest'); + $FileServerRequest->setAttribute('version', '1.0'); + // AccessRequest part + $AccessRequest = $xml->createElement('AccessRequest'); + $Owner = $xml->createElement('Owner'); + $OwnerID = $xml->createElement('OwnerID', $this->OwnerID); + $OwnerPW = $xml->createElement('OwnerPW', $this->OwnerPW); + $Owner->appendChild($OwnerID); + $Owner->appendChild($OwnerPW); + $AccessRequest->appendChild($Owner); + $FileServerRequest->appendChild($AccessRequest); + // file part + $File = $xml->createElement('File'); + switch ($type) { + case "Upload": + $FileAction = $xml->createElement('FileAction', 'Submit'); + $DeliveryMethod = $xml->createElement('DeliveryMethod', 'Submit'); + $FieldName = $xml->createElement('FieldName', 'file_upload'); + $File->appendChild($FileAction); + $File->appendChild($DeliveryMethod); + $File->appendChild($FieldName); + $FileServerRequest->appendChild($File); + $size = filesize($_FILES[$fileName]['tmp_name']); + $validStr = md5($this->OwnerID.$this->OwnerPW.IS_VALIDATE_SECRET); + break; + case "URL": + $FileAction = $xml->createElement('FileAction', 'Submit'); + $DeliveryMethod = $xml->createElement('DeliveryMethod', 'URL'); + $Src = $xml->createElement('Src', $fileName); + $File->appendChild($FileAction); + $File->appendChild($DeliveryMethod); + $File->appendChild($Src); + $FileServerRequest->appendChild($File); + $size = strlen($fileName); + $validStr = md5($this->OwnerID.$this->OwnerPW.IS_VALIDATE_SECRET); + break; + case "Delete": + $FileAction = $xml->createElement('FileAction', 'Delete'); + $File->appendChild($FileAction); + $FileName = $xml->createElement('FileName', $fileName); + $File->appendChild($FileName); + $FileServerRequest->appendChild($File); + $validStr = md5($this->OwnerID.$this->OwnerPW.IS_VALIDATE_SECRET); + break; + } + // validation part + $Validation = $xml->createElement('Validation', $validStr); + $FileServerRequest->appendChild($Validation); + $xml->appendChild($FileServerRequest); + return $xml->saveXML($xml); + } + + // }}} + + // {{{ imageDelete() + + /** + * imageDelete + * + * Delete an image from the image server + * + * @param unknown $name Image name + * + * @return unknown image name + * @access public + */ + function imageDelete($name) + { + // don't do anything if on development server + if (defined('DEVELOPMENT') && DEVELOPMENT == true) { + return "File deleted. File: " . $name; + } + if ($name) { + $request = $this->buildImageServerXML($name, 'Delete'); + $ch = curl_init(); + $fileData = array( + 'request' => $request + ); + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $xmlDoc = new DOMDocument; + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $SuccessCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $Message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $Owner = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/Owner' + ); + $StoredName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $StoredSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $MediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + return $Message; + } + } + + // }}} + // {{{ imageUpload() + + /** + * imageUpload + * + * Upload image to server + * + * @param string $name Form field name of image + * + * @return string Image name + * @access public + */ + function imageUpload($name) + { + $fileType = null; + if (preg_match("/^http/", $name)) { + $fileType = 'URL'; + } elseif (is_array($_FILES[$name])) { + $fileType = 'Upload'; + } + if ($fileType) { + $request = $this->buildImageServerXML($name, $fileType); + $ch = curl_init(); + if ($fileType == "URL") { + $fileData = array( + 'request' => $request + ); + } else { + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $fileData = array( + 'request' => $request, + 'file_upload' => new CurlFile( + $_FILES[$name]['tmp_name'], + $_FILES[$name]['type'], + $_FILES[$name]['name'] + ), + 'file_upload_name' => $_FILES[$name]['name'] + ); + } else { + $fileData = array( + 'request' => $request, + 'file_upload' => '@'.$_FILES[$name]['tmp_name'], + 'file_upload_name' => $_FILES[$name]['name'] + ); + } + } + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $xmlDoc = new DOMDocument; + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $SuccessCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $Message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $Owner = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/Owner' + ); + $StoredName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $StoredSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $MediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + if ($SuccessCode != 0) { + //throw new Exception('Image Server Error said:'.$response); + throw new PEAR_Exception('Image Server Error said:'.$response); + exit; + } + return $StoredName; + } + } + + // }}} + + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws PEAR Error + */ + function getImageSize($image) + { + $options = array('allowed_schemes' => array('http','https')); + if (!Validate::uri($image, $options)) { + throw new PEAR_Exception('Invalid URI for the image'); + exit; + } + + $ch = curl_init(); + $curlOptions = array( + CURLOPT_URL => "{$image}/info", + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, +// CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $wPattern = "/(.*)<\/width>/"; + preg_match($wPattern, $response, $matches); + $width = $matches[1]; + $hPattern = "/(.*)<\/height>/"; + preg_match($hPattern, $response, $matches); + $height = $matches[1]; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + + // {{{ xmlPathContent() + + /** + * xmlPathContent + * + * Grab the content given XPath Query + * + * @param unknown $dom DOMDocument nodelist + * @param unknown $content query for XPath + * + * @return object string of node + * @access public + */ + function xmlPathContent($dom, $content) + { + $xPath = new DOMXPath($dom); + $nodelist = $xPath->query($content); + foreach ($nodelist as $entry) { + return $entry->nodeValue; + } + } + + // }}} +} diff --git a/Toolkit/Logger.php b/Toolkit/Logger.php new file mode 100644 index 0000000..17993c2 --- /dev/null +++ b/Toolkit/Logger.php @@ -0,0 +1,168 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Logger.php,v 1.6 2010/05/25 14:09:12 jamie Exp $ + * @link <> + * @see Log + */ + +/** + * Logging class used to handle system logs + */ +require_once 'Log.php'; + +/** + * Error handling logger for system + * + * @category Logger + * @package Toolkit_Logger + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see Log + */ +class Toolkit_Logger +{ + // {{{ &getLogger() + + /** + * Gets a concrete log subclass based on constant parameters set for server + * + * Define parameters in server setup block of bootstrap file + * + * @return Log concrete Log subclass + * @access public + * @static + */ + public static function &getLogger() + { + if (defined('ERROR_LOG_NAME') && constant('ERROR_LOG_NAME') != '') { + $errorLogName = constant('ERROR_LOG_NAME'); + } else { + $errorLogName = ''; + } + + $logger =& Log::singleton( + ERROR_LOG_TYPE, + $errorLogName, + constant('ERROR_LOG_IDENT'), + $GLOBALS['ERROR_LOG_CONF'], + constant('ERROR_LOG_LEVEL') + ); + + return $logger; + } + + // }}} + // {{{ errorHandler() + + /** + * User-defined error handler function + * + * handles errors in script. E_ERROR, E_WARNING, E_NOTICE are automatically + * logged when they occur. Fatal errors (E_ERROR) have a 404 page shown to + * user so script doesn't halt. + * + * @param int $errno Level of the error rasied + * @param string $errstr Error message + * @param string $errfile Filename that the error was raised in + * @param int $errline Line number the error was raised at + * @param Log $logger Logger to user for error loggin + * + * @return boolean false, allows the normal error handler to continue + * @access public + * @static + */ + public static function errorHandler( + $errno, + $errstr, + $errfile, + $errline, + $logger = null + ) { + if (!($logger instanceof Log)) { + $logger =& self::getLogger(); + } + + $msg = "$errstr in $errfile at line $errline"; + switch ($errno) { + case E_ERROR : + case E_USER_ERROR : + $logger->emerg($msg, PEAR_LOG_EMERG); + header("HTTP/1.0 404 Not Found"); + exit(1); + break; + + case E_WARNING : + CASE E_USER_WARNING : + $logger->warning($msg, PEAR_LOG_WARNING); + break; + + case E_NOTICE : + case E_USER_NOTICE : + $logger->notice($msg, PEAR_LOG_NOTICE); + break; + + default : + $logger->info($msg, PEAR_LOG_INFO); + break; + } + + return false; // let the normal error handler continue + } + + // }}} + // {{{ logException() + + /** + * Create a log for an exception + * + * @param string $type Type of error encountered that caused exception + * @param Exception $e Exception that was thrown + * + * @return void + * @static + */ + public static function logException($type, Exception $e) + { + $msg = $e->getMessage(); + $file = $e->getFile(); + $line = $e->getLine(); + + $lcType = strtolower($type); // uniformity in type when looking at log + $log = "[$lcType] $msg in $file at line $line"; + + $logger =& self::getLogger(); + + switch ($lcType) { + case 'db error' : + case 'invalid arg' : + case 'runtime error' : + $logger->emerg($log); + break; + + case 'image server' : + case 'file server' : + $logger->warning($log); + break; + + default : + $logger->err($log); + break; + } + } + + // }}} +} +?> diff --git a/Toolkit/NavigationAbstract.php b/Toolkit/NavigationAbstract.php new file mode 100644 index 0000000..524243a --- /dev/null +++ b/Toolkit/NavigationAbstract.php @@ -0,0 +1,89 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_NavigationAbstract + * + * Description of NavigationAbstract + * + * @category Toolkit + * @package None + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_NavigationAbstract +{ + // {{{ properties + + /** + * Default nav index + * @param integer + * @access protected + */ + protected $currIndex; + + /** + * page menu + * @param HTML_Menu + * @access protected + */ + protected $menu; + + /** + * menu rendering engine + * @param HTML_Menu_DirectRenderer + * @access protected + */ + protected $rEngine; + + // }}} + // {{{ renderPageNav() + + /** + * Render the page navigation that is defined in the navStructure + * + * @param array $navStructure Page navigation structure + * @param string $type Type of menu to render + * + * @return string Page navigation structure + * @access public + */ + public function renderPageNav(array $navStructure, $type) + { + $this->menu->setMenu($navStructure); + $this->menu->setMenuType($type); + + $this->setCurrentIndex(); + $this->setNavTemplates(); + + $this->menu->render($this->rEngine); + return $this->rEngine->toHtml(); + } + + // }}} + // {{{ setNavTemplates() + /** + * set nav templates + * + * @return void + */ + abstract protected function setNavTemplates(); + + // }}} +} +?> diff --git a/Toolkit/NavigationFactoryAbstract.php b/Toolkit/NavigationFactoryAbstract.php new file mode 100644 index 0000000..9288e31 --- /dev/null +++ b/Toolkit/NavigationFactoryAbstract.php @@ -0,0 +1,48 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +/** + * Toolkit_BaseControllerAbstract + * + * Generate a sitemap for the site + * need to remove members only pages and other pages you + * don't want viewed by public + * + * @category Toolkit + * @package Toolkit_NavigationFactoryAbstract + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +abstract class Toolkit_NavigationFactoryAbstract +{ + /** + * create side nav + * + * @return void + */ + abstract public function createSideNav(); + + /** + * create side nav + * + * @return void + */ + abstract public function createMainNav(); +} +?> diff --git a/Toolkit/PHPImageEditor/classes/phpimageeditor.php b/Toolkit/PHPImageEditor/classes/phpimageeditor.php new file mode 100644 index 0000000..e29361d --- /dev/null +++ b/Toolkit/PHPImageEditor/classes/phpimageeditor.php @@ -0,0 +1,843 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + + + /* + Copyright 2008, 2009, 2010 Patrik Hultgren + + YOUR PROJECT MUST ALSO BE OPEN SOURCE IN ORDER TO USE PHP IMAGE EDITOR. + OR ELSE YOU NEED TO BUY THE COMMERCIAL VERSION AT: + http://www.shareit.com/product.html?productid=300296445&backlink=http%3A%2F%2Fwww.phpimageeditor.se%2F + + This file is part of PHP Image Editor. + + PHP Image Editor is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + PHP Image Editor is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with PHP Image Editor. If not, see . + */ + + + //Requires + //PHP: 4.3 + //GD: 2.0.28 + + /*PHP FUNCTIONS REQUIRES THESE VERSIONS + getimagesize PHP 4 + image_type_to_mime_type PHP 4.3 + imagecopyresized PHP 4 + file_exists PHP 4 + copy PHP 4 + imagecreatetruecolor PHP 4.0.6, GD 2.0.1 + imagecopyresized PHP 4 + imagecopy PHP 4 + imagecreatefromjpeg PHP 4, GD 1.8 + imagecreatefromgif PHP 4, GD 2.0.28 + imagecreatefrompng PHP 4 + imagefilter PHP 5, GD + imagejpeg PHP 4, GD-1.8 + imagepng PHP 4 + imagegif PHP 4 + imagerotate PHP 4.3 GD + imagesx PHP 4 + imagesy PHP 4 + */ + + + /** + * Description of PHPImageEditor + * + * @category Toolkit + * @package PHPImageEditor/Classes + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class PHPImageEditor +{ + public $srcEdit = ""; + public $srcOriginal = ""; + public $srcPng = ""; + public $srcWorkWith = ""; + public $resourceWorkWith = false; + public $mimeType = ""; + public $actionSaveAndClose = "save"; + public $actionRotateLeft = "rotate:90"; + public $actionRotateRight = "rotate:-90"; + public $actionGrayscale = "grayscale"; + public $actionContrast = "contrast"; + public $actionBrightness = "brightness"; + public $actionUndo = "undo"; + public $actionUpdate = "update"; + public $actionRotateIsSelected = false; + public $actionRotate = ""; + public $actionSeparatorSign = "#"; + public $fieldNameKeepProportions = "keepproportions"; + public $errorMessages = array(); + public $formName = "phpimageeditor"; + public $inputImageName = ''; + public $inputWidth = -1; + public $inputHeight = -1; + public $inputCropLeft = 0; + public $inputCropRight = 0; + public $inputCropTop = 0; + public $inputCropBottom = 0; + public $inputKeepProportions = true; + public $inputCropKeepProportions = false; + public $inputCropKeepProportionsRatio = 1; + public $inputPanel = MENU_RESIZE; + public $inputLanguage = DEFUALT_LANGUAGE; + public $inputContrast = 0; + public $inputBrightness = 0; + public $inputContrastLast = 0; + public $inputBrightnessLast = 0; + public $inputGrayscale = false; + public $httpImageKey = "imagesrc"; + public $texts = array(); + public $actions = ""; + public $isPostBack = false; + public $isAjaxPost = false; + public $finalWidth = -1; + public $finalHeight = -1; + public $widthKeepProportions = -1; + public $heightKeepProportions = -1; + public $userId = ""; + + public $contrastMax = 100; + public $brightnessMax = 255; + + + function PHPImageEditor() + { + $this->LoadLanguage(); + + if (version_compare(phpversion(), PHP_VERSION_MINIMUM, "<")) + { + $this->errorMessages[] = phpversion()." ".$this->texts["OLD PHP VERSION"]." ".PHP_VERSION_MINIMUM; + return; + } + + $this->isPostBack = isset($_POST["actiontype"]); + + $srcEdit = ""; + + if ($_GET[$this->httpImageKey] != NULL) + { + $srcEdit = $_GET[$this->httpImageKey]; + } + + if ($srcEdit == "") + { + $this->errorMessages[] = $this->texts["NO PROVIDED IMAGE"]; + return; + } + + $this->srcEdit = urldecode($srcEdit); + $this->inputImageName = urlencode($_GET['image_name']); + + if (isset($_POST["userid"])) + $this->userId = $_POST["userid"]; + else + $this->userId = "_".time()."_".str_replace(".", "_", $_SERVER['REMOTE_ADDR']); + + $this->SetSrcOriginal(); + $this->SetSrcPng(); + $this->SetSrcWorkWith(); + + if (!file_exists($this->srcEdit)) + { + $this->errorMessages[] = $this->texts["IMAGE DOES NOT EXIST"]; + return; + } + + $info = getimagesize($this->srcEdit); + + if (!$info) + { + $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"]; + return; + } + + $this->mimeType = image_type_to_mime_type($info[2]); + + if ($this->mimeType == image_type_to_mime_type(IMAGETYPE_JPEG) || $this->mimeType == image_type_to_mime_type(IMAGETYPE_GIF) || $this->mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + if (!$this->isPostBack) + $this->SaveOriginal(); + + $this->resourceWorkWith = $this->CreateImage($this->srcOriginal); + $this->SavePng(); + copy($this->srcPng, $this->srcWorkWith); + + $this->resourceWorkWith = $this->CreateImage($this->srcPng); + } + else + { + $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"]; + return; + } + + $this->finalWidth = $this->GetWidth(); + $this->finalHeight = $this->GetHeight(); + $this->widthKeepProportions = $this->GetWidth(); + $this->heightKeepProportions = $this->GetHeight(); + + $this->GrantAllAccess($this->srcOriginal); + $this->GrantAllAccess($this->srcPng); + $this->GrantAllAccess($this->srcWorkWith); + + if ($this->isPostBack) + { + $this->actionRotateIsSelected = ($_POST["rotate"] != "-1"); + $this->actionRotate = $_POST["rotate"]; + $this->actions = $_POST["actions"]; + $this->isAjaxPost = ($_POST["isajaxpost"] == "true"); + +// $this->inputImageName = $_POST['image_name']; + $this->inputWidth = (int)$_POST["width"]; + $this->inputHeight = (int)$_POST["height"]; + $this->inputCropLeft = (int)$_POST["cropleft"]; + $this->inputCropRight = (int)$_POST["cropright"]; + $this->inputCropTop = (int)$_POST["croptop"]; + $this->inputCropBottom = (int)$_POST["cropbottom"]; + $this->inputPanel = (int)$_POST["panel"]; + $this->inputLanguage = $_POST["language"]; + $this->inputKeepProportions = ($_POST["keepproportionsval"] == "1"); + $this->inputCropKeepProportions = ($_POST["cropkeepproportionsval"] == "1"); + $this->inputCropKeepProportionsRatio = (float)$_POST["cropkeepproportionsratio"]; + $this->inputGrayscale = ($_POST["grayscaleval"] == "1"); + $this->inputBrightness = (int)$_POST["brightness"]; + $this->inputContrast = (int)$_POST["contrast"]; + $this->inputBrightnessLast = (int)$_POST["brightnesslast"]; + $this->inputContrastLast = (int)$_POST["contrastlast"]; + + $this->Action($_POST["actiontype"]); + } + } + + function LoadLanguage() + { + $language = ""; + + if (isset($_POST["language"])) + { + $this->inputLanguage = $_POST["language"]; + $language = $this->inputLanguage; + } + else if (isset($_GET["language"])) + { + $this->inputLanguage = $_GET["language"]; + $language = $this->inputLanguage; + } + else + $language = DEFUALT_LANGUAGE; + + $tryLanguage = "language/".$language."/".$language.".com_admin.ini"; + if (file_exists($tryLanguage)) + $this->texts = PIE_GetTexts("language/".$language."/".$language.".com_admin.ini"); + else + $this->texts = PIE_GetTexts("language/".DEFUALT_LANGUAGE."/".DEFUALT_LANGUAGE.".com_admin.ini"); + } + + function SetSrcOriginal() + { + $arr = explode("/", $this->srcEdit); + $this->srcOriginal = IMAGE_ORIGINAL_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + } + + function SetSrcWorkWith() + { + $arr = explode("/", $this->srcEdit); + $srcWorkWith = IMAGE_WORK_WITH_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + $srcWorkWith = substr($srcWorkWith, 0, strripos($srcWorkWith, ".")).".png"; + $this->srcWorkWith = $srcWorkWith; + } + + function SetSrcPng() + { + $arr = explode("/", $this->srcEdit); + $srcPng = IMAGE_PNG_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + $srcPng = substr($srcPng, 0, strripos($srcPng, ".")).".png"; + $this->srcPng = $srcPng; + } + + function SaveOriginal() + { + copy($this->srcEdit, $this->srcOriginal); + + //Resize to fit in max width/height. + $imageTmp = $this->CreateImage($this->srcOriginal); + $finalWidth = $this->GetWidthFromImage($imageTmp); + $finalHeight = $this->GetHeightFromImage($imageTmp); + + $doSave = false; + + if ($finalWidth > IMAGE_MAX_WIDTH) + { + $widthProp = IMAGE_MAX_WIDTH/$finalWidth; + $finalWidth = IMAGE_MAX_WIDTH; + $finalHeight = round($finalHeight*$widthProp); + $doSave = true; + } + + if ($finalHeight > IMAGE_MAX_HEIGHT) + { + $heightProp = IMAGE_MAX_HEIGHT/$finalHeight; + $finalHeight = IMAGE_MAX_HEIGHT; + $finalWidth = round($finalWidth*$heightProp); + $doSave = true; + } + + if ($doSave) + { + $imageTmp = $this->ActionResize($finalWidth, $finalHeight, $imageTmp); + $this->SaveImage($imageTmp, $this->srcOriginal); + } + } + + function SavePng() + { + $this->SaveImage($this->resourceWorkWith, $this->srcPng, image_type_to_mime_type(IMAGETYPE_PNG)); + } + + function ErrorHasOccurred() + { + return (count($this->errorMessages) > 0); + } + + function GetWidthFinal() + { + return $this->finalWidth; + } + + function GetHeightFinal() + { + return $this->finalHeight; + } + + function GetWidth() + { + return $this->GetWidthFromImage($this->resourceWorkWith); + } + + function GetWidthLast() + { + if ($this->isPostBack) + return (int)$_POST["widthlast"]; + + return $this->GetWidth(); + } + + function GetHeight() + { + return $this->GetHeightFromImage($this->resourceWorkWith); + } + + function GetHeightLast() + { + if ($this->isPostBack) + return (int)$_POST["heightlast"]; + + return $this->GetWidth(); + } + + function GetImageNameFinal() + { + if ($this->isPostBack) + return $_POST["image_name"]; + + return $this->inputImageName; + } + + function getImageName() + { + return $this->inputImageName; + } + + function GetWidthFromImage($image) + { + return imagesx($image); + } + + function GetHeightFromImage($image) + { + return imagesy($image); + } + + function Action($actionType) + { + $doSave = false; + + if ($actionType == $this->actionUndo) { + $this->ActionUndo(); + $doSave = true; + } + + if ( $actionType == $this->actionUpdate + || $actionType == $this->actionSaveAndClose) { + if ( $this->inputWidth != $this->GetWidthLast() + || $this->inputHeight != $this->GetHeightLast()) { + $this->actions .= $this->GetActionSeparator()."resize:".$this->inputWidth.",".$this->inputHeight; + } + + if ( $this->inputCropLeft != 0 || $this->inputCropRight != 0 + || $this->inputCropTop != 0 || $this->inputCropBottom != 0) { + $this->actions + .= $this->GetActionSeparator() + ."crop:".$this->inputCropLeft."," + .$this->inputCropRight."," + .$this->inputCropTop."," + .$this->inputCropBottom; + } +// var_dump($this->inputImageName); +// var_dump($this->getImageNameFinal()); +// var_dump($_POST); +// var_dump($_GET); +// exit; + if (urldecode($this->inputImageName) != $this->GetImageNameFinal()) { + $this->actions .= $this->GetActionSeparator ()."imageName:".$this->GetImageNameFinal(); + } + $doSave = true; + } + + if ($actionType == $this->actionUpdate && $this->inputGrayscale) { + if (strpos($this->actions, $this->actionGrayscale) === false) { + $this->actions .= $this->GetActionSeparator().$this->actionGrayscale.":0"; + $doSave = true; + } + } else if ($actionType == $this->actionUpdate && !$this->inputGrayscale) { + if (!(strpos($this->actions, $this->actionGrayscale) === false)) { + $this->actions = str_replace($this->actionGrayscale.":0".$this->GetActionSeparator(), "", $this->actions); + $this->actions = str_replace($this->GetActionSeparator().$this->actionGrayscale.":0", "", $this->actions); + $this->actions = str_replace($this->actionGrayscale.":0", "", $this->actions); + $doSave = true; + } + } + + if ($this->inputContrast != $this->inputContrastLast) { + $this->actions .= $this->GetActionSeparator().$this->actionContrast.":".$this->inputContrast; + $doSave = true; + } + + if ($this->inputBrightness != $this->inputBrightnessLast) { + $this->actions .= $this->GetActionSeparator().$this->actionBrightness.":".$this->inputBrightness; + $doSave = true; + } + + if ($this->actionRotateIsSelected) { + if ($this->actionRotate == $this->actionRotateLeft) { + $this->actions .= $this->GetActionSeparator().$this->actionRotateLeft; + $doSave = true; + } else if ($this->actionRotate == $this->actionRotateRight) { + $this->actions .= $this->GetActionSeparator().$this->actionRotateRight; + $doSave = true; + } + } + + $finalContrast = 0; + $finalBrightness = 0; + $finalContrastFound = false; + $finalBrightnessFound = false; + $finalGrayscale = false; + + if ($doSave && $this->actions != "") { + $allActions = explode($this->actionSeparatorSign, $this->actions); + + $finalRotate = 0; + $finalCropLeft = 0; + $finalCropRight = 0; + $finalCropTop = 0; + $finalCropBottom = 0; + + $doSwitch = false; + + foreach ($allActions as $loopAction) { + $actionDetail = explode(":", $loopAction); + $actionValues = explode(",", $actionDetail[1]); + + if ($actionDetail[0] == "resize") { + $this->finalWidth = (int)$actionValues[0]; + $this->finalHeight = (int)$actionValues[1]; + } else if ($actionDetail[0] == "crop") { + $actionValueLeft = (int)$actionValues[0]; + $actionValueRight = (int)$actionValues[1]; + $actionValueTop = (int)$actionValues[2]; + $actionValueBottom = (int)$actionValues[3]; + + $widthProp = 1; + $heightProp = 1; + + if ($doSwitch) { + $widthProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalWidth); + $heightProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalHeight); + } else { + $widthProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalWidth); + $heightProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalHeight); + } + + $cropLeft = $actionValueLeft * $widthProp; + $cropRight = $actionValueRight * $widthProp; + $cropTop = $actionValueTop * $heightProp; + $cropBottom = $actionValueBottom * $heightProp; + + $cropValues = array(); + $cropValues[] = $cropRight; + $cropValues[] = $cropBottom; + $cropValues[] = $cropLeft; + $cropValues[] = $cropTop; + + if ($finalRotate != 0) + $cropValues = $this->RotateArray(($finalRotate/-90), $cropValues); + + $finalCropRight += $cropValues[0]; + $finalCropBottom += $cropValues[1]; + $finalCropLeft += $cropValues[2]; + $finalCropTop += $cropValues[3]; + + $this->finalWidth -= ($actionValueLeft + $actionValueRight); + $this->finalHeight -= ($actionValueTop + $actionValueBottom); + } else if ($actionDetail[0] == $this->actionGrayscale && $this->inputGrayscale) { + $finalGrayscale = true; + } else if ($actionDetail[0] == "contrast") { + $finalContrastFound = true; + $finalContrast = $actionValues[0]; + } else if ($actionDetail[0] == "brightness") { + $finalBrightnessFound = true; + $finalBrightness = $actionValues[0]; + } else if ($actionDetail[0] == "rotate") { + $finalRotate += (int)$actionValues[0]; + $finalWidthTmp = $this->finalWidth; + $this->finalWidth = $this->finalHeight; + $this->finalHeight = $finalWidthTmp; + } + + if ($finalRotate == -360 || $finalRotate == 360) { + $finalRotate = 0; + } + + $doSwitch = ($finalRotate != 0 && ($finalRotate == 90 || $finalRotate == 270 || $finalRotate == -90 || $finalRotate == -270)); + } + + //1. All effects. + if ($finalGrayscale) { + $this->ActionGrayscale(); + } + + if ($finalBrightnessFound) { + $this->ActionBrightness($finalBrightness); + } + + if ($finalContrastFound) { + $this->ActionContrast($finalContrast*-1); + } + + //2. Do cropping. + $finalCropLeft = round($finalCropLeft); + $finalCropRight = round($finalCropRight); + $finalCropTop = round($finalCropTop); + $finalCropBottom = round($finalCropBottom); + if ($finalCropLeft != 0 || $finalCropRight != 0 || $finalCropTop != 0 || $finalCropBottom != 0) { + $this->ActionCrop($finalCropLeft, $finalCropRight, $finalCropTop, $finalCropBottom); + } + + //3. Rotate + if ($finalRotate != 0) { + $this->ActionRotate($finalRotate); + } + + //Calculate keep proportions values. + if (round($this->finalWidth/$this->finalHeight,1) == round($this->GetWidth()/$this->GetHeight(),1)) { + //It seems to have the same proportions as the original. Use the original proportions value. + $this->widthKeepProportions = $this->GetWidth(); + $this->heightKeepProportions = $this->GetHeight(); + } else { + //The proportions has been changed. Use the new width and height instead. + $this->widthKeepProportions = $this->finalWidth; + $this->heightKeepProportions = $this->finalHeight; + } + + //4. Resize + if ($this->finalWidth > 0 && $this->finalHeight > 0) + $this->resourceWorkWith = $this->ActionResize($this->finalWidth, $this->finalHeight, $this->resourceWorkWith); + + $this->SaveImage($this->resourceWorkWith, $this->srcWorkWith, image_type_to_mime_type(IMAGETYPE_PNG)); + } + + $this->inputBrightness = $finalBrightness; + $this->inputContrast = $finalContrast; + $this->inputGrayscale = $finalGrayscale; + + if ($actionType == $this->actionSaveAndClose) { + $this->SaveImage($this->resourceWorkWith, $this->srcEdit, $this->mimeType); + + /*** GLM stuff ***/ + require_once '../../setup.phtml'; + $CKUpdater = new Toolkit_CKImages_ImageUpdater(Toolkit_Database::getInstance()); + $CKUpdater->load(basename($_GET['imagesrc'])); + $CKUpdater->update(new Toolkit_FileServer_ImageAdapter()); + /*****************/ + + unlink($this->srcOriginal); + unlink($this->srcPng); + unlink($this->srcWorkWith); + $this->DeleteOldImages(IMAGE_ORIGINAL_PATH); + $this->DeleteOldImages(IMAGE_PNG_PATH); + $this->DeleteOldImages(IMAGE_WORK_WITH_PATH); + $reloadParentBrowser = RELOAD_PARENT_BROWSER_ON_SAVE ? 'window.opener.location.reload();' : ''; + PIE_Echo(''); + } + } + + function ActionResize($width, $height, $image) + { + $newImage = @imagecreatetruecolor($width, $height); + imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $this->GetWidthFromImage($image), $this->GetHeightFromImage($image)); + return $newImage; + } + + function ActionCrop($cropLeft, $cropRight, $cropTop, $cropBottom) + { + $cropWidth = $this->GetWidth() - $cropLeft - $cropRight; + $cropHeight = $this->GetHeight() - $cropTop - $cropBottom; + + $newImageCropped = @imagecreatetruecolor($cropWidth, $cropHeight); + imagecopy($newImageCropped, $this->resourceWorkWith, 0, 0, $cropLeft, $cropTop, $cropWidth, $cropHeight); + + $this->resourceWorkWith = $newImageCropped; + } + + function ActionUndo() + { + $separatorPos = strrpos($this->actions, $this->actionSeparatorSign); + if (!($separatorPos === false)) + { + $this->actions = substr($this->actions, 0, $separatorPos); + } + else + { + $this->actions = ""; + } + } + + function CreateImage($srcEdit) + { + $info = getimagesize($srcEdit); + + if (!$info) + return NULL; + + $mimeType = image_type_to_mime_type($info[2]); + + if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG)) + { + return imagecreatefromjpeg($srcEdit); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF)) + { + return imagecreatefromgif($srcEdit); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + return imagecreatefrompng($srcEdit); + } + + return NULL; + } + + function ActionRotate($Degrees) + { + $this->resourceWorkWith = imagerotate($this->resourceWorkWith, $Degrees, 0); + } + + function ActionGrayscale() + { + imagefilter($this->resourceWorkWith, IMG_FILTER_GRAYSCALE); + } + + function ActionContrast($contrast) + { + //-100 = max contrast, 0 = no change, +100 = min contrast + imagefilter($this->resourceWorkWith, IMG_FILTER_CONTRAST, $contrast); + } + + function ActionBrightness($light) + { + //-255 = min brightness, 0 = no change, +255 = max brightness + imagefilter($this->resourceWorkWith, IMG_FILTER_BRIGHTNESS, $light); + } + + function GetErrorMessages() + { + if (count($this->errorMessages)) + { + PIE_Echo('
    '); + PIE_Echo('
      '); + + foreach ($this->errorMessages as $errorMessage) + PIE_Echo ('
    • '.$errorMessage.'
    • '); + + PIE_Echo("
    "); + PIE_Echo('
    '); + } + } + + function GetActions() + { + PIE_Echo($this->actions); + } + + function GetActionSeparator() + { + if ($this->actions != "") + return $this->actionSeparatorSign; + + return ""; + } + + function SaveImage($image, $toSrc, $mimeType = -1) + { + if ($mimeType == -1) + $mimeType = $this->mimeType; + + if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG)) + { + imagejpeg($image, $toSrc); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF)) + { + imagegif($image, $toSrc); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + imagepng($image, $toSrc); + } + } + + function CleanUp() + { + if ($this->resourceWorkWith) + imagedestroy($this->resourceWorkWith); + } + + function RotateArray($numberOfSteps, $arr) + { + $finalArray = array(); + + //-3 to 3 + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 0)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 1)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 2)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 3)]; + + return $finalArray; + } + + function NumberOfStepsCalculator($sum) + { + $maxIndex = 3; + if ($sum > $maxIndex) + return ($sum-$maxIndex)-1; + else if ($sum < 0) + { + return ($sum+$maxIndex)+1; + } + + return $sum; + } + + function AddUserIdToImageSrc($imageSrc) + { + return str_replace(".", $this->userId.".", $imageSrc); + } + + function IsPHP5OrHigher() + { + return version_compare(phpversion(), "5", ">="); + } + + function GetFormAction() + { + return "index.php?" + . $this->httpImageKey . "=" . $this->srcEdit + . '&image_name=' . $this->inputImageName; + } + + function GetWidthKeepProportions() + { + return $this->widthKeepProportions; + } + + function GetHeightKeepProportions() + { + return $this->heightKeepProportions; + } + + function DeleteOldImages($srcdir) + { + if($curdir = opendir($srcdir)) + { + while($file = readdir($curdir)) + { + if($file != '.' && $file != '..') + { + //$srcfile = $srcdir . '\\' . $file; + //$srcfile = $srcdir.'/'.$file; + $srcfile = $srcdir.$file; + $srcfileLower = strtolower($srcfile); + + if (stripos($srcfile, ".svn") === false) + { + if(is_file($srcfile)) + { + $doDelete = true; + + if (substr_count($srcfile, "sample.jpg") > 0 || substr_count($srcfile, "sample.png") > 0 || (substr_count($srcfileLower, ".jpg") == 0 && substr_count($srcfileLower, ".gif") == 0 && substr_count($srcfileLower, ".png") == 0)) + $doDelete = false; + + if ($doDelete) + { + + $deleteTime = mktime(0, 0, 0, date("m"), date("d")-2, date("Y")); + if (fileatime($srcfile) < $deleteTime) + { + //Image is old and will be deleted. Or else the server space will be filled up with not needed images. + //echo "

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

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

    ";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="
    ";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("
    ").append(M.responseText.replace(//g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='
    ';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js b/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js new file mode 100644 index 0000000..ad261f9 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js @@ -0,0 +1,1197 @@ +/** + * jquery.Jcrop.js v0.9.8 + * jQuery Image Cropping Plugin + * @author Kelly Hallman + * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{ + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + + * }}} + */ + +(function($) { + +$.Jcrop = function(obj,opt) +{ + // Initialization {{{ + + // Sanitize some options {{{ + var obj = obj, opt = opt; + + if (typeof(obj) !== 'object') obj = $(obj)[0]; + if (typeof(opt) !== 'object') opt = { }; + + // Some on-the-fly fixes for MSIE...sigh + if (!('trackDocument' in opt)) + { + opt.trackDocument = $.browser.msie ? false : true; + if ($.browser.msie && $.browser.version.split('.')[0] == '8') + opt.trackDocument = true; + } + + if (!('keySupport' in opt)) + opt.keySupport = $.browser.msie ? false : true; + + // }}} + // Extend the default options {{{ + var defaults = { + + // Basic Settings + trackDocument: false, + baseClass: 'jcrop', + addClass: null, + + // Styling Options + bgColor: 'black', + bgOpacity: .6, + borderOpacity: .4, + handleOpacity: .5, + + handlePad: 5, + handleSize: 9, + handleOffset: 5, + edgeMargin: 14, + + aspectRatio: 0, + keySupport: true, + cornerHandles: true, + sideHandles: true, + drawBorders: true, + dragEdges: true, + + boxWidth: 0, + boxHeight: 0, + + boundary: 8, + animationDelay: 20, + swingSpeed: 3, + + allowSelect: true, + allowMove: true, + allowResize: true, + + minSelect: [ 0, 0 ], + maxSize: [ 0, 0 ], + minSize: [ 0, 0 ], + + // Callbacks / Event Handlers + onChange: function() { }, + onSelect: function() { } + + }; + var options = defaults; + setOptions(opt); + + // }}} + // Initialize some jQuery objects {{{ + + var $origimg = $(obj); + var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' }); + + $img.width($origimg.width()); + $img.height($origimg.height()); + $origimg.after($img).hide(); + + presize($img,options.boxWidth,options.boxHeight); + + var boundx = $img.width(), + boundy = $img.height(), + + $div = $('
    ') + .width(boundx).height(boundy) + .addClass(cssClass('holder')) + .css({ + position: 'relative', + backgroundColor: options.bgColor + }).insertAfter($origimg).append($img); + ; + + if (options.addClass) $div.addClass(options.addClass); + //$img.wrap($div); + + var $img2 = $('')/*{{{*/ + .attr('src',$img.attr('src')) + .css('position','absolute') + .width(boundx).height(boundy) + ;/*}}}*/ + var $img_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css({ + zIndex: 310, + position: 'absolute', + overflow: 'hidden' + }) + .append($img2) + ;/*}}}*/ + var $hdl_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css('zIndex',320); + /*}}}*/ + var $sel = $('
    ')/*{{{*/ + .css({ + position: 'absolute', + zIndex: 300 + }) + .insertBefore($img) + .append($img_holder,$hdl_holder) + ;/*}}}*/ + + var bound = options.boundary; + var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2)) + .css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 }) + .mousedown(newSelection); + + /* }}} */ + // Set more variables {{{ + + var xlimit, ylimit, xmin, ymin; + var xscale, yscale, enabled = true; + var docOffset = getPos($img), + // Internal states + btndown, lastcurs, dimmed, animating, + shift_down; + + // }}} + + + // }}} + // Internal Modules {{{ + + var Coords = function()/*{{{*/ + { + var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy; + + function setPressed(pos)/*{{{*/ + { + var pos = rebound(pos); + x2 = x1 = pos[0]; + y2 = y1 = pos[1]; + }; + /*}}}*/ + function setCurrent(pos)/*{{{*/ + { + var pos = rebound(pos); + ox = pos[0] - x2; + oy = pos[1] - y2; + x2 = pos[0]; + y2 = pos[1]; + }; + /*}}}*/ + function getOffset()/*{{{*/ + { + return [ ox, oy ]; + }; + /*}}}*/ + function moveOffset(offset)/*{{{*/ + { + var ox = offset[0], oy = offset[1]; + + if (0 > x1 + ox) ox -= ox + x1; + if (0 > y1 + oy) oy -= oy + y1; + + if (boundy < y2 + oy) oy += boundy - (y2 + oy); + if (boundx < x2 + ox) ox += boundx - (x2 + ox); + + x1 += ox; + x2 += ox; + y1 += oy; + y2 += oy; + }; + /*}}}*/ + function getCorner(ord)/*{{{*/ + { + var c = getFixed(); + switch(ord) + { + case 'ne': return [ c.x2, c.y ]; + case 'nw': return [ c.x, c.y ]; + case 'se': return [ c.x2, c.y2 ]; + case 'sw': return [ c.x, c.y2 ]; + } + }; + /*}}}*/ + function getFixed()/*{{{*/ + { + if (!options.aspectRatio) return getRect(); + // This function could use some optimization I think... + var aspect = options.aspectRatio, + min_x = options.minSize[0]/xscale, + min_y = options.minSize[1]/yscale, + max_x = options.maxSize[0]/xscale, + max_y = options.maxSize[1]/yscale, + rw = x2 - x1, + rh = y2 - y1, + rwa = Math.abs(rw), + rha = Math.abs(rh), + real_ratio = rwa / rha, + xx, yy + ; + if (max_x == 0) { max_x = boundx * 10 } + if (max_y == 0) { max_y = boundy * 10 } + if (real_ratio < aspect) + { + yy = y2; + w = rha * aspect; + xx = rw < 0 ? x1 - w : w + x1; + + if (xx < 0) + { + xx = 0; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h: h + y1; + } + else if (xx > boundx) + { + xx = boundx; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h : h + y1; + } + } + else + { + xx = x2; + h = rwa / aspect; + yy = rh < 0 ? y1 - h : y1 + h; + if (yy < 0) + { + yy = 0; + w = Math.abs((yy - y1) * aspect); + xx = rw < 0 ? x1 - w : w + x1; + } + else if (yy > boundy) + { + yy = boundy; + w = Math.abs(yy - y1) * aspect; + xx = rw < 0 ? x1 - w : w + x1; + } + } + + // Magic %-) + if(xx > x1) { // right side + if(xx - x1 < min_x) { + xx = x1 + min_x; + } else if (xx - x1 > max_x) { + xx = x1 + max_x; + } + if(yy > y1) { + yy = y1 + (xx - x1)/aspect; + } else { + yy = y1 - (xx - x1)/aspect; + } + } else if (xx < x1) { // left side + if(x1 - xx < min_x) { + xx = x1 - min_x + } else if (x1 - xx > max_x) { + xx = x1 - max_x; + } + if(yy > y1) { + yy = y1 + (x1 - xx)/aspect; + } else { + yy = y1 - (x1 - xx)/aspect; + } + } + + if(xx < 0) { + x1 -= xx; + xx = 0; + } else if (xx > boundx) { + x1 -= xx - boundx; + xx = boundx; + } + + if(yy < 0) { + y1 -= yy; + yy = 0; + } else if (yy > boundy) { + y1 -= yy - boundy; + yy = boundy; + } + + return last = makeObj(flipCoords(x1,y1,xx,yy)); + }; + /*}}}*/ + function rebound(p)/*{{{*/ + { + if (p[0] < 0) p[0] = 0; + if (p[1] < 0) p[1] = 0; + + if (p[0] > boundx) p[0] = boundx; + if (p[1] > boundy) p[1] = boundy; + + return [ p[0], p[1] ]; + }; + /*}}}*/ + function flipCoords(x1,y1,x2,y2)/*{{{*/ + { + var xa = x1, xb = x2, ya = y1, yb = y2; + if (x2 < x1) + { + xa = x2; + xb = x1; + } + if (y2 < y1) + { + ya = y2; + yb = y1; + } + return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ]; + }; + /*}}}*/ + function getRect()/*{{{*/ + { + var xsize = x2 - x1; + var ysize = y2 - y1; + + if (xlimit && (Math.abs(xsize) > xlimit)) + x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit); + if (ylimit && (Math.abs(ysize) > ylimit)) + y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit); + + if (ymin && (Math.abs(ysize) < ymin)) + y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin); + if (xmin && (Math.abs(xsize) < xmin)) + x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin); + + if (x1 < 0) { x2 -= x1; x1 -= x1; } + if (y1 < 0) { y2 -= y1; y1 -= y1; } + if (x2 < 0) { x1 -= x2; x2 -= x2; } + if (y2 < 0) { y1 -= y2; y2 -= y2; } + if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; } + if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; } + if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; } + if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; } + + return makeObj(flipCoords(x1,y1,x2,y2)); + }; + /*}}}*/ + function makeObj(a)/*{{{*/ + { + return { x: a[0], y: a[1], x2: a[2], y2: a[3], + w: a[2] - a[0], h: a[3] - a[1] }; + }; + /*}}}*/ + + return { + flipCoords: flipCoords, + setPressed: setPressed, + setCurrent: setCurrent, + getOffset: getOffset, + moveOffset: moveOffset, + getCorner: getCorner, + getFixed: getFixed + }; + }(); + + /*}}}*/ + var Selection = function()/*{{{*/ + { + var start, end, dragmode, awake, hdep = 370; + var borders = { }; + var handle = { }; + var seehandles = false; + var hhs = options.handleOffset; + + /* Insert draggable elements {{{*/ + + // Insert border divs for outline + if (options.drawBorders) { + borders = { + top: insertBorder('hline') + .css('top',$.browser.msie?px(-1):px(0)), + bottom: insertBorder('hline'), + left: insertBorder('vline'), + right: insertBorder('vline') + }; + } + + // Insert handles on edges + if (options.dragEdges) { + handle.t = insertDragbar('n'); + handle.b = insertDragbar('s'); + handle.r = insertDragbar('e'); + handle.l = insertDragbar('w'); + } + + // Insert side handles + options.sideHandles && + createHandles(['n','s','e','w']); + + // Insert corner handles + options.cornerHandles && + createHandles(['sw','nw','ne','se']); + + /*}}}*/ + // Private Methods + function insertBorder(type)/*{{{*/ + { + var jq = $('
    ') + .css({position: 'absolute', opacity: options.borderOpacity }) + .addClass(cssClass(type)); + $img_holder.append(jq); + return jq; + }; + /*}}}*/ + function dragDiv(ord,zi)/*{{{*/ + { + var jq = $('
    ') + .mousedown(createDragger(ord)) + .css({ + cursor: ord+'-resize', + position: 'absolute', + zIndex: zi + }) + ; + $hdl_holder.append(jq); + return jq; + }; + /*}}}*/ + function insertHandle(ord)/*{{{*/ + { + return dragDiv(ord,hdep++) + .css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity }) + .addClass(cssClass('handle')); + }; + /*}}}*/ + function insertDragbar(ord)/*{{{*/ + { + var s = options.handleSize, + o = hhs, + h = s, w = s, + t = o, l = o; + + switch(ord) + { + case 'n': case 's': w = pct(100); break; + case 'e': case 'w': h = pct(100); break; + } + + return dragDiv(ord,hdep++).width(w).height(h) + .css({ top: px(-t+1), left: px(-l+1)}); + }; + /*}}}*/ + function createHandles(li)/*{{{*/ + { + for(i in li) handle[li[i]] = insertHandle(li[i]); + }; + /*}}}*/ + function moveHandles(c)/*{{{*/ + { + var midvert = Math.round((c.h / 2) - hhs), + midhoriz = Math.round((c.w / 2) - hhs), + north = west = -hhs+1, + east = c.w - hhs, + south = c.h - hhs, + x, y; + + 'e' in handle && + handle.e.css({ top: px(midvert), left: px(east) }) && + handle.w.css({ top: px(midvert) }) && + handle.s.css({ top: px(south), left: px(midhoriz) }) && + handle.n.css({ left: px(midhoriz) }); + + 'ne' in handle && + handle.ne.css({ left: px(east) }) && + handle.se.css({ top: px(south), left: px(east) }) && + handle.sw.css({ top: px(south) }); + + 'b' in handle && + handle.b.css({ top: px(south) }) && + handle.r.css({ left: px(east) }); + }; + /*}}}*/ + function moveto(x,y)/*{{{*/ + { + $img2.css({ top: px(-y), left: px(-x) }); + $sel.css({ top: px(y), left: px(x) }); + }; + /*}}}*/ + function resize(w,h)/*{{{*/ + { + $sel.width(w).height(h); + }; + /*}}}*/ + function refresh()/*{{{*/ + { + var c = Coords.getFixed(); + + Coords.setPressed([c.x,c.y]); + Coords.setCurrent([c.x2,c.y2]); + + updateVisible(); + }; + /*}}}*/ + + // Internal Methods + function updateVisible()/*{{{*/ + { if (awake) return update(); }; + /*}}}*/ + function update()/*{{{*/ + { + var c = Coords.getFixed(); + + resize(c.w,c.h); + moveto(c.x,c.y); + + options.drawBorders && + borders['right'].css({ left: px(c.w-1) }) && + borders['bottom'].css({ top: px(c.h-1) }); + + seehandles && moveHandles(c); + awake || show(); + + options.onChange(unscale(c)); + }; + /*}}}*/ + function show()/*{{{*/ + { + $sel.show(); + $img.css('opacity',options.bgOpacity); + awake = true; + }; + /*}}}*/ + function release()/*{{{*/ + { + disableHandles(); + $sel.hide(); + $img.css('opacity',1); + awake = false; + }; + /*}}}*/ + function showHandles()//{{{ + { + if (seehandles) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + } + }; + //}}} + function enableHandles()/*{{{*/ + { + seehandles = true; + if (options.allowResize) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + return true; + } + }; + /*}}}*/ + function disableHandles()/*{{{*/ + { + seehandles = false; + $hdl_holder.hide(); + }; + /*}}}*/ + function animMode(v)/*{{{*/ + { + (animating = v) ? disableHandles(): enableHandles(); + }; + /*}}}*/ + function done()/*{{{*/ + { + animMode(false); + refresh(); + }; + /*}}}*/ + + var $track = newTracker().mousedown(createDragger('move')) + .css({ cursor: 'move', position: 'absolute', zIndex: 360 }) + + $img_holder.append($track); + disableHandles(); + + return { + updateVisible: updateVisible, + update: update, + release: release, + refresh: refresh, + setCursor: function (cursor) { $track.css('cursor',cursor); }, + enableHandles: enableHandles, + enableOnly: function() { seehandles = true; }, + showHandles: showHandles, + disableHandles: disableHandles, + animMode: animMode, + done: done + }; + }(); + /*}}}*/ + var Tracker = function()/*{{{*/ + { + var onMove = function() { }, + onDone = function() { }, + trackDoc = options.trackDocument; + + if (!trackDoc) + { + $trk + .mousemove(trackMove) + .mouseup(trackUp) + .mouseout(trackUp) + ; + } + + function toFront()/*{{{*/ + { + $trk.css({zIndex:450}); + if (trackDoc) + { + $(document) + .mousemove(trackMove) + .mouseup(trackUp) + ; + } + } + /*}}}*/ + function toBack()/*{{{*/ + { + $trk.css({zIndex:290}); + if (trackDoc) + { + $(document) + .unbind('mousemove',trackMove) + .unbind('mouseup',trackUp) + ; + } + } + /*}}}*/ + function trackMove(e)/*{{{*/ + { + onMove(mouseAbs(e)); + }; + /*}}}*/ + function trackUp(e)/*{{{*/ + { + e.preventDefault(); + e.stopPropagation(); + + if (btndown) + { + btndown = false; + + onDone(mouseAbs(e)); + options.onSelect(unscale(Coords.getFixed())); + toBack(); + onMove = function() { }; + onDone = function() { }; + } + + return false; + }; + /*}}}*/ + + function activateHandlers(move,done)/* {{{ */ + { + btndown = true; + onMove = move; + onDone = done; + toFront(); + return false; + }; + /* }}} */ + + function setCursor(t) { $trk.css('cursor',t); }; + + $img.before($trk); + return { + activateHandlers: activateHandlers, + setCursor: setCursor + }; + }(); + /*}}}*/ + var KeyManager = function()/*{{{*/ + { + var $keymgr = $('') + .css({ position: 'absolute', left: '-30px' }) + .keypress(parseKey) + .blur(onBlur), + + $keywrap = $('
    ') + .css({ + position: 'absolute', + overflow: 'hidden' + }) + .append($keymgr) + ; + + function watchKeys()/*{{{*/ + { + if (options.keySupport) + { + $keymgr.show(); + $keymgr.focus(); + } + }; + /*}}}*/ + function onBlur(e)/*{{{*/ + { + $keymgr.hide(); + }; + /*}}}*/ + function doNudge(e,x,y)/*{{{*/ + { + if (options.allowMove) { + Coords.moveOffset([x,y]); + Selection.updateVisible(); + }; + e.preventDefault(); + e.stopPropagation(); + }; + /*}}}*/ + function parseKey(e)/*{{{*/ + { + if (e.ctrlKey) return true; + shift_down = e.shiftKey ? true : false; + var nudge = shift_down ? 10 : 1; + switch(e.keyCode) + { + case 37: doNudge(e,-nudge,0); break; + case 39: doNudge(e,nudge,0); break; + case 38: doNudge(e,0,-nudge); break; + case 40: doNudge(e,0,nudge); break; + + case 27: Selection.release(); break; + + case 9: return true; + } + + return nothing(e); + }; + /*}}}*/ + + if (options.keySupport) $keywrap.insertBefore($img); + return { + watchKeys: watchKeys + }; + }(); + /*}}}*/ + + // }}} + // Internal Methods {{{ + + function px(n) { return '' + parseInt(n) + 'px'; }; + function pct(n) { return '' + parseInt(n) + '%'; }; + function cssClass(cl) { return options.baseClass + '-' + cl; }; + function getPos(obj)/*{{{*/ + { + // Updated in v0.9.4 to use built-in dimensions plugin + var pos = $(obj).offset(); + return [ pos.left, pos.top ]; + }; + /*}}}*/ + function mouseAbs(e)/*{{{*/ + { + return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ]; + }; + /*}}}*/ + function myCursor(type)/*{{{*/ + { + if (type != lastcurs) + { + Tracker.setCursor(type); + //Handles.xsetCursor(type); + lastcurs = type; + } + }; + /*}}}*/ + function startDragMode(mode,pos)/*{{{*/ + { + docOffset = getPos($img); + Tracker.setCursor(mode=='move'?mode:mode+'-resize'); + + if (mode == 'move') + return Tracker.activateHandlers(createMover(pos), doneSelect); + + var fc = Coords.getFixed(); + var opp = oppLockCorner(mode); + var opc = Coords.getCorner(oppLockCorner(opp)); + + Coords.setPressed(Coords.getCorner(opp)); + Coords.setCurrent(opc); + + Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect); + }; + /*}}}*/ + function dragmodeHandler(mode,f)/*{{{*/ + { + return function(pos) { + if (!options.aspectRatio) switch(mode) + { + case 'e': pos[1] = f.y2; break; + case 'w': pos[1] = f.y2; break; + case 'n': pos[0] = f.x2; break; + case 's': pos[0] = f.x2; break; + } + else switch(mode) + { + case 'e': pos[1] = f.y+1; break; + case 'w': pos[1] = f.y+1; break; + case 'n': pos[0] = f.x+1; break; + case 's': pos[0] = f.x+1; break; + } + Coords.setCurrent(pos); + Selection.update(); + }; + }; + /*}}}*/ + function createMover(pos)/*{{{*/ + { + var lloc = pos; + KeyManager.watchKeys(); + + return function(pos) + { + Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]); + lloc = pos; + + Selection.update(); + }; + }; + /*}}}*/ + function oppLockCorner(ord)/*{{{*/ + { + switch(ord) + { + case 'n': return 'sw'; + case 's': return 'nw'; + case 'e': return 'nw'; + case 'w': return 'ne'; + case 'ne': return 'sw'; + case 'nw': return 'se'; + case 'se': return 'nw'; + case 'sw': return 'ne'; + }; + }; + /*}}}*/ + function createDragger(ord)/*{{{*/ + { + return function(e) { + if (options.disabled) return false; + if ((ord == 'move') && !options.allowMove) return false; + btndown = true; + startDragMode(ord,mouseAbs(e)); + e.stopPropagation(); + e.preventDefault(); + return false; + }; + }; + /*}}}*/ + function presize($obj,w,h)/*{{{*/ + { + var nw = $obj.width(), nh = $obj.height(); + if ((nw > w) && w > 0) + { + nw = w; + nh = (w/$obj.width()) * $obj.height(); + } + if ((nh > h) && h > 0) + { + nh = h; + nw = (h/$obj.height()) * $obj.width(); + } + xscale = $obj.width() / nw; + yscale = $obj.height() / nh; + $obj.width(nw).height(nh); + }; + /*}}}*/ + function unscale(c)/*{{{*/ + { + return { + x: parseInt(c.x * xscale), y: parseInt(c.y * yscale), + x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale), + w: parseInt(c.w * xscale), h: parseInt(c.h * yscale) + }; + }; + /*}}}*/ + function doneSelect(pos)/*{{{*/ + { + var c = Coords.getFixed(); + if (c.w > options.minSelect[0] && c.h > options.minSelect[1]) + { + Selection.enableHandles(); + Selection.done(); + } + else + { + Selection.release(); + } + Tracker.setCursor( options.allowSelect?'crosshair':'default' ); + }; + /*}}}*/ + function newSelection(e)/*{{{*/ + { + if (options.disabled) return false; + if (!options.allowSelect) return false; + btndown = true; + docOffset = getPos($img); + Selection.disableHandles(); + myCursor('crosshair'); + var pos = mouseAbs(e); + Coords.setPressed(pos); + Tracker.activateHandlers(selectDrag,doneSelect); + KeyManager.watchKeys(); + Selection.update(); + + e.stopPropagation(); + e.preventDefault(); + return false; + }; + /*}}}*/ + function selectDrag(pos)/*{{{*/ + { + Coords.setCurrent(pos); + Selection.update(); + }; + /*}}}*/ + function newTracker() + { + var trk = $('
    ').addClass(cssClass('tracker')); + $.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' }); + return trk; + }; + + // }}} + // API methods {{{ + + function animateTo(a)/*{{{*/ + { + var x1 = a[0] / xscale, + y1 = a[1] / yscale, + x2 = a[2] / xscale, + y2 = a[3] / yscale; + + if (animating) return; + + var animto = Coords.flipCoords(x1,y1,x2,y2); + var c = Coords.getFixed(); + var animat = initcr = [ c.x, c.y, c.x2, c.y2 ]; + var interv = options.animationDelay; + + var x = animat[0]; + var y = animat[1]; + var x2 = animat[2]; + var y2 = animat[3]; + var ix1 = animto[0] - initcr[0]; + var iy1 = animto[1] - initcr[1]; + var ix2 = animto[2] - initcr[2]; + var iy2 = animto[3] - initcr[3]; + var pcent = 0; + var velocity = options.swingSpeed; + + Selection.animMode(true); + + var animator = function() + { + return function() + { + pcent += (100 - pcent) / velocity; + + animat[0] = x + ((pcent / 100) * ix1); + animat[1] = y + ((pcent / 100) * iy1); + animat[2] = x2 + ((pcent / 100) * ix2); + animat[3] = y2 + ((pcent / 100) * iy2); + + if (pcent < 100) animateStart(); + else Selection.done(); + + if (pcent >= 99.8) pcent = 100; + + setSelectRaw(animat); + }; + }(); + + function animateStart() + { window.setTimeout(animator,interv); }; + + animateStart(); + }; + /*}}}*/ + function setSelect(rect)//{{{ + { + setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]); + }; + //}}} + function setSelectRaw(l) /*{{{*/ + { + Coords.setPressed([l[0],l[1]]); + Coords.setCurrent([l[2],l[3]]); + Selection.update(); + }; + /*}}}*/ + function setOptions(opt)/*{{{*/ + { + if (typeof(opt) != 'object') opt = { }; + options = $.extend(options,opt); + + if (typeof(options.onChange)!=='function') + options.onChange = function() { }; + + if (typeof(options.onSelect)!=='function') + options.onSelect = function() { }; + + }; + /*}}}*/ + function tellSelect()/*{{{*/ + { + return unscale(Coords.getFixed()); + }; + /*}}}*/ + function tellScaled()/*{{{*/ + { + return Coords.getFixed(); + }; + /*}}}*/ + function setOptionsNew(opt)/*{{{*/ + { + setOptions(opt); + interfaceUpdate(); + }; + /*}}}*/ + function disableCrop()//{{{ + { + options.disabled = true; + Selection.disableHandles(); + Selection.setCursor('default'); + Tracker.setCursor('default'); + }; + //}}} + function enableCrop()//{{{ + { + options.disabled = false; + interfaceUpdate(); + }; + //}}} + function cancelCrop()//{{{ + { + Selection.done(); + Tracker.activateHandlers(null,null); + }; + //}}} + function destroy()//{{{ + { + $div.remove(); + $origimg.show(); + }; + //}}} + + function interfaceUpdate(alt)//{{{ + // This method tweaks the interface based on options object. + // Called when options are changed and at end of initialization. + { + options.allowResize ? + alt?Selection.enableOnly():Selection.enableHandles(): + Selection.disableHandles(); + + Tracker.setCursor( options.allowSelect? 'crosshair': 'default' ); + Selection.setCursor( options.allowMove? 'move': 'default' ); + + $div.css('backgroundColor',options.bgColor); + + if ('setSelect' in options) { + setSelect(opt.setSelect); + Selection.done(); + delete(options.setSelect); + } + + if ('trueSize' in options) { + xscale = options.trueSize[0] / boundx; + yscale = options.trueSize[1] / boundy; + } + + xlimit = options.maxSize[0] || 0; + ylimit = options.maxSize[1] || 0; + xmin = options.minSize[0] || 0; + ymin = options.minSize[1] || 0; + + if ('outerImage' in options) + { + $img.attr('src',options.outerImage); + delete(options.outerImage); + } + + Selection.refresh(); + }; + //}}} + + // }}} + + $hdl_holder.hide(); + interfaceUpdate(true); + + var api = { + animateTo: animateTo, + setSelect: setSelect, + setOptions: setOptionsNew, + tellSelect: tellSelect, + tellScaled: tellScaled, + + disable: disableCrop, + enable: enableCrop, + cancel: cancelCrop, + + focus: KeyManager.watchKeys, + + getBounds: function() { return [ boundx * xscale, boundy * yscale ]; }, + getWidgetSize: function() { return [ boundx, boundy ]; }, + + release: Selection.release, + destroy: destroy + + }; + + $origimg.data('Jcrop',api); + return api; +}; + +$.fn.Jcrop = function(options)/*{{{*/ +{ + function attachWhenDone(from)/*{{{*/ + { + var loadsrc = options.useImg || from.src; + var img = new Image(); + img.onload = function() { $.Jcrop(from,options); }; + img.src = loadsrc; + }; + /*}}}*/ + if (typeof(options) !== 'object') options = { }; + + // Iterate over each object, attach Jcrop + this.each(function() + { + // If we've already attached to this object + if ($(this).data('Jcrop')) + { + // The API can be requested this way (undocumented) + if (options == 'api') return $(this).data('Jcrop'); + // Otherwise, we just reset the options... + else $(this).data('Jcrop').setOptions(options); + } + // If we haven't been attached, preload and attach + else attachWhenDone(this); + }); + + // Return "this" so we're chainable a la jQuery plugin-style! + return this; +}; +/*}}}*/ + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/jquery.numeric.js b/Toolkit/PHPImageEditor/javascript/jquery.numeric.js new file mode 100644 index 0000000..a496403 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/jquery.numeric.js @@ -0,0 +1,127 @@ +/* + * + * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk) + * Licensed under the MIT License: + * http://www.opensource.org/licenses/mit-license.php + * + * Version 1.0 + * Demo: http://www.texotela.co.uk/code/jquery/numeric/ + * + * $LastChangedDate: 2007-05-29 11:31:36 +0100 (Tue, 29 May 2007) $ + * $Rev: 2005 $ + */ + +/* + * Allows only valid characters to be entered into input boxes. + * Note: does not validate that the final text is a valid number + * (that could be done by another script, or server-side) + * + * @name numeric + * @param decimal Decimal separator (e.g. '.' or ',' - default is '.') + * @param callback A function that runs if the number is not valid (fires onblur) + * @author Sam Collett (http://www.texotela.co.uk) + * @example $(".numeric").numeric(); + * @example $(".numeric").numeric(","); + * @example $(".numeric").numeric(null, callback); + * + */ +jQuery.fn.numeric = function(decimal, callback) +{ + decimal = decimal || "."; + callback = typeof callback == "function" ? callback : function(){}; + this.keypress( + function(e) + { + var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; + // allow enter/return key (only when in an input box) + if(key == 13 && this.nodeName.toLowerCase() == "input") + { + return true; + } + else if(key == 13) + { + return false; + } + var allow = false; + // allow Ctrl+A + if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true; + // allow Ctrl+X (cut) + if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true; + // allow Ctrl+C (copy) + if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true; + // allow Ctrl+Z (undo) + if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true; + // allow or deny Ctrl+V (paste), Shift+Ins + if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */ + || (e.shiftKey && key == 45)) return true; + // if a number was not pressed + if(key < 48 || key > 57) + { + /* '-' only allowed at start */ + if(key == 45 && this.value.length == 0) return true; + /* only one decimal separator allowed */ + if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) + { + allow = false; + } + // check for other keys that have special purposes + if( + key != 8 /* backspace */ && + key != 9 /* tab */ && + key != 13 /* enter */ && + key != 35 /* end */ && + key != 36 /* home */ && + key != 37 /* left */ && + key != 39 /* right */ && + key != 46 /* del */ + ) + { + allow = false; + } + else + { + // for detecting special keys (listed above) + // IE does not support 'charCode' and ignores them in keypress anyway + if(typeof e.charCode != "undefined") + { + // special keys have 'keyCode' and 'which' the same (e.g. backspace) + if(e.keyCode == e.which && e.which != 0) + { + allow = true; + } + // or keyCode != 0 and 'charCode'/'which' = 0 + else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0) + { + allow = true; + } + } + } + // if key pressed is the decimal and it is not already in the field + if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1) + { + allow = true; + } + } + else + { + allow = true; + } + return allow; + } + ) + .blur( + function() + { + var val = jQuery(this).val(); + if(val != "") + { + var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+"); + if(!re.exec(val)) + { + callback.apply(this); + } + } + } + ); + return this; +} \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/phpimageeditor.js b/Toolkit/PHPImageEditor/javascript/phpimageeditor.js new file mode 100644 index 0000000..1800e34 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/phpimageeditor.js @@ -0,0 +1,711 @@ +var objCrop = null; + +function ajax_post() +{ + if ($('#loading').css('display') == 'none') { + $('#width').attr('disabled','disabled'); + $('#height').attr('disabled','disabled'); + $('#keepproportions').attr('disabled','disabled'); + $('#btnRotateLeft').attr('disabled','disabled'); + $('#btnRotateRight').attr('disabled','disabled'); + $('#croptop').attr('disabled','disabled'); + $('#cropbottom').attr('disabled','disabled'); + $('#cropleft').attr('disabled','disabled'); + $('#cropright').attr('disabled','disabled'); + $('#grayscale').attr('disabled','disabled'); + $('#btnupdate').attr('disabled','disabled'); + $('#btnsave').attr('disabled','disabled'); + $('#btnundo').attr('disabled','disabled'); + $('#brightness_slider_track').slider('disable'); + $('#contrast_slider_track').slider('disable'); + + $('#loading').css('display','block'); + $('#loading_bar').width(0); + $('#loading_bar').animate({width: document.getElementById('loading').offsetWidth-30}, document.getElementById('loading').offsetWidth*10); + + $.ajax({ + timeout: AjaxPostTimeoutMs, + type: "POST", + url: FormAction, + data: "grayscaleval="+$('#grayscaleval').val()+ + "&keepproportionsval="+$('#keepproportionsval').val()+ + "&image_name="+$('#image_name').val()+ + "&width="+$('#width').val()+ + "&widthoriginal="+$('#widthoriginal').val()+ + "&height="+$('#height').val()+ + "&heightoriginal="+$('#heightoriginal').val()+ + "&rotate="+$('#rotate').val()+ + "&croptop="+$('#croptop').val()+ + "&cropleft="+$('#cropleft').val()+ + "&cropright="+$('#cropright').val()+ + "&cropbottom="+$('#cropbottom').val()+ + "&contrast="+$('#contrast').val()+ + "&brightness="+$('#brightness').val()+ + "&actiontype="+$('#actiontype').val()+ + "&panel="+$('#panel').val()+ + "&language="+$('#language').val()+ + "&actions="+$('#actions').val()+ + "&widthlast="+$('#widthlast').val()+ + "&heightlast="+$('#heightlast').val()+ + "&userid="+$('#userid').val()+ + "&contrastlast="+$('#contrastlast').val()+ + "&brightnesslast="+$('#brightnesslast').val()+ + "&widthlastbeforeresize="+$('#widthlastbeforeresize').val()+ + "&heightlastbeforeresize="+$('#heightlastbeforeresize').val()+ + "&cropkeepproportionsval="+$('#cropkeepproportionsval').val()+ + "&cropkeepproportionsratio="+$('#cropkeepproportionsratio').val()+ + "&isajaxpost=true", + success: function(data) + { + $('#phpImageEditor').html(data); + activate_form(); + phpimageeditor_crop_activator(parseInt($('#panel').val())); + phpimageeditor_init(); + $('#loading_bar').stop(); + $('#loading').css('display','none'); + }, + error: function(XMLHttpRequest, textStatus, errorThrown) + { + activate_form(); + $('#ulJsErrors').html(""); + adderror(TextAnUnexpectedError); + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + phpimageeditor_crop_activator(parseInt($('#panel').val())); + $('#loading_bar').stop(); + $('#loading').css('display','none'); + } + }); + + } +} + +function isinteger(s) +{ + var i; + + if (isempty(s)) + if (isinteger.arguments.length == 1) return 0; + else return (isinteger.arguments[1] == true); + + for (i = 0; i < s.length; i++) + { + var c = s.charAt(i); + + if (!isdigit(c)) return false; + } + + return true; +} + +function focus_on_enter(element, event) +{ + if(event.keyCode == 13) + element.focus(); +} + +function reload_mouse_crop() +{ + objCrop.destroy(); + objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("#cropkeepproportionsratio").val() : 0}); + $(".jcrop-holder").css("display", "none"); + $("#image").css("display", "block"); +} + +function update_width(InputWidth, EditForm) +{ + if (isinteger(InputWidth.val())) + { + var Width = parseInt($('#width').val()); + var Height = parseInt($('#height').val()); + + $('#image').css('width',Width+'px'); + + if ($("input#keepproportions").attr('checked')) + { + $('#image').css('height', get_proportional_height(Width, EditForm) + "px"); + $('#height').val(get_proportional_height(Width, EditForm)); + } + + update_mouse_resizer(); + reload_mouse_crop(); + } +} + +function update_mouse_resizer() +{ + $('#imageResizerKeepProportions').css('width',$('#width').val()+'px'); + $('#imageResizerKeepProportions').css('height',$('#height').val()+'px'); + $('#imageResizerNoProportions').css('width',$('#width').val()+'px'); + $('#imageResizerNoProportions').css('height',$('#height').val()+'px'); +} + +function update_height(InputHeight, EditForm) +{ + if (isinteger(InputHeight.val())) + { + var Height = parseInt($('#height').val()); + var Width = parseInt($('#width').val()); + + $('#image').css('height',$('#height').val()+'px'); + + if ($("input#keepproportions").attr('checked')) + { + $('#image').css('width',get_proportional_width(Height, EditForm)+'px'); + $('#width').val(get_proportional_width(Height, EditForm)); + } + + update_mouse_resizer(); + reload_mouse_crop(); + } +} + +function isempty(s) +{ + return ((s == null) || (s.length == 0)) +} + +function isdigit (c) +{ + return ((c >= "0") && (c <= "9")) +} + +function isintegerinrange(s, a, b) +{ + if (isempty(s)) + if (isintegerinrange.arguments.length == 1) return false; + else return (isintegerinrange.arguments[1] == true); + + // Catch non-integer strings to avoid creating a NaN below, + // which isn't available on JavaScript 1.0 for Windows. + if (!isinteger(s, false)) return false; + + // Now, explicitly change the type to integer via parseInt + // so that the comparison code below will work both on + // JavaScript 1.2 (which typechecks in equality comparisons) + // and JavaScript 1.1 and before (which doesn't). + var num = parseInt (s); + return ((num >= a) && (num <= b)); +} + +function validate_form() +{ + var sendForm = true; + + var width = $('#width').val(); + var height = $('#height').val(); + var cropleft = $('#cropleft').val(); + var cropright = $('#cropright').val(); + var croptop = $('#croptop').val(); + var cropbottom = $('#cropbottom').val(); + var imageName = $('#image_name').val(); + + $('#divJsErrors').css('display','none'); + $('#ulJsErrors').css('display','none'); + + $('#ulJsErrors').html(""); + + if (imageName == "") { + adderror("\"Image Name\" is Required!" ); + sendForm = false; + } + + if (width == "") + { + adderror("\"" + TextWidth + "\" " + TextIsRequired) + sendForm = false; + } + + if (height == "") + { + adderror("\"" + TextHeight + "\" " + TextIsRequired) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + + return sendForm; + } + + if (!isinteger(width)) + { + adderror("\"" + TextWidth + "\" " + TextMustBeNumeric) + sendForm = false; + } + + if (!isinteger(height)) + { + adderror("\"" + TextHeight + "\" " + TextMustBeNumeric) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + return sendForm; + } + + width = parseInt(width); + height = parseInt(height); + + if (!isintegerinrange(width, 1, ImageMaxWidth)) + { + adderror("\"" + TextWidth + "\" " + TextNotInRange + ": 1 - " + ImageMaxWidth) + sendForm = false; + } + + if (!isintegerinrange(height, 1, ImageMaxHeight)) + { + adderror("\"" + TextHeight + "\" " + TextNotInRange + ": 1 - " + ImageMaxHeight) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + } + + return sendForm; +} + +function adderror(ErrorText) +{ + $('#ulJsErrors').html($('#ulJsErrors').html()+'
  • '+ErrorText+'
  • '); +} + +function get_proportional_width(Height, EditForm) +{ + var HeightOriginal = parseInt($("#heightlastbeforeresize").val()); + var WidthOriginal = parseInt($("#widthlastbeforeresize").val()); + + return Math.round((WidthOriginal/HeightOriginal)*Height); +} + +function get_proportional_height(Width, EditForm) +{ + var HeightOriginal = parseInt($("#heightlastbeforeresize").val()); + var WidthOriginal = parseInt($("#widthlastbeforeresize").val()); + + return Math.round((HeightOriginal/WidthOriginal)*Width); +} + +function remove_px(Value) +{ + return Value.replace("px",""); +} + +function activate_form() +{ + $('#width').removeAttr('disabled'); + $('#height').removeAttr('disabled'); + $('#keepproportions').removeAttr('disabled'); + $('#btnRotateLeft').removeAttr('disabled'); + $('#btnRotateRight').removeAttr('disabled'); + $('#croptop').removeAttr('disabled'); + $('#cropbottom').removeAttr('disabled'); + $('#cropleft').removeAttr('disabled'); + $('#cropright').removeAttr('disabled'); + $('#grayscale').removeAttr('disabled'); + $('#btnupdate').removeAttr('disabled'); + $('#btnsave').removeAttr('disabled'); + $('#btnundo').removeAttr('disabled'); + $('#brightness_slider_track').slider('enable'); + $('#contrast_slider_track').slider('enable'); + + if ($('#actions').val() == '') + { + $('#btnundo').attr('disabled','disabled'); + $('#btnsave').attr('disabled','disabled'); + } + else + { + $('#btnundo').removeAttr('disabled'); + $('#btnsave').removeAttr('disabled'); + } +} + + +function set_crop_values(c) +{ + if (isinteger($("#height").val()) && isinteger($("#width").val())) + { + $("#croptop").val(c.y); + $("#cropbottom").val(parseInt($("#height").val()) - (c.y + c.h)); + $("#cropleft").val(c.x); + $("#cropright").val(parseInt($("#width").val()) - (c.x + c.w)); + $("#cropwidth").html(c.w); + $("#cropheight").html(c.h); + } +} + +function phpimageeditor_resize_activator(selectedIndex) +{ + if (selectedIndex == MenuResize) + { + if ($('#keepproportionsval').val() == "1") + { + $("#imageResizerKeepProportions").css("display", "block"); + $("#imageResizerNoProportions").css("display", "none"); + } + else + { + $("#imageResizerKeepProportions").css("display", "none"); + $("#imageResizerNoProportions").css("display", "block"); + } + } + else + { + $("#imageResizerKeepProportions").css("display", "none"); + $("#imageResizerNoProportions").css("display", "none"); + } +} + +function phpimageeditor_panelfade(selectedIndex) +{ + for (i = 0; i < 4; i++) + { + if ($('#panel_'+i) != null) + { + $("#panel_"+i).css('opacity','0.0'); + + if (i == selectedIndex) + { + $("#menuitem_"+i).removeClass("not-selected"); + $("#menuitem_"+i).addClass("selected"); + $("#panel_"+i).css('display','block'); + $("#panel_"+i).fadeTo("normal", 1.0); + } + else + { + $("#menuitem_"+i).removeClass("selected"); + $("#menuitem_"+i).addClass("not-selected"); + $("#panel_"+i).css('display','none'); + } + } + } + + if (selectedIndex != MenuCrop) + { + $("#cropleft").val("0"); + $("#cropright").val("0"); + $("#croptop").val("0"); + $("#cropbottom").val("0"); + $("#cropwidth").html("0"); + $("#cropheight").html("0"); + } + + phpimageeditor_resize_activator(selectedIndex); + phpimageeditor_crop_activator(selectedIndex); + + $("#panel").val(selectedIndex); +} + +function phpimageeditor_crop_activator(selectedIndex) +{ + if (objCrop != null) + { + if (selectedIndex != MenuCrop) + { + objCrop.release(); + objCrop.disable(); + $(".jcrop-holder").css("display", "none"); + $("#image").css("display", "block"); + } + else + { + objCrop.release(); + objCrop.enable(); + $(".jcrop-holder").css("display", "block"); + $("#image").css("display", "block"); + } + } +} + +function phpimageeditor_init() +{ + objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("input#cropkeepproportionsratio").val() : 0}); + + $("#imageResizerKeepProportions").resizable( + { + aspectRatio: parseFloat($("input#widthlastbeforeresize").val()) / parseFloat($("input#heightlastbeforeresize").val()), + stop: function(event,ui) + { + var resize_width = parseInt(remove_px($("#imageResizerKeepProportions").css("width"))); + var resize_height = parseInt(remove_px($("#imageResizerKeepProportions").css("height"))); + + $("#image").css("width", resize_width+"px"); + $("#image").css("height", resize_height+"px"); + $("#width").val(resize_width); + $("#height").val(resize_height); + + update_mouse_resizer(); + + $("#imageResizerKeepProportions").css("opacity", "0.0"); + + reload_mouse_crop(); + }, + start: function(event,ui) + { + $("#imageResizerKeepProportions").css("opacity", "0.5"); + } + }); + + $("#imageResizerNoProportions").resizable( + { + aspectRatio: false, + stop: function(event,ui) + { + var resize_width = parseInt(remove_px($("#imageResizerNoProportions").css("width"))); + var resize_height = parseInt(remove_px($("#imageResizerNoProportions").css("height"))); + + $("#image").css("width", resize_width+"px"); + $("#image").css("height", resize_height+"px"); + $("#width").val(resize_width); + $("#height").val(resize_height); + + update_mouse_resizer(); + + $("#widthlastbeforeresize").val(resize_width); + $("#heightlastbeforeresize").val(resize_height); + $("#imageResizerKeepProportions").resizable('option','aspectRatio',parseFloat($('#widthlastbeforeresize').val())/parseFloat($('#heightlastbeforeresize').val())); + + $("#imageResizerNoProportions").css("opacity", "0.0"); + + reload_mouse_crop(); + }, + start: function(event,ui) + { + $("#imageResizerNoProportions").css("opacity", "0.5"); + } + }); + + $("#contrast_slider_track").slider({value: parseInt($("#contrast").val()) + ContrastMax, min: 1, max: ((ContrastMax*2)+1), step: 1, + stop: function(event,ui) + { + if (validate_form()) + ajax_post(); + }, + slide: function(event, ui) + { + $("#contrast").val(parseInt(ui.value)-((ContrastMax)+1)); + } + }); + + $("#brightness_slider_track").slider({value: (parseInt($("input#brightness").val())+BrightnessMax),min: 1,max: ((BrightnessMax*2)+1),step: 1, + stop: function(event,ui) + { + if (validate_form()) + ajax_post(); + }, + slide: function(event, ui) + { + $("#brightness").val(parseInt(ui.value)-(BrightnessMax+1)); + } + }); + + $("#grayscale").click(function() + { + if (validate_form()) + { + $("#grayscale").attr('checked') ? $('#grayscaleval').val('1') : $('#grayscaleval').val('0'); + ajax_post(); + } + }); + + $("#btnupdate").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionUpdate); + ajax_post(); + } + }); + + $("#btnundo").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionUndo); + ajax_post(); + } + }); + + $("#btnsave").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionSaveAndClose); + ajax_post(); + } + }); + + $("#btnRotateLeft").click(function() + { + if (validate_form()) + { + $("#rotate").val(ActionRotateLeft); + ajax_post(); + } + }); + + $("#btnRotateRight").click(function() + { + if (validate_form()) + { + $("#rotate").val(ActionRotateRight); + ajax_post(); + } + }); + + $("form#" + FormId).submit(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionSaveAndClose); + return true; + } + return false; + }); + + $("#width").keydown(function(event) + { + focus_on_enter($("input#btnupdate"), event); + }); + + $("#width").keyup(function() + { + update_width($(this),$("form#" + FormId)); + }); + + $("#height").keydown(function(event) + { + focus_on_enter($("input#btnupdate"), event); + }); + + $("#height").keyup(function() + { + update_height($(this),$("form#" + FormId)); + }); + + $("#keepproportions").click(function() + { + if ($(this).attr('checked')) + { + $('#keepproportionsval').val('1'); + $('#imageResizerKeepProportions').css('display','block'); + $('#imageResizerNoProportions').css('display','none'); + } + else + { + $('#keepproportionsval').val('0'); + $('#imageResizerKeepProportions').css('display','none'); + $('#imageResizerNoProportions').css('display','block'); + } + }); + + + $("#cropkeepproportions").click(function() + { + if ($(this).attr('checked')) + { + $('#cropkeepproportionsval').val('1'); + } + else + { + $('#cropkeepproportionsval').val('0'); + } + }); + + $("#menuitem_" + MenuResize).click(function() + { + if ($('#panel').val() != MenuResize) + { + phpimageeditor_panelfade(MenuResize); + } + }); + + $("#menuitem_" + MenuRotate).click(function() + { + if ($('#panel').val() != MenuRotate) + { + phpimageeditor_panelfade(MenuRotate); + } + }); + + $("#menuitem_" + MenuCrop).click(function() + { + if ($('#panel').val() != MenuCrop) + { + phpimageeditor_panelfade(MenuCrop); + } + }); + + if ($("#menuitem_" + MenuEffects) != null) + { + $("#menuitem_" + MenuEffects).click(function() + { + if ($('#panel').val() != MenuEffects) + { + phpimageeditor_panelfade(MenuEffects); + } + }); + } + + $('#cropkeepproportions').change(function(e) + { + if (objCrop != null) + { + if (this.checked && parseFloat($("#cropwidth").html()) != 0 && parseFloat($("#cropheight").html()) != 0) + { + var aspectRatio = parseFloat($("#cropwidth").html()) / parseFloat($("#cropheight").html()); + objCrop.setOptions({ aspectRatio: aspectRatio }); + $("#cropkeepproportionsratio").val(aspectRatio); + } + else if (this.checked && parseFloat($("#cropwidth").html()) == 0 && parseFloat($("#cropheight").html()) == 0) + { + objCrop.setOptions({ aspectRatio: $("#cropkeepproportionsratio").val() }); + } + else + { + objCrop.setOptions({ aspectRatio: 0 }); + } + } + }); + + $("input#width").numeric(); + $("input#height").numeric(); + + var selectedIndex = parseInt($('#panel').val()); + for (i = 0; i < 4; i++) + { + if ($('#panel_'+i) != null) + { + if (i == selectedIndex) + { + $("#panel_"+i).css('opacity','1.0'); + $("#panel_"+i).css('display','block'); + } + else + { + $("#panel_"+i).css('opacity','0.0'); + $("#panel_"+i).css('display','none'); + } + } + } + + phpimageeditor_crop_activator(selectedIndex); + phpimageeditor_resize_activator(selectedIndex); +} + +$(document).ready(function() +{ + phpimageeditor_init(); +});define('CKIMAGE_ORIGINAL', TOOLBOX_ORIGINAL); +define('CKIMAGE_RESIZED', TOOLBOX_RESIZED); +define('CKIMAGE_MIDSIZED', TOOLBOX_MIDSIZED); +define('CKIMAGE_THUMB', TOOLBOX_THUMB); \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/ui.core.js b/Toolkit/PHPImageEditor/javascript/ui.core.js new file mode 100644 index 0000000..89300d9 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.core.js @@ -0,0 +1,519 @@ +/* + * jQuery UI 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI + */ +;jQuery.ui || (function($) { + +var _remove = $.fn.remove, + isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); + +//Helper functions and ui object +$.ui = { + version: "1.7", + + // $.ui.plugin is deprecated. Use the proxy pattern instead. + plugin: { + add: function(module, option, set) { + var proto = $.ui[module].prototype; + for(var i in set) { + proto.plugins[i] = proto.plugins[i] || []; + proto.plugins[i].push([option, set[i]]); + } + }, + call: function(instance, name, args) { + var set = instance.plugins[name]; + if(!set || !instance.element[0].parentNode) { return; } + + for (var i = 0; i < set.length; i++) { + if (instance.options[set[i][0]]) { + set[i][1].apply(instance.element, args); + } + } + } + }, + + contains: function(a, b) { + return document.compareDocumentPosition + ? a.compareDocumentPosition(b) & 16 + : a !== b && a.contains(b); + }, + + hasScroll: function(el, a) { + + //If overflow is hidden, the element might have extra content, but the user wants to hide it + if ($(el).css('overflow') == 'hidden') { return false; } + + var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', + has = false; + + if (el[scroll] > 0) { return true; } + + // TODO: determine which cases actually cause this to happen + // if the element doesn't have the scroll set, see if it's possible to + // set the scroll + el[scroll] = 1; + has = (el[scroll] > 0); + el[scroll] = 0; + return has; + }, + + isOverAxis: function(x, reference, size) { + //Determines when x coordinate is over "b" element axis + return (x > reference) && (x < (reference + size)); + }, + + isOver: function(y, x, top, left, height, width) { + //Determines when x, y coordinates is over "b" element + return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); + }, + + keyCode: { + BACKSPACE: 8, + CAPS_LOCK: 20, + COMMA: 188, + CONTROL: 17, + DELETE: 46, + DOWN: 40, + END: 35, + ENTER: 13, + ESCAPE: 27, + HOME: 36, + INSERT: 45, + LEFT: 37, + NUMPAD_ADD: 107, + NUMPAD_DECIMAL: 110, + NUMPAD_DIVIDE: 111, + NUMPAD_ENTER: 108, + NUMPAD_MULTIPLY: 106, + NUMPAD_SUBTRACT: 109, + PAGE_DOWN: 34, + PAGE_UP: 33, + PERIOD: 190, + RIGHT: 39, + SHIFT: 16, + SPACE: 32, + TAB: 9, + UP: 38 + } +}; + +// WAI-ARIA normalization +if (isFF2) { + var attr = $.attr, + removeAttr = $.fn.removeAttr, + ariaNS = "http://www.w3.org/2005/07/aaa", + ariaState = /^aria-/, + ariaRole = /^wairole:/; + + $.attr = function(elem, name, value) { + var set = value !== undefined; + + return (name == 'role' + ? (set + ? attr.call(this, elem, name, "wairole:" + value) + : (attr.apply(this, arguments) || "").replace(ariaRole, "")) + : (ariaState.test(name) + ? (set + ? elem.setAttributeNS(ariaNS, + name.replace(ariaState, "aaa:"), value) + : attr.call(this, elem, name.replace(ariaState, "aaa:"))) + : attr.apply(this, arguments))); + }; + + $.fn.removeAttr = function(name) { + return (ariaState.test(name) + ? this.each(function() { + this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); + }) : removeAttr.call(this, name)); + }; +} + +//jQuery plugins +$.fn.extend({ + remove: function() { + // Safari has a native remove event which actually removes DOM elements, + // so we have to use triggerHandler instead of trigger (#3037). + $("*", this).add(this).each(function() { + $(this).triggerHandler("remove"); + }); + return _remove.apply(this, arguments ); + }, + + enableSelection: function() { + return this + .attr('unselectable', 'off') + .css('MozUserSelect', '') + .unbind('selectstart.ui'); + }, + + disableSelection: function() { + return this + .attr('unselectable', 'on') + .css('MozUserSelect', 'none') + .bind('selectstart.ui', function() { return false; }); + }, + + scrollParent: function() { + var scrollParent; + if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { + scrollParent = this.parents().filter(function() { + return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } else { + scrollParent = this.parents().filter(function() { + return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } + + return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; + } +}); + + +//Additional selectors +$.extend($.expr[':'], { + data: function(elem, i, match) { + return !!$.data(elem, match[3]); + }, + + focusable: function(element) { + var nodeName = element.nodeName.toLowerCase(), + tabIndex = $.attr(element, 'tabindex'); + return (/input|select|textarea|button|object/.test(nodeName) + ? !element.disabled + : 'a' == nodeName || 'area' == nodeName + ? element.href || !isNaN(tabIndex) + : !isNaN(tabIndex)) + // the element and all of its ancestors must be visible + // the browser may report that the area is hidden + && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; + }, + + tabbable: function(element) { + var tabIndex = $.attr(element, 'tabindex'); + return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); + } +}); + + +// $.widget is a factory to create jQuery plugins +// taking some boilerplate code out of the plugin code +function getter(namespace, plugin, method, args) { + function getMethods(type) { + var methods = $[namespace][plugin][type] || []; + return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); + } + + var methods = getMethods('getter'); + if (args.length == 1 && typeof args[0] == 'string') { + methods = methods.concat(getMethods('getterSetter')); + } + return ($.inArray(method, methods) != -1); +} + +$.widget = function(name, prototype) { + var namespace = name.split(".")[0]; + name = name.split(".")[1]; + + // create plugin method + $.fn[name] = function(options) { + var isMethodCall = (typeof options == 'string'), + args = Array.prototype.slice.call(arguments, 1); + + // prevent calls to internal methods + if (isMethodCall && options.substring(0, 1) == '_') { + return this; + } + + // handle getter methods + if (isMethodCall && getter(namespace, name, options, args)) { + var instance = $.data(this[0], name); + return (instance ? instance[options].apply(instance, args) + : undefined); + } + + // handle initialization and non-getter methods + return this.each(function() { + var instance = $.data(this, name); + + // constructor + (!instance && !isMethodCall && + $.data(this, name, new $[namespace][name](this, options))._init()); + + // method call + (instance && isMethodCall && $.isFunction(instance[options]) && + instance[options].apply(instance, args)); + }); + }; + + // create widget constructor + $[namespace] = $[namespace] || {}; + $[namespace][name] = function(element, options) { + var self = this; + + this.namespace = namespace; + this.widgetName = name; + this.widgetEventPrefix = $[namespace][name].eventPrefix || name; + this.widgetBaseClass = namespace + '-' + name; + + this.options = $.extend({}, + $.widget.defaults, + $[namespace][name].defaults, + $.metadata && $.metadata.get(element)[name], + options); + + this.element = $(element) + .bind('setData.' + name, function(event, key, value) { + if (event.target == element) { + return self._setData(key, value); + } + }) + .bind('getData.' + name, function(event, key) { + if (event.target == element) { + return self._getData(key); + } + }) + .bind('remove', function() { + return self.destroy(); + }); + }; + + // add widget prototype + $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); + + // TODO: merge getter and getterSetter properties from widget prototype + // and plugin prototype + $[namespace][name].getterSetter = 'option'; +}; + +$.widget.prototype = { + _init: function() {}, + destroy: function() { + this.element.removeData(this.widgetName) + .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') + .removeAttr('aria-disabled'); + }, + + option: function(key, value) { + var options = key, + self = this; + + if (typeof key == "string") { + if (value === undefined) { + return this._getData(key); + } + options = {}; + options[key] = value; + } + + $.each(options, function(key, value) { + self._setData(key, value); + }); + }, + _getData: function(key) { + return this.options[key]; + }, + _setData: function(key, value) { + this.options[key] = value; + + if (key == 'disabled') { + this.element + [value ? 'addClass' : 'removeClass']( + this.widgetBaseClass + '-disabled' + ' ' + + this.namespace + '-state-disabled') + .attr("aria-disabled", value); + } + }, + + enable: function() { + this._setData('disabled', false); + }, + disable: function() { + this._setData('disabled', true); + }, + + _trigger: function(type, event, data) { + var callback = this.options[type], + eventName = (type == this.widgetEventPrefix + ? type : this.widgetEventPrefix + type); + + event = $.Event(event); + event.type = eventName; + + // copy original event properties over to the new event + // this would happen if we could call $.event.fix instead of $.Event + // but we don't have a way to force an event to be fixed multiple times + if (event.originalEvent) { + for (var i = $.event.props.length, prop; i;) { + prop = $.event.props[--i]; + event[prop] = event.originalEvent[prop]; + } + } + + this.element.trigger(event, data); + + return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false + || event.isDefaultPrevented()); + } +}; + +$.widget.defaults = { + disabled: false +}; + + +/** Mouse Interaction Plugin **/ + +$.ui.mouse = { + _mouseInit: function() { + var self = this; + + this.element + .bind('mousedown.'+this.widgetName, function(event) { + return self._mouseDown(event); + }) + .bind('click.'+this.widgetName, function(event) { + if(self._preventClickEvent) { + self._preventClickEvent = false; + event.stopImmediatePropagation(); + return false; + } + }); + + // Prevent text selection in IE + if ($.browser.msie) { + this._mouseUnselectable = this.element.attr('unselectable'); + this.element.attr('unselectable', 'on'); + } + + this.started = false; + }, + + // TODO: make sure destroying one instance of mouse doesn't mess with + // other instances of mouse + _mouseDestroy: function() { + this.element.unbind('.'+this.widgetName); + + // Restore text selection in IE + ($.browser.msie + && this.element.attr('unselectable', this._mouseUnselectable)); + }, + + _mouseDown: function(event) { + // don't let more than one widget handle mouseStart + // TODO: figure out why we have to use originalEvent + event.originalEvent = event.originalEvent || {}; + if (event.originalEvent.mouseHandled) { return; } + + // we may have missed mouseup (out of window) + (this._mouseStarted && this._mouseUp(event)); + + this._mouseDownEvent = event; + + var self = this, + btnIsLeft = (event.which == 1), + elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); + if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { + return true; + } + + this.mouseDelayMet = !this.options.delay; + if (!this.mouseDelayMet) { + this._mouseDelayTimer = setTimeout(function() { + self.mouseDelayMet = true; + }, this.options.delay); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = (this._mouseStart(event) !== false); + if (!this._mouseStarted) { + event.preventDefault(); + return true; + } + } + + // these delegates are required to keep context + this._mouseMoveDelegate = function(event) { + return self._mouseMove(event); + }; + this._mouseUpDelegate = function(event) { + return self._mouseUp(event); + }; + $(document) + .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + // preventDefault() is used to prevent the selection of text here - + // however, in Safari, this causes select boxes not to be selectable + // anymore, so this fix is needed + ($.browser.safari || event.preventDefault()); + + event.originalEvent.mouseHandled = true; + return true; + }, + + _mouseMove: function(event) { + // IE mouseup check - mouseup happened when mouse was out of window + if ($.browser.msie && !event.button) { + return this._mouseUp(event); + } + + if (this._mouseStarted) { + this._mouseDrag(event); + return event.preventDefault(); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = + (this._mouseStart(this._mouseDownEvent, event) !== false); + (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); + } + + return !this._mouseStarted; + }, + + _mouseUp: function(event) { + $(document) + .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + if (this._mouseStarted) { + this._mouseStarted = false; + this._preventClickEvent = (event.target == this._mouseDownEvent.target); + this._mouseStop(event); + } + + return false; + }, + + _mouseDistanceMet: function(event) { + return (Math.max( + Math.abs(this._mouseDownEvent.pageX - event.pageX), + Math.abs(this._mouseDownEvent.pageY - event.pageY) + ) >= this.options.distance + ); + }, + + _mouseDelayMet: function(event) { + return this.mouseDelayMet; + }, + + // These are placeholder methods, to be overriden by extending plugin + _mouseStart: function(event) {}, + _mouseDrag: function(event) {}, + _mouseStop: function(event) {}, + _mouseCapture: function(event) { return true; } +}; + +$.ui.mouse.defaults = { + cancel: null, + distance: 1, + delay: 0 +}; + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/ui.resizable.js b/Toolkit/PHPImageEditor/javascript/ui.resizable.js new file mode 100644 index 0000000..0e4b894 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.resizable.js @@ -0,0 +1,800 @@ +/* + * jQuery UI Resizable 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Resizables + * + * Depends: + * ui.core.js + */ +(function($) { + +$.widget("ui.resizable", $.extend({}, $.ui.mouse, { + + _init: function() { + + var self = this, o = this.options; + this.element.addClass("ui-resizable"); + + $.extend(this, { + _aspectRatio: !!(o.aspectRatio), + aspectRatio: o.aspectRatio, + originalElement: this.element, + _proportionallyResizeElements: [], + _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null + }); + + //Wrap the element if it cannot hold child nodes + if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { + + //Opera fix for relative positioning + if (/relative/.test(this.element.css('position')) && $.browser.opera) + this.element.css({ position: 'relative', top: 'auto', left: 'auto' }); + + //Create a wrapper element and set the wrapper to the new current internal element + this.element.wrap( + $('
    ').css({ + position: this.element.css('position'), + width: this.element.outerWidth(), + height: this.element.outerHeight(), + top: this.element.css('top'), + left: this.element.css('left') + }) + ); + + //Overwrite the original this.element + this.element = this.element.parent().data( + "resizable", this.element.data('resizable') + ); + + this.elementIsWrapper = true; + + //Move margins to the wrapper + this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); + this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); + + //Prevent Safari textarea resize + this.originalResizeStyle = this.originalElement.css('resize'); + this.originalElement.css('resize', 'none'); + + //Push the actual element to our proportionallyResize internal array + this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); + + // avoid IE jump (hard set the margin) + this.originalElement.css({ margin: this.originalElement.css('margin') }); + + // fix handlers offset + this._proportionallyResize(); + + } + + this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' }); + if(this.handles.constructor == String) { + + if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw'; + var n = this.handles.split(","); this.handles = {}; + + for(var i = 0; i < n.length; i++) { + + var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; + var axis = $('
    '); + + // increase zIndex of sw, se, ne, nw axis + //TODO : this modifies original option + if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex }); + + //TODO : What's going on here? + if ('se' == handle) { + axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se'); + }; + + //Insert into internal handles object and append to element + this.handles[handle] = '.ui-resizable-'+handle; + this.element.append(axis); + } + + } + + this._renderAxis = function(target) { + + target = target || this.element; + + for(var i in this.handles) { + + if(this.handles[i].constructor == String) + this.handles[i] = $(this.handles[i], this.element).show(); + + //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) + if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { + + var axis = $(this.handles[i], this.element), padWrapper = 0; + + //Checking the correct pad and border + padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); + + //The padding type i have to apply... + var padPos = [ 'padding', + /ne|nw|n/.test(i) ? 'Top' : + /se|sw|s/.test(i) ? 'Bottom' : + /^e$/.test(i) ? 'Right' : 'Left' ].join(""); + + target.css(padPos, padWrapper); + + this._proportionallyResize(); + + } + + //TODO: What's that good for? There's not anything to be executed left + if(!$(this.handles[i]).length) + continue; + + } + }; + + //TODO: make renderAxis a prototype function + this._renderAxis(this.element); + + this._handles = $('.ui-resizable-handle', this.element) + .disableSelection(); + + //Matching axis name + this._handles.mouseover(function() { + if (!self.resizing) { + if (this.className) + var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); + //Axis, default = se + self.axis = axis && axis[1] ? axis[1] : 'se'; + } + }); + + //If we want to auto hide the elements + if (o.autoHide) { + this._handles.hide(); + $(this.element) + .addClass("ui-resizable-autohide") + .hover(function() { + $(this).removeClass("ui-resizable-autohide"); + self._handles.show(); + }, + function(){ + if (!self.resizing) { + $(this).addClass("ui-resizable-autohide"); + self._handles.hide(); + } + }); + } + + //Initialize the mouse interaction + this._mouseInit(); + + }, + + destroy: function() { + + this._mouseDestroy(); + + var _destroy = function(exp) { + $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") + .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); + }; + + //TODO: Unwrap at same DOM position + if (this.elementIsWrapper) { + _destroy(this.element); + var wrapper = this.element; + wrapper.parent().append( + this.originalElement.css({ + position: wrapper.css('position'), + width: wrapper.outerWidth(), + height: wrapper.outerHeight(), + top: wrapper.css('top'), + left: wrapper.css('left') + }) + ).end().remove(); + } + + this.originalElement.css('resize', this.originalResizeStyle); + _destroy(this.originalElement); + + }, + + _mouseCapture: function(event) { + + var handle = false; + for(var i in this.handles) { + if($(this.handles[i])[0] == event.target) handle = true; + } + + return this.options.disabled || !!handle; + + }, + + _mouseStart: function(event) { + + var o = this.options, iniPos = this.element.position(), el = this.element; + + this.resizing = true; + this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; + + // bugfix for http://dev.jquery.com/ticket/1749 + if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { + el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); + } + + //Opera fixing relative position + if ($.browser.opera && (/relative/).test(el.css('position'))) + el.css({ position: 'relative', top: 'auto', left: 'auto' }); + + this._renderProxy(); + + var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top')); + + if (o.containment) { + curleft += $(o.containment).scrollLeft() || 0; + curtop += $(o.containment).scrollTop() || 0; + } + + //Store needed variables + this.offset = this.helper.offset(); + this.position = { left: curleft, top: curtop }; + this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalPosition = { left: curleft, top: curtop }; + this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; + this.originalMousePosition = { left: event.pageX, top: event.pageY }; + + //Aspect Ratio + this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); + + var cursor = $('.ui-resizable-' + this.axis).css('cursor'); + $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor); + + el.addClass("ui-resizable-resizing"); + this._propagate("start", event); + return true; + }, + + _mouseDrag: function(event) { + + //Increase performance, avoid regex + var el = this.helper, o = this.options, props = {}, + self = this, smp = this.originalMousePosition, a = this.axis; + + var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0; + var trigger = this._change[a]; + if (!trigger) return false; + + // Calculate the attrs that will be change + var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff; + + if (this._aspectRatio || event.shiftKey) + data = this._updateRatio(data, event); + + data = this._respectSize(data, event); + + // plugins callbacks need to be called first + this._propagate("resize", event); + + el.css({ + top: this.position.top + "px", left: this.position.left + "px", + width: this.size.width + "px", height: this.size.height + "px" + }); + + if (!this._helper && this._proportionallyResizeElements.length) + this._proportionallyResize(); + + this._updateCache(data); + + // calling the user callback at the end + this._trigger('resize', event, this.ui()); + + return false; + }, + + _mouseStop: function(event) { + + this.resizing = false; + var o = this.options, self = this; + + if(this._helper) { + var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + if (!o.animate) + this.element.css($.extend(s, { top: top, left: left })); + + self.helper.height(self.size.height); + self.helper.width(self.size.width); + + if (this._helper && !o.animate) this._proportionallyResize(); + } + + $('body').css('cursor', 'auto'); + + this.element.removeClass("ui-resizable-resizing"); + + this._propagate("stop", event); + + if (this._helper) this.helper.remove(); + return false; + + }, + + _updateCache: function(data) { + var o = this.options; + this.offset = this.helper.offset(); + if (isNumber(data.left)) this.position.left = data.left; + if (isNumber(data.top)) this.position.top = data.top; + if (isNumber(data.height)) this.size.height = data.height; + if (isNumber(data.width)) this.size.width = data.width; + }, + + _updateRatio: function(data, event) { + + var o = this.options, cpos = this.position, csize = this.size, a = this.axis; + + if (data.height) data.width = (csize.height * this.aspectRatio); + else if (data.width) data.height = (csize.width / this.aspectRatio); + + if (a == 'sw') { + data.left = cpos.left + (csize.width - data.width); + data.top = null; + } + if (a == 'nw') { + data.top = cpos.top + (csize.height - data.height); + data.left = cpos.left + (csize.width - data.width); + } + + return data; + }, + + _respectSize: function(data, event) { + + var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis, + ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), + isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height); + + if (isminw) data.width = o.minWidth; + if (isminh) data.height = o.minHeight; + if (ismaxw) data.width = o.maxWidth; + if (ismaxh) data.height = o.maxHeight; + + var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; + var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); + + if (isminw && cw) data.left = dw - o.minWidth; + if (ismaxw && cw) data.left = dw - o.maxWidth; + if (isminh && ch) data.top = dh - o.minHeight; + if (ismaxh && ch) data.top = dh - o.maxHeight; + + // fixing jump error on top/left - bug #2330 + var isNotwh = !data.width && !data.height; + if (isNotwh && !data.left && data.top) data.top = null; + else if (isNotwh && !data.top && data.left) data.left = null; + + return data; + }, + + _proportionallyResize: function() { + + var o = this.options; + if (!this._proportionallyResizeElements.length) return; + var element = this.helper || this.element; + + for (var i=0; i < this._proportionallyResizeElements.length; i++) { + + var prel = this._proportionallyResizeElements[i]; + + if (!this.borderDif) { + var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], + p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; + + this.borderDif = $.map(b, function(v, i) { + var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; + return border + padding; + }); + } + + if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length))) + continue; + + prel.css({ + height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, + width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 + }); + + }; + + }, + + _renderProxy: function() { + + var el = this.element, o = this.options; + this.elementOffset = el.offset(); + + if(this._helper) { + + this.helper = this.helper || $('
    '); + + // fix ie6 offset TODO: This seems broken + var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0), + pxyoffset = ( ie6 ? 2 : -1 ); + + this.helper.addClass(this._helper).css({ + width: this.element.outerWidth() + pxyoffset, + height: this.element.outerHeight() + pxyoffset, + position: 'absolute', + left: this.elementOffset.left - ie6offset +'px', + top: this.elementOffset.top - ie6offset +'px', + zIndex: ++o.zIndex //TODO: Don't modify option + }); + + this.helper + .appendTo("body") + .disableSelection(); + + } else { + this.helper = this.element; + } + + }, + + _change: { + e: function(event, dx, dy) { + return { width: this.originalSize.width + dx }; + }, + w: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { left: sp.left + dx, width: cs.width - dx }; + }, + n: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { top: sp.top + dy, height: cs.height - dy }; + }, + s: function(event, dx, dy) { + return { height: this.originalSize.height + dy }; + }, + se: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + sw: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + }, + ne: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + nw: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + } + }, + + _propagate: function(n, event) { + $.ui.plugin.call(this, n, [event, this.ui()]); + (n != "resize" && this._trigger(n, event, this.ui())); + }, + + plugins: {}, + + ui: function() { + return { + originalElement: this.originalElement, + element: this.element, + helper: this.helper, + position: this.position, + size: this.size, + originalSize: this.originalSize, + originalPosition: this.originalPosition + }; + } + +})); + +$.extend($.ui.resizable, { + version: "1.7", + eventPrefix: "resize", + defaults: { + alsoResize: false, + animate: false, + animateDuration: "slow", + animateEasing: "swing", + aspectRatio: false, + autoHide: false, + cancel: ":input,option", + containment: false, + delay: 0, + distance: 1, + ghost: false, + grid: false, + handles: "e,s,se", + helper: false, + maxHeight: null, + maxWidth: null, + minHeight: 10, + minWidth: 10, + zIndex: 1000 + } +}); + +/* + * Resizable Extensions + */ + +$.ui.plugin.add("resizable", "alsoResize", { + + start: function(event, ui) { + + var self = $(this).data("resizable"), o = self.options; + + _store = function(exp) { + $(exp).each(function() { + $(this).data("resizable-alsoresize", { + width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10), + left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10) + }); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) { + if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } + else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); } + }else{ + _store(o.alsoResize); + } + }, + + resize: function(event, ui){ + var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition; + + var delta = { + height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0, + top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0 + }, + + _alsoResize = function(exp, c) { + $(exp).each(function() { + var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left']; + + $.each(css || ['width', 'height', 'top', 'left'], function(i, prop) { + var sum = (start[prop]||0) + (delta[prop]||0); + if (sum && sum >= 0) + style[prop] = sum || null; + }); + + //Opera fixing relative position + if (/relative/.test(el.css('position')) && $.browser.opera) { + self._revertToRelativePosition = true; + el.css({ position: 'absolute', top: 'auto', left: 'auto' }); + } + + el.css(style); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { + $.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); }); + }else{ + _alsoResize(o.alsoResize); + } + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"); + + //Opera fixing relative position + if (self._revertToRelativePosition && $.browser.opera) { + self._revertToRelativePosition = false; + el.css({ position: 'relative' }); + } + + $(this).removeData("resizable-alsoresize-start"); + } +}); + +$.ui.plugin.add("resizable", "animate", { + + stop: function(event, ui) { + var self = $(this).data("resizable"), o = self.options; + + var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + self.element.animate( + $.extend(style, top && left ? { top: top, left: left } : {}), { + duration: o.animateDuration, + easing: o.animateEasing, + step: function() { + + var data = { + width: parseInt(self.element.css('width'), 10), + height: parseInt(self.element.css('height'), 10), + top: parseInt(self.element.css('top'), 10), + left: parseInt(self.element.css('left'), 10) + }; + + if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height }); + + // propagating resize, and updating values for each animation step + self._updateCache(data); + self._propagate("resize", event); + + } + } + ); + } + +}); + +$.ui.plugin.add("resizable", "containment", { + + start: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, el = self.element; + var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; + if (!ce) return; + + self.containerElement = $(ce); + + if (/document/.test(oc) || oc == document) { + self.containerOffset = { left: 0, top: 0 }; + self.containerPosition = { left: 0, top: 0 }; + + self.parentData = { + element: $(document), left: 0, top: 0, + width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight + }; + } + + // i'm a node, so compute top, left, right, bottom + else { + var element = $(ce), p = []; + $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); + + self.containerOffset = element.offset(); + self.containerPosition = element.position(); + self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; + + var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width, + width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); + + self.parentData = { + element: ce, left: co.left, top: co.top, width: width, height: height + }; + } + }, + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, + ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position, + pRatio = o._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement; + + if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co; + + if (cp.left < (self._helper ? co.left : 0)) { + self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left)); + if (pRatio) self.size.height = self.size.width / o.aspectRatio; + self.position.left = o.helper ? co.left : 0; + } + + if (cp.top < (self._helper ? co.top : 0)) { + self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top); + if (pRatio) self.size.width = self.size.height * o.aspectRatio; + self.position.top = self._helper ? co.top : 0; + } + + self.offset.left = self.parentData.left+self.position.left; + self.offset.top = self.parentData.top+self.position.top; + + var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ), + hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height ); + + var isParent = self.containerElement.get(0) == self.element.parent().get(0), + isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position')); + + if(isParent && isOffsetRelative) woset -= self.parentData.left; + + if (woset + self.size.width >= self.parentData.width) { + self.size.width = self.parentData.width - woset; + if (pRatio) self.size.height = self.size.width / o.aspectRatio; + } + + if (hoset + self.size.height >= self.parentData.height) { + self.size.height = self.parentData.height - hoset; + if (pRatio) self.size.width = self.size.height * o.aspectRatio; + } + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options, cp = self.position, + co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement; + + var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height; + + if (self._helper && !o.animate && (/relative/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + if (self._helper && !o.animate && (/static/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + } +}); + +$.ui.plugin.add("resizable", "ghost", { + + start: function(event, ui) { + + var self = $(this).data("resizable"), o = self.options, cs = self.size; + + self.ghost = self.originalElement.clone(); + self.ghost + .css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) + .addClass('ui-resizable-ghost') + .addClass(typeof o.ghost == 'string' ? o.ghost : ''); + + self.ghost.appendTo(self.helper); + + }, + + resize: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width }); + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0)); + } + +}); + +$.ui.plugin.add("resizable", "grid", { + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey; + o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; + var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); + + if (/^(se|s|e)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + } + else if (/^(ne)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + } + else if (/^(sw)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.left = op.left - ox; + } + else { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + self.position.left = op.left - ox; + } + } + +}); + +var num = function(v) { + return parseInt(v, 10) || 0; +}; + +var isNumber = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/ui.slider.js b/Toolkit/PHPImageEditor/javascript/ui.slider.js new file mode 100644 index 0000000..a7b4d0c --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.slider.js @@ -0,0 +1,511 @@ +/* + * jQuery UI Slider 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Slider + * + * Depends: + * ui.core.js + */ + +(function($) { + +$.widget("ui.slider", $.extend({}, $.ui.mouse, { + + _init: function() { + + var self = this, o = this.options; + this._keySliding = false; + this._handleIndex = null; + this._detectOrientation(); + this._mouseInit(); + + this.element + .addClass("ui-slider" + + " ui-slider-" + this.orientation + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all"); + + this.range = $([]); + + if (o.range) { + + if (o.range === true) { + this.range = $('
    '); + if (!o.values) o.values = [this._valueMin(), this._valueMin()]; + if (o.values.length && o.values.length != 2) { + o.values = [o.values[0], o.values[0]]; + } + } else { + this.range = $('
    '); + } + + this.range + .appendTo(this.element) + .addClass("ui-slider-range"); + + if (o.range == "min" || o.range == "max") { + this.range.addClass("ui-slider-range-" + o.range); + } + + // note: this isn't the most fittingly semantic framework class for this element, + // but worked best visually with a variety of themes + this.range.addClass("ui-widget-header"); + + } + + if ($(".ui-slider-handle", this.element).length == 0) + $('') + .appendTo(this.element) + .addClass("ui-slider-handle"); + + if (o.values && o.values.length) { + while ($(".ui-slider-handle", this.element).length < o.values.length) + $('') + .appendTo(this.element) + .addClass("ui-slider-handle"); + } + + this.handles = $(".ui-slider-handle", this.element) + .addClass("ui-state-default" + + " ui-corner-all"); + + this.handle = this.handles.eq(0); + + this.handles.add(this.range).filter("a") + .click(function(event) { event.preventDefault(); }) + .hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); }) + .focus(function() { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); }) + .blur(function() { $(this).removeClass('ui-state-focus'); }); + + this.handles.each(function(i) { + $(this).data("index.ui-slider-handle", i); + }); + + this.handles.keydown(function(event) { + + var ret = true; + + var index = $(this).data("index.ui-slider-handle"); + + if (self.options.disabled) + return; + + switch (event.keyCode) { + case $.ui.keyCode.HOME: + case $.ui.keyCode.END: + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + ret = false; + if (!self._keySliding) { + self._keySliding = true; + $(this).addClass("ui-state-active"); + self._start(event, index); + } + break; + } + + var curVal, newVal, step = self._step(); + if (self.options.values && self.options.values.length) { + curVal = newVal = self.values(index); + } else { + curVal = newVal = self.value(); + } + + switch (event.keyCode) { + case $.ui.keyCode.HOME: + newVal = self._valueMin(); + break; + case $.ui.keyCode.END: + newVal = self._valueMax(); + break; + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + if(curVal == self._valueMax()) return; + newVal = curVal + step; + break; + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + if(curVal == self._valueMin()) return; + newVal = curVal - step; + break; + } + + self._slide(event, index, newVal); + + return ret; + + }).keyup(function(event) { + + var index = $(this).data("index.ui-slider-handle"); + + if (self._keySliding) { + self._stop(event, index); + self._change(event, index); + self._keySliding = false; + $(this).removeClass("ui-state-active"); + } + + }); + + this._refreshValue(); + + }, + + destroy: function() { + + this.handles.remove(); + + this.element + .removeClass("ui-slider" + + " ui-slider-horizontal" + + " ui-slider-vertical" + + " ui-slider-disabled" + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all") + .removeData("slider") + .unbind(".slider"); + + this._mouseDestroy(); + + }, + + _mouseCapture: function(event) { + + var o = this.options; + + if (o.disabled) + return false; + + this.elementSize = { + width: this.element.outerWidth(), + height: this.element.outerHeight() + }; + this.elementOffset = this.element.offset(); + + var position = { x: event.pageX, y: event.pageY }; + var normValue = this._normValueFromMouse(position); + + var distance = this._valueMax() + 1, closestHandle; + var self = this, index; + this.handles.each(function(i) { + var thisDistance = Math.abs(normValue - self.values(i)); + if (distance > thisDistance) { + distance = thisDistance; + closestHandle = $(this); + index = i; + } + }); + + // workaround for bug #3736 (if both handles of a range are at 0, + // the first is always used as the one with least distance, + // and moving it is obviously prevented by preventing negative ranges) + if(o.range == true && this.values(1) == o.min) { + closestHandle = $(this.handles[++index]); + } + + this._start(event, index); + + self._handleIndex = index; + + closestHandle + .addClass("ui-state-active") + .focus(); + + var offset = closestHandle.offset(); + var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle'); + this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { + left: event.pageX - offset.left - (closestHandle.width() / 2), + top: event.pageY - offset.top + - (closestHandle.height() / 2) + - (parseInt(closestHandle.css('borderTopWidth'),10) || 0) + - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0) + + (parseInt(closestHandle.css('marginTop'),10) || 0) + }; + + normValue = this._normValueFromMouse(position); + this._slide(event, index, normValue); + return true; + + }, + + _mouseStart: function(event) { + return true; + }, + + _mouseDrag: function(event) { + + var position = { x: event.pageX, y: event.pageY }; + var normValue = this._normValueFromMouse(position); + + this._slide(event, this._handleIndex, normValue); + + return false; + + }, + + _mouseStop: function(event) { + + this.handles.removeClass("ui-state-active"); + this._stop(event, this._handleIndex); + this._change(event, this._handleIndex); + this._handleIndex = null; + this._clickOffset = null; + + return false; + + }, + + _detectOrientation: function() { + this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal'; + }, + + _normValueFromMouse: function(position) { + + var pixelTotal, pixelMouse; + if ('horizontal' == this.orientation) { + pixelTotal = this.elementSize.width; + pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0); + } else { + pixelTotal = this.elementSize.height; + pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0); + } + + var percentMouse = (pixelMouse / pixelTotal); + if (percentMouse > 1) percentMouse = 1; + if (percentMouse < 0) percentMouse = 0; + if ('vertical' == this.orientation) + percentMouse = 1 - percentMouse; + + var valueTotal = this._valueMax() - this._valueMin(), + valueMouse = percentMouse * valueTotal, + valueMouseModStep = valueMouse % this.options.step, + normValue = this._valueMin() + valueMouse - valueMouseModStep; + + if (valueMouseModStep > (this.options.step / 2)) + normValue += this.options.step; + + // Since JavaScript has problems with large floats, round + // the final value to 5 digits after the decimal point (see #4124) + return parseFloat(normValue.toFixed(5)); + + }, + + _start: function(event, index) { + this._trigger("start", event, this._uiHash(index)); + }, + + _slide: function(event, index, newVal) { + + var handle = this.handles[index]; + + if (this.options.values && this.options.values.length) { + + var otherVal = this.values(index ? 0 : 1); + + if ((index == 0 && newVal >= otherVal) || (index == 1 && newVal <= otherVal)) + newVal = otherVal; + + if (newVal != this.values(index)) { + var newValues = this.values(); + newValues[index] = newVal; + // A slide can be canceled by returning false from the slide callback + var allowed = this._trigger("slide", event, this._uiHash(index, newVal, newValues)); + var otherVal = this.values(index ? 0 : 1); + if (allowed !== false) { + this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true); + } + } + + } else { + + if (newVal != this.value()) { + // A slide can be canceled by returning false from the slide callback + var allowed = this._trigger("slide", event, this._uiHash(index, newVal)); + if (allowed !== false) { + this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate )); + } + + } + + } + + }, + + _stop: function(event, index) { + this._trigger("stop", event, this._uiHash(index)); + }, + + _change: function(event, index) { + this._trigger("change", event, this._uiHash(index)); + }, + + value: function(newValue) { + + if (arguments.length) { + this._setData("value", newValue); + this._change(null, 0); + } + + return this._value(); + + }, + + values: function(index, newValue, animated, noPropagation) { + + if (arguments.length > 1) { + this.options.values[index] = newValue; + this._refreshValue(animated); + if(!noPropagation) this._change(null, index); + } + + if (arguments.length) { + if (this.options.values && this.options.values.length) { + return this._values(index); + } else { + return this.value(); + } + } else { + return this._values(); + } + + }, + + _setData: function(key, value, animated) { + + $.widget.prototype._setData.apply(this, arguments); + + switch (key) { + case 'orientation': + + this._detectOrientation(); + + this.element + .removeClass("ui-slider-horizontal ui-slider-vertical") + .addClass("ui-slider-" + this.orientation); + this._refreshValue(animated); + break; + case 'value': + this._refreshValue(animated); + break; + } + + }, + + _step: function() { + var step = this.options.step; + return step; + }, + + _value: function() { + + var val = this.options.value; + if (val < this._valueMin()) val = this._valueMin(); + if (val > this._valueMax()) val = this._valueMax(); + + return val; + + }, + + _values: function(index) { + + if (arguments.length) { + var val = this.options.values[index]; + if (val < this._valueMin()) val = this._valueMin(); + if (val > this._valueMax()) val = this._valueMax(); + + return val; + } else { + return this.options.values; + } + + }, + + _valueMin: function() { + var valueMin = this.options.min; + return valueMin; + }, + + _valueMax: function() { + var valueMax = this.options.max; + return valueMax; + }, + + _refreshValue: function(animate) { + + var oRange = this.options.range, o = this.options, self = this; + + if (this.options.values && this.options.values.length) { + var vp0, vp1; + this.handles.each(function(i, j) { + var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100; + var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; + $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); + if (self.options.range === true) { + if (self.orientation == 'horizontal') { + (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate); + (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); + } else { + (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate); + (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); + } + } + lastValPercent = valPercent; + }); + } else { + var value = this.value(), + valueMin = this._valueMin(), + valueMax = this._valueMax(), + valPercent = valueMax != valueMin + ? (value - valueMin) / (valueMax - valueMin) * 100 + : 0; + var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; + this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); + + (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate); + (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); + (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate); + (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); + } + + }, + + _uiHash: function(index, value, values) { + + var multiple = this.options.values && this.options.values.length; + return { + handle: this.handles[index], + value: value || (multiple ? this.values(index) : this.value()), + values: values || (multiple && this.values()) + }; + + } + +})); + +$.extend($.ui.slider, { + getter: "value values", + version: "1.7", + eventPrefix: "slide", + defaults: { + animate: false, + delay: 0, + distance: 0, + max: 100, + min: 0, + orientation: 'horizontal', + range: false, + step: 1, + value: 0, + values: null + } +}); + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini b/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini new file mode 100644 index 0000000..8498163 --- /dev/null +++ b/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini @@ -0,0 +1,37 @@ +#PHP IMAGE EDITOR TEXTS +EDIT IMAGE=Edit Image +RESIZE IMAGE=Resize Image +WIDTH=Width +HEIGHT=Height +KEEP PROPORTIONS=Keep Proportions +ROTATE IMAGE=Rotate Image +LEFT 90 DEGREES=Left 90 Degrees +RIGHT 90 DEGREES=Right 90 Degrees +CROP IMAGE=Crop Image +EFFECTS=Effects +SELECT EFFECT=Select Effect +SAVE AND CLOSE=Save and Close +GRAYSCALE=Grayscale +CONTRAST=Contrast +BRIGHTNESS=Brightness +DARKER=Darker +IS REQUIRED=is required +MUST BE NUMERIC=must be numeric +NOT NEGATIVE=must be a positive number +NOT IN RANGE=is not in valid range +CANT BE LARGER THEN=can´t be larger then +NO PROVIDED IMAGE=No image has been provided. +IMAGE DOES NOT EXIST=The image doesn´t exist. +INVALID IMAGE TYPE=Image must be of type jpeg, png or gif. +OLD PHP VERSION=is too old php version. Minimum is: +OLD GD VERSION=is too old GD version. Minimum is: +UNDO=Undo +UPDATE=Update +LOADING=Loading +AN UNEXPECTED ERROR=An unexpected error has occured, please try again... +RESIZE HELP=Update Width and Height fields.
    Or drag and drop in the right or bottom side of the image. +CROP HELP=Drag and drop to create a crop area on the image. +CROP WIDTH=Crop Width +CROP HEIGHT=Crop Height +CROP KEEP PROPORTIONS=Keep Crop Proportions +INSTRUCTIONS=Instructions \ No newline at end of file diff --git a/Toolkit/Page.php b/Toolkit/Page.php new file mode 100755 index 0000000..7832075 --- /dev/null +++ b/Toolkit/Page.php @@ -0,0 +1,887 @@ + + * @copyright 2009 Gaslight Media + * @license http://demo.gaslightmedia.com Gaslight Media + * @version CVS: $Id: Page.php,v 1.80 2010/08/16 17:39:58 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ +/** + * Page for Error Doc + */ +define("ERROR_DOCUMENT", "404.html"); + +/** + * The home page template + */ +define("HOME_TEMPLATE", "template.html"); + +/** + * inside page template + */ +define("INSIDE_TEMPLATE", "template.html"); + +/** + * Template for the error doc + */ +define("ERROR_DOCUMENT_TEMPLATE", "404-template.html"); + +/** + * page title default + */ +define("PAGE_TITLE", SITENAME); + +/** + * Toolkit_Page + * + * A class Object for use with merging into the flexy template for output. + * Sets up the $page object used for merging with the flexy template + * to output the toolbox and members admin content + * + * @category Toolkit + * @package Page + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license http://demo.gaslightmedia.com Gaslight Media + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Page +{ + + /** + * 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 ' + '; + } + + /** + * 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); + } + } +} diff --git a/Toolkit/Registry.php b/Toolkit/Registry.php new file mode 100644 index 0000000..3003cd1 --- /dev/null +++ b/Toolkit/Registry.php @@ -0,0 +1,82 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Registry.php,v 1.2 2010/05/25 14:07:22 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Variable Registry + * + * The registry is an object where site wide variables can be stored + * without the use of globals. By passing the registry object to + * the controllers that need them, we avoid pollution of the global + * namespace and render our variables safe. + * + * @category Toolkit + * @package Registry + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Registry +{ + // {{{ properties + + /** + * variables + * @access private + */ + private $_vars = array(); + + // }}} + + // {{{ __set() + + /** + * Sets undefined variables + * + * @param string $index key index in variables array + * @param mixed $value variable value + * + * @return void + * @access public + */ + public function __set($index, $value) + { + $this->_vars[$index] = $value; + } + + // }}} + // {{{ __get() + + /** + * Gets defined variables + * + * @param mixed $index variable to retrieve + * + * @return mixed + */ + public function __get($index) + { + return $this->_vars[$index]; + } + + // }}} +} +?> diff --git a/Toolkit/Router.php b/Toolkit/Router.php new file mode 100644 index 0000000..eaca26d --- /dev/null +++ b/Toolkit/Router.php @@ -0,0 +1,195 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Registry.php,v 1.2 2010/05/25 14:07:22 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Toolkit_Router + * + * The registry is an object where site wide variables can be stored + * without the use of globals. By passing the registry object to + * the controllers that need them, we avoid pollution of the global + * namespace and render our variables safe. + * + * @category Toolkit + * @package Router + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Router +{ + // {{{ properties + + + /** + * Description for $_registry + * @var string + * @access protected + */ + private $_registry; + + /** + * Description for $_path + * @var string + * @access protected + */ + private $_path; + + /** + * Description for $_application + * @var string + * @access protected + */ + private $_application; + + /** + * Will hold location of controller + * @var string + * @access protected + */ + public $file; + + /** + * Holds intended controller + * @var string + * @access protected + */ + public $controller; + + /** + * Holds intended action + * @var string + * @access protected + */ + public $action; + + // }}} + // {{{ __construct() + + /** + * class constructor + * + * @param Toolkit_Registry $registry Registry + * + * @access public + */ + public function __construct(Toolkit_Registry $registry) + { + $this->_registry = $registry; + } + + // }}} + + // {{{ _getController() + + /** + * Gets controller and action. + * + * @access private + * @return void + */ + private function _getController() + { + $this->controller = empty($_GET['rt']) ? 'Index' : $_GET['rt']; + $this->action = empty($_GET['ac']) ? 'index' : $_GET['ac']; + + // all action methods must end in the word [Action] so we + // can easily spot them. + $this->action .= 'Action'; + + $this->file = $this->_path . '/' . $this->controller . 'Controller.php'; + } + + // }}} + + // {{{ loader() + + /** + * Loads toolkit application + * + * @return string + */ + public function loader() + { + // Check the route + $this->_getController(); + + // If the file is not there, log error + if (is_readable($this->file) == false) { + $this->_registry + ->logger + ->emerg("File is not readable: `{$this->file}`"); + } + + $class = "Toolkit_{$this->_application}_{$this->controller}Controller"; + $controller = new $class($this->_registry); + + if (is_callable(array($controller, $this->action)) == false) { + $action = 'indexAction'; + } else { + $action = $this->action; + } + + return $controller->$action(); + } + + // }}} + + // {{{ setApplication() + + /** + * Set application + * + * @param string $application Application + * + * @return void + */ + public function setApplication($application) + { + $this->_application = str_replace('/', '_', $application); + } + + // }}} + // {{{ setPath() + + /** + * Sets path + * + * @param string $path Path + * + * @throws RuntimeException + * + * @return void + */ + public function setPath($path) + { + if (is_dir($path) == false) { + throw new RuntimeException( + "Invalid controller path: `$path`" + ); + } + + $this->_path = $path; + } + + // }}} +} +?> diff --git a/Toolkit/ShortURL.php b/Toolkit/ShortURL.php new file mode 100755 index 0000000..208b885 --- /dev/null +++ b/Toolkit/ShortURL.php @@ -0,0 +1,163 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_ShortURL + * + * Integration of Toolbox with creation of ShortURL + * the url rewrite happens with one line of code in .htaccess + * RewriteRule ^([A-Za-z0-9_-]*)$ index.php?page=$1 [L] + * index page checks for $_GET['page'] and then calls + * getShortUrlId to get the page's catid. If not found it + * defaults to HOME_ID + * + * @category Toolkit + * @package Toolkit_ShortURL + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version Release: @package_version@ + * @link <> + */ +class Toolkit_ShortURL +{ + // {{{ Class Properties + + /** + * Database handler + * @var PDO + * @access private + */ + private $_dbh; + + // }}} + + // {{{ __construct() + + /** + * __construct() + * + * @param PDO $dbh Database handler + * + * @return void + * @access public + */ + function __construct(PDO $dbh) + { + $this->_dbh = $dbh; + } + + // }}} + // {{{ getShortUrl() + + /** + * getShortUrl() + * + * grab the shorturl from bus_category table + * else return false + * + * @param string $id bus_category id + * + * @return mixed ShortURL from bus_category + * @access public + */ + function getShortUrl($id) + { + $sql = " + SELECT short_url + FROM pages + WHERE id = :id"; + try { + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(":id", $id, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getShortUrlId() + + /** + * getShortUrlId() + * + * grab the id from bus_category table + * else return false + * + * @param string $short_url bus_category short_url + * + * @return mixed catid for page or HOME_ID if not found + * @access public + */ + function getShortUrlId($short_url) + { + $sql = " + SELECT id + FROM pages + WHERE short_url = :short_url"; + try { + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(":short_url", $short_url, PDO::PARAM_STR); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + return HOME_ID; + } + + // }}} + // {{{ isValidUrlName() + + /** + * check the short url nam eto make sure it doesn't match any file names in the root + * + * @param mixed $url requested short url name + * + * @access public + * @return string + */ + public function isValidUrlName($url) + { + if (is_dir(BASE)) { + if (file_exists(BASE . $url)) { + return false; + } + if (file_exists(BASE . $url.'.php')) { + return false; + } + if (file_exists(BASE . $url.'.css')) { + return false; + } + if (file_exists(BASE . $url.'.html')) { + return false; + } + if (file_exists(BASE . $url.'.js')) { + return false; + } + return true; + } else { + throw new Exception('Main Web root dir define BASE not set'); + } + } + + // }}} +} +?> diff --git a/Toolkit/SiteMap.php b/Toolkit/SiteMap.php new file mode 100755 index 0000000..c527645 --- /dev/null +++ b/Toolkit/SiteMap.php @@ -0,0 +1,158 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: SiteMap.php,v 1.10 2010/06/08 20:39:20 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_SiteMap + * + * Generate a sitemap for the site + * need to remove members only pages and other pages you + * don't want viewed by public + * + * @category Toolkit + * @package Toolkit_SiteMap + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_SiteMap +{ + // {{{ Properties + /** + * Description of $beginLevel + * @var string + * @access public + */ + var $beginLevel = "
      "; + + /** + * Description of $endLevel + * @var string + * @access public + */ + var $endLevel = "
    "; + + /** + * Description of $beginItem + * @var string + * @access public + */ + var $beginItem = "
  • "; + + /** + * Description of $endItem + * @var string + * @access public + */ + var $endItem = "
  • "; + + /** + * Description of $wholeThread + * @var string + * @access public + */ + var $wholeThread; + + /** + * Description of $search + * @var string + * @access public + */ + var $search = ""; + + /** + * Description of $pageGateway + * @var string + * @access public + */ + var $pageGateway; + + // }}} + + /** + * Class constructor + * + * Creates object of siteMap + * + * @param string $pageGateway page gateway + */ + public function __construct($pageGateway) + { + $this->pageGateway = $pageGateway; + } + // {{{ sortChilds() + + /** + * sortChilds + * + * Sort by Parent + * + * @param array $threads Array + * + * @return array Return array + * @access public + */ + function sortChilds($threads) + { + $childs = array(); + while (list($var, $value) = each($threads)) { + $childs[$value['parent']][$value['id']] = $value; + } + return $childs; + } + + // }}} + + // {{{ convertToThread() + + /** + * convertToThread + * + * outputs the array with the correct styles and code applied + * + * @param array $threads Thread array + * @param array $thread Start with thread[0] will work it way down + * + * @return wholeThread + * @access public + */ + function convertToThread($threads, $thread) + { + static $level_counter = 1; + + $this->wholeThread .= $this->beginLevel; + while (list($parent, $value) = each($thread)) { + $this->wholeThread .= $this->beginItem; + $page = Toolkit_Template_Page::getSeoUrl( + $this->pageGateway, + $value['id'] + ); + $this->wholeThread .= ''; + $this->wholeThread .= $value["category"] + . ""; + if ($threads[$parent]) { + ++$level_counter; + $this->convertToThread($threads, $threads[$parent]); + --$level_counter; + } + $this->wholeThread .= $this->endItem ."\n"; + } + $this->wholeThread .= $this->endLevel; + return $this->wholeThread; + } + // }}} +} +?> diff --git a/Toolkit/SiteMapXml.php b/Toolkit/SiteMapXml.php new file mode 100644 index 0000000..7fb394f --- /dev/null +++ b/Toolkit/SiteMapXml.php @@ -0,0 +1,186 @@ + + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @version SVN: $id$ + * @link <> + */ + +/** + * Toolkit_SiteMapXml + * + * Description of Toolkit_SiteMapXml + * + * @category Toolkit + * @package Toolkit + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ + +class Toolkit_SiteMapXml +{ + /** + * Database Connection + * + * @var PDO + * @access private + */ + private $_dbh; + + /** + * Class Constructor + * + * @param PDO $pdo Database Connection + * + * @return void + * @access public + */ + public function __construct(PDO $pdo) + { + $this->_dbh = $pdo; + } + + /** + * getMobileSitemap + * + * Call this function with no $sid. + * + * This function will recurse down the menu structure and + * return a full list of all menu data at all levels + * + * This is helpful for generating a sitemap or index + * + * @static var array $mids Member array + * @static var string $xml XML string + * + * @param int $sid Catid of the page + * + * @return string xml + * @access public + */ + public function getXmlSitemap($sid = 0) + { + + // Characters to be replaced in link text + $transdata = array('/' => '', ' ' => '-', '&' => ''); + + // Array to keep track of member's for whom we produced links + // This is used to prevent duplicate links to the same member + // records from different catids. It's static so that it is + // common to all instances of recursion. + static $mids = array(); + + // This is where the XML site map goes. It's also static so + // we don't have to pass map segments back from recursive calls. + static $xml = ''; + + // If this is the top level, add the beginning of the xml file + if ($sid == 0) { + $xml = '' . "\r\n" + . '' . "\r\n"; + } + + $qs = " + SELECT id, navigation_name as category, include_members + FROM pages + WHERE parent = :id"; + if (defined('MEMBERS_CATEGORY') && MEMBERS_CATEGORY) { + $qs .= " AND parent != ".MEMBERS_CATEGORY." + AND id != ".MEMBERS_CATEGORY; + } + $qs .= " AND active = 't' + ORDER BY pos"; + $stmt = $this->_dbh->prepare($qs); + $stmt->bindParam( + ':id', + $sid, + PDO::PARAM_INT + ); + $stmt->execute(); + + while ($v = $stmt->fetch(PDO::FETCH_ASSOC)) { + $catid = $v['id']; + if ($catid > 0) { + // Add this menu item to the site map + $url + = ($catid == HOME_ID) + ? MEDIA_BASE_URL + : MEDIA_BASE_URL . strtr($v['category'], $transdata) . '-' + . $catid . '/'; + $xml .= '' . $url . "\r\n"; + // Get members for this catid + if (MEMBERS_DB == 1 && $v['include_members']) { + // now check to see if the page has member + // categories assigned to it + $qs = " + SELECT * + FROM member_categories2toolbox_pages + WHERE page = {$catid}"; + $mc2tpData + = $this->_dbh->query($qs) + ->fetchAll(PDO::FETCH_ASSOC); + if ($mc2tpData) { + foreach ($mc2tpData as $mc2tp) { + $mc2tpCat[] = $mc2tp['category']; + } + if (is_array($mc2tpCat) && !empty($mc2tpCat)) { + $where = " WHERE member_id IN ( + SELECT member_id + FROM member_category + WHERE category_id IN (" + . implode(",", $mc2tpCat) . ")) "; + } + } + $qs = " + SELECT member_id,member_name + FROM member + $where"; + $members = $this->_dbh + ->query($qs) + ->fetchAll(PDO::FETCH_ASSOC); + } //IF MEMBERS_DB + // If there are any + if ($members && count($members) > 0) { + // Include an entry for each member on this page + foreach ($members as $memb) { + + // Check to make sure we have a member # and + // that we haven't already provided some + // link to this member + $member = ($memb['member_id'] - 0); + if ($member > 0 && !isset($mids[$member])) { + + // Add this member to the site map + $murl = MEDIA_BASE_URL . 'member-profile/'.$catid + . '/' . $member . '/'; + $xml .= '' . $murl + . "\r\n"; + // Add this member to the member id array so we + // don't display them again. + $mids[$member] = true; + } + } + } // if members + $this->getXmlSitemap($catid); + } // if catid + } // if menu results + // If this is the top level, add the end of the XML file and be done + if ($sid == 0) { + $xml .= "\r\n"; + return $xml; + } + } + +} \ No newline at end of file diff --git a/Toolkit/SortForm.php b/Toolkit/SortForm.php new file mode 100644 index 0000000..1c6e8da --- /dev/null +++ b/Toolkit/SortForm.php @@ -0,0 +1,67 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: SortForm.php,v 1.6 2010/01/18 02:09:05 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Creates a sortform to be used w/ datagrid DataGrids + * + * @category HTML + * @package Toolkit_SortForm + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_SortForm extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The default rules to register for validating + * + * @var string + * @access protected + */ + protected $registeredRules = array(); + + // }}} + // {{{ toHTML() + + /** + * Render the form to a string + * + * Handle the rendering and validation of the form when displayed + * and submitted. + * + * @return string html form + * @access public + */ + public function toHTML() + { + $this->setupRenderers(); + if ($this->validate()) { + $output = parent::toHTML(); + } else if ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $output = parent::toHTML(); + } + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/Table.php b/Toolkit/Table.php new file mode 100644 index 0000000..2b6120a --- /dev/null +++ b/Toolkit/Table.php @@ -0,0 +1,300 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Abstract class for aiding creation of class objects which relate to + * Database tables + * + * @category Toolkit + * @package Table + * @author Steve Sutton + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +abstract class Toolkit_Table + implements Toolkit_ITable, Toolkit_IMapper +{ + /** + * Description for $tableName + * @var string + * @access protected + */ + protected $tableName; + + /** + * Helps to create functions for any class variable if the variable does + * exists + * + * @param String $name Name of variable + * @param mixed $args Argument for the varable (if set) + * + * @return Toolkit_Table + */ + public function __call($name, $args) + { + if ( preg_match('/^(get|set)(\w+)/', strtolower($name), $match) + && $attribute = $this->validateAttribute($match[2]) + ) { + if ('get' == $match[1]) { + return $this->$attribute; + } else { + $this->$attribute = trim($args[0]); + return $this; + } + } else { + throw new Exception( + 'Call to undefined method '. get_class($this).'::' . $name + ); + } + } + + /** + * Create a class object that has the given values from an array + * + * @param Array $values Array of values to set the class properties to + * + * @return Object + * @access public + */ + public function createByValues($values) + { + $classVars = get_object_vars($this); + unset($classVars['tableName']); + foreach ($classVars as $fieldName => $var) { + if ($fieldName == 'id' && $values[$fieldName] == '') { + continue; + } + $setter = 'set' . ucfirst($fieldName); + $this->$setter($values[$fieldName]); + } + return $this; + } + + /** + * Removes a object from the database by the id + * if id is not set then it throws an error + * + * @param PDO $dbh Database Connection + * + * @return void + * @throws Exception + * @access public + */ + public function delete(PDO $dbh) + { + if (!$this->id) { + throw new Exception('id is not set'); + } + try { + $sql = " + DELETE + FROM {$this->tableName} + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $this->getId(), PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * fetch from $this->tableName by id + * + * @param PDO $dbh Database Connection + * @param integer $id id to fetch with + * + * @return null|object + * @access public + */ + public function fetchById(PDO $dbh, $id) + { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $values = $stmt->fetch(PDO::FETCH_ASSOC); + if ($values) { + return $this->createByValues($values); + } else { + return null; + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Return the object as an array + * + * @return Array + * @access public + */ + public function getPropertiesAsArray() + { + $classVars = get_object_vars($this); + unset($classVars['tableName']); + return $classVars; + } + + /** + * Return the table metadata + * + * @param PDO $dbh Database Connection + * @param string $tableName Table name + * + * @return array + * @access public + */ + public function getTableMetaData(PDO $dbh, $tableName = null) + { + try { + $sql = " + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = :tname"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':tname', $tableName, PDO::PARAM_STR); + $stmt->execute(); + + $metaData = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $metaData[$row['column_name']] = $row['data_type']; + } + + return $metaData; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + /** + * insert the object + * + * @param PDO $dbh Database Connection + * + * @return Toolkit_Table + * @access public + */ + public function insert(PDO $dbh) + { + + try { + $values = get_object_vars($this); + unset($values['id'], $values['tableName']); + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + $sql .= ' RETURNING id'; + $stmt = Toolkit_Common::prepareQuery( + $dbh, + $this->tableName, + $sql, + $values + ); + $stmt->execute(); + $this->setId($stmt->fetchColumn()); + return $this; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Checks the id of the object if it is set then calls update othervise + * calls insert function + * + * @param PDO $dbh Database connection + * + * @return void + * @access public + */ + public function save(PDO $dbh) + { + if ($this->id) { + $this->update($dbh); + } else { + $this->insert($dbh); + } + } + + /** + * sets the id of object + * + * @param Int $id set the id of object if not numeric throw Exception + * + * @return Toolkit_Table + * @access public + */ + public function setId($id) + { + if (!is_numeric($id)) { + throw new Exception('id must be an integer'); + } + if (!$this->id) { + $this->id = $id; + } + return $this; + } + + /** + * update the object + * + * @param PDO $dbh Database connection + * + * @return Toolkit_Table + * @access public + */ + public function update(PDO $dbh) + { + try { + $values = get_object_vars($this); + unset($values['tableName']); + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('id = :id') + ); + $stmt = Toolkit_Common::prepareQuery( + $dbh, + $this->tableName, + $sql, + $values + ); + $stmt->execute(); + return $this; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + /** + * Validates the property + * + * @param String $name property name + * + * @return String + * @access public + */ + protected function validateAttribute($name) + { + if (property_exists(get_class($this), $name)) { + return strtolower($name); + } + } +} diff --git a/Toolkit/Template/BreadCrumbs.php b/Toolkit/Template/BreadCrumbs.php new file mode 100644 index 0000000..3a2a20e --- /dev/null +++ b/Toolkit/Template/BreadCrumbs.php @@ -0,0 +1,143 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_BreadCrumbs + * + * Description of Toolkit_Template_BreadCrumbs + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_BreadCrumbs +{ + // {{{ properties + + /** + * Description for $pageGateway + * @var Toolkit_Toolbox_PageGatewayAbstract $gateway + * @access protected + */ + protected $pageGateway; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * @access public + */ + public function __construct(Toolkit_Toolbox_PageGatewayAbstract $gateway) + { + $this->pageGateway = $gateway; + } + + // }}} + // {{{ getBreadCrumbsArray() + + /** + * Gets bread crumbs array + * + * @param int $id ID + * + * @return array + * @throws RuntimeException + * @access protected + */ + protected function getBreadCrumbsArray($id) + { + $stack = array(); + + $hasPhotoGalleriesOnThisPage + = ( defined('PHOTO_GALLERY') + && PHOTO_GALLERY + && filter_var($_GET['photo_catid'], FILTER_VALIDATE_INT) + ); + + if ($hasPhotoGalleriesOnThisPage) { + if (!$catid = filter_var($_GET['catid'], FILTER_VALIDATE_INT)) { + throw new RuntimeException('Invalid catid'); + } + if (!$photoCatid = filter_var($_GET['photo_catid'], FILTER_VALIDATE_INT)) { + throw new RuntimeException('Invalid photo_catid'); + } + $page = $this->pageGateway->findNavItem($catid); + array_unshift($stack, $page['photo_galleries'][$_GET['photo_catid']]); + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->pageGateway, + $_GET['catid'] + ); + $anchor = ''.$page['navigation_name'].''; + array_unshift($stack, $anchor); + } + + if ($id != HOME_ID) { + $page = $this->pageGateway->findNavItem($id); + if ($hasPhotoGalleriesOnThisPage) { + // Do Nothing + } else { + array_unshift($stack, $page['navigation_name']); + } + $parent = $page['parent']; + while ($parent != 0) { + $page = $this->pageGateway->findNavItem($parent); + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->pageGateway, + $parent + ); + $anchor = ''.$page['navigation_name'].''; + array_unshift($stack, $anchor); + $parent = $page['parent']; + } + + $anchor = 'Home'; + array_unshift($stack, $anchor); + } + + return $stack; + } + + // }}} + // {{{ toHtml() + + /** + * to html + * + * @param int $id ID + * + * @return string + * @access public + */ + public function toHtml($id) + { + $breadCrumbsArray = $this->getBreadCrumbsArray($id); + $breadCrumbs = implode(' > ', $breadCrumbsArray); + + return !empty($breadCrumbsArray) + ? '' + : ''; + } + + // }}} +} +?> diff --git a/Toolkit/Template/DraftBreadCrumbs.php b/Toolkit/Template/DraftBreadCrumbs.php new file mode 100644 index 0000000..8bd85e4 --- /dev/null +++ b/Toolkit/Template/DraftBreadCrumbs.php @@ -0,0 +1,110 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_DraftBreadCrumbs + * + * Description of Toolkit_Template_DraftBreadCrumbs + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_DraftBreadCrumbs + extends Toolkit_Template_BreadCrumbs +{ + // {{{ properties + + /** + * Description for $pageGatewayPublish + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access protected + */ + protected $pageGatewayPublish; + + /** + * Description for $pageGatewayDraft + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access protected + */ + protected $pageGatewayDraft; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $publishGateway + * @param Toolkit_Toolbox_PageGatewayAbstract $draftGateway + * + * @access public + */ + public function __construct( + Toolkit_Toolbox_PageGatewayAbstract $publishGateway, + Toolkit_Toolbox_PageGatewayAbstract $draftGateway + ) { + $this->pageGatewayPublish = $publishGateway; + $this->pageGatewayDraft = $draftGateway; + } + + // }}} + // {{{ getBreadCrumbsArray() + + /** + * Gets BreadCrumbs Array + * + * @param int $id + * + * @return array + * @access protected + */ + protected function getBreadCrumbsArray($id) + { + if ($id == HOME_ID) { + return array(); + } + + $stack = array(); + $draftPage = $this->pageGatewayDraft->find($id); + array_unshift($stack, $draftPage['navigation_name']); + + $publishPage = $this->pageGatewayPublish->find($draftPage['published_page']); + $parent = $publishPage['parent']; + while ($parent != 0) { + $page = $this->pageGatewayPublish->find($parent); + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->pageGatewayPublish, + $parent + ); + $anchor = ''.$page['navigation_name'].''; + array_unshift($stack, $anchor); + $parent = $page['parent']; + } + + $anchor = 'Home'; + array_unshift($stack, $anchor); + + return $stack; + } + + // }}} +} +?> diff --git a/Toolkit/Template/DraftController.php b/Toolkit/Template/DraftController.php new file mode 100644 index 0000000..8d79bab --- /dev/null +++ b/Toolkit/Template/DraftController.php @@ -0,0 +1,82 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_DraftController + * + * Description of Toolkit_Template_DraftController + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_DraftController + extends Toolkit_Template_PageControllerAbstract +{ + /** + * Description of $_pageGatewayFactory + * + * @var Toolkit_Toolbox_PageGatewayDraftFactory + * @access private + */ + private $_pageGatewayFactory; + + /** + * Description of $_paragraphGatewayFactory + * + * @var Toolkit_Toolbox_ParagraphGatewayDraftFactory + * @access private + */ + private $_paragraphGatewayFactory; + + /** + * Description of getPageGatewayFactory + * + * @return Toolkit_Toolbox_PageGatewayDraftFactory + * @access protected + */ + protected function getPageGatewayFactory() + { + if (!($this->_pageGatewayFactory instanceof Toolkit_Toolbox_PageGatewayDraftFactory)) { + $this->_pageGatewayFactory = new Toolkit_Toolbox_PageGatewayDraftFactory( + $this->registry->dbh + ); + } + + return $this->_pageGatewayFactory; + } + + /** + * Description of getParagraphGatewayFactory + * + * @return Toolkit_Toolbox_ParagraphGatewayDraftFactory + * @access protected + */ + protected function getParagraphGatewayFactory() + { + if (!($this->_paragraphGatewayFactory instanceof Toolkit_Toolbox_ParagraphGatewayDraftFactory)) { + $this->_paragraphGatewayFactory = new Toolkit_Toolbox_ParagraphGatewayDraftFactory( + $this->registry->dbh + ); + } + + return $this->_paragraphGatewayFactory; + } +} +?> diff --git a/Toolkit/Template/Exception.php b/Toolkit/Template/Exception.php new file mode 100644 index 0000000..d623f22 --- /dev/null +++ b/Toolkit/Template/Exception.php @@ -0,0 +1,31 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_Exception + * + * Description of Toolkit_Template_Exception + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Exception extends Exception {} +?> diff --git a/Toolkit/Template/Image/Factory.php b/Toolkit/Template/Image/Factory.php new file mode 100644 index 0000000..13614db --- /dev/null +++ b/Toolkit/Template/Image/Factory.php @@ -0,0 +1,91 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Image_Factory + * + * Description of Toolkit_Template_Image_Factory + * + * @category Toolkit + * @package Template/Image + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Image_Factory +{ + // {{{ properties + + /** + * Description of $_imageServerAdapter + * + * @var string + * @access private + */ + private $_imageServerAdapter; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_FileServer_ImageAdapter $adapter Adapter + * + * @access public + */ + public function __construct(Toolkit_FileServer_ImageAdapter $adapter) + { + $this->_imageServerAdapter = $adapter; + } + + // }}} + // {{{ getImageBuilder() + + /** + * Get image builder + * + * @param array $data data + * @param string $side Side image is on + * + * @access public + * @return \Toolkit_Template_Image_Left|\Toolkit_Template_Image_Right|\Toolkit_Template_Image_Null + */ + public function getImageBuilder(array $data, $side) + { + if (isset($data['image']) && !empty($data['image'])) { + if ($side == 'left') { + return new Toolkit_Template_Image_Left( + $this->_imageServerAdapter, + $data['image'], + $data['caption'] + ); + } else { + return new Toolkit_Template_Image_Right( + $this->_imageServerAdapter, + $data['image'], + $data['caption'] + ); + } + } else { + return new Toolkit_Template_Image_Null(); + } + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/ImageAbstract.php b/Toolkit/Template/Image/ImageAbstract.php new file mode 100644 index 0000000..bb212ca --- /dev/null +++ b/Toolkit/Template/Image/ImageAbstract.php @@ -0,0 +1,114 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: ImageAbstract.php,v 1.1 2010/07/22 19:59:01 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Page Image Element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +abstract class Toolkit_Template_Image_ImageAbstract +{ + // {{{ properties + + /** + * Description for $_adapter + * + * @var string + * @access protected + */ + protected $_adapter; + + /** + * Description for $_caption + * + * @var string + * @access protected + */ + protected $_caption; + + /** + * Description for $_src + * + * @var string + * @access protected + */ + protected $_src; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * Sets elements attributes + * + * @param Toolkit_FileServer_ImageAdapter $adapter File server adapter + * @param string $src src attribute value + * @param string $caption caption + * + * @return void + * @access public + */ + public function __construct( + Toolkit_FileServer_ImageAdapter $adapter, + $src, + $caption + ) { + if (empty($src)) { + throw new InvalidArgumentException('$src cannot be empty'); + } + + $this->_adapter = $adapter; + $this->_caption = $caption; + $this->_src = $src; + } + + // }}} + + // {{{ getImage() + + /** + * Get image + * + * @param int $size Size + * + * @return string + * @access public + */ + public function getImage($size) + { + $format = '%s'; + $img = sprintf( + $format, + $size . $this->_src, + $this->_caption, + $this->_src + ); + + return $img; + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/Left.php b/Toolkit/Template/Image/Left.php new file mode 100644 index 0000000..6fb37f1 --- /dev/null +++ b/Toolkit/Template/Image/Left.php @@ -0,0 +1,62 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Left.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Page Image + * + * Returns a left side image + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Image_Left extends Toolkit_Template_Image_ImageAbstract +{ + // {{{ getImage() + + /** + * Gets the image markup + * + * @param string $size constant path to image size + * + * @return string Html image element + * @access public + */ + public function getImage($size) + { + $imageData = $this->_adapter->getImageSize($size . $this->_src); + + $html = '
    '; + $html .= parent::getImage($size); + if (!empty($this->_caption)) { + $html .= '
    '; + $html .= $this->_caption; + $html .= '
    '; + } + $html .= '
    '; + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/Null.php b/Toolkit/Template/Image/Null.php new file mode 100644 index 0000000..fe291cb --- /dev/null +++ b/Toolkit/Template/Image/Null.php @@ -0,0 +1,56 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Null.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Coupon Image Element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Image_Null +{ + /** + * Class construct + */ + public function __construct() + { + + } + + // {{{ getImage() + + /** + * Get nothing for the image + * + * @param int $size Size of image + * + * @return string empty html string; + * @access public + */ + public function getImage($size) + { + return; + } + + // }}} +} +?> diff --git a/Toolkit/Template/Image/Right.php b/Toolkit/Template/Image/Right.php new file mode 100644 index 0000000..f1ef03b --- /dev/null +++ b/Toolkit/Template/Image/Right.php @@ -0,0 +1,62 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: Right.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Page Image + * + * Returns a right side image + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Image_Right extends Toolkit_Template_Image_ImageAbstract +{ + // {{{ getImage() + + /** + * Gets the image markup + * + * @param string $size constant path to image size + * + * @return string Html image element + * @access public + */ + public function getImage($size) + { + $imageData = $this->_adapter->getImageSize($size . $this->_src); + + $html = '
    '; + $html .= parent::getImage($size); + if (!empty($this->_caption)) { + $html .= '
    '; + $html .= $this->_caption; + $html .= '
    '; + } + $html .= '
    '; + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Template/IndexController.php b/Toolkit/Template/IndexController.php new file mode 100644 index 0000000..442ebfb --- /dev/null +++ b/Toolkit/Template/IndexController.php @@ -0,0 +1,82 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_IndexController + * + * Description of Toolkit_Template_IndexController + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_IndexController + extends Toolkit_Template_PageControllerAbstract +{ + /** + * Description for $_pageGatewayFactory + * + * @var Toolkit_Toolbox_PageGatewayPublishFactory + * @access private + */ + private $_pageGatewayFactory; + + /** + * Description for $_paragraphGatewayFactory + * + * @var Toolkit_Toolbox_PageGatewayPublishFactory + * @access private + */ + private $_paragraphGatewayFactory; + + /** + * description of paragraphGatewayFactory + * + * @return Toolkit_Toolbox_ParagraphGatewayPublishFactory + * @access protected + */ + protected function getPageGatewayFactory() + { + if (!($this->_pageGatewayFactory instanceof Toolkit_Toolbox_PageGatewayPublishFactory)) { + $this->_pageGatewayFactory = new Toolkit_Toolbox_PageGatewayPublishFactory( + $this->registry->dbh + ); + } + + return $this->_pageGatewayFactory; + } + + /** + * description of getParagraphGatewayFactory + * + * @return Toolkit_Toolbox_ParagraphGatewayPublishFactory + * @access protected + */ + protected function getParagraphGatewayFactory() + { + if (!($this->_paragraphGatewayFactory instanceof Toolkit_Toolbox_ParagraphGatewayPublishFactory)) { + $this->_paragraphGatewayFactory = new Toolkit_Toolbox_ParagraphGatewayPublishFactory( + $this->registry->dbh + ); + } + + return $this->_paragraphGatewayFactory; + } +} +?> diff --git a/Toolkit/Template/KeywordReplacement.php b/Toolkit/Template/KeywordReplacement.php new file mode 100644 index 0000000..c3c2230 --- /dev/null +++ b/Toolkit/Template/KeywordReplacement.php @@ -0,0 +1,86 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_KeywordReplacement + * + * Description of Toolkit_Template_KeywordReplacement + * + * @category Toolkit + * @package Template + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_KeywordReplacement +{ + /** + * Description for $_pageGateway + * @var Toolkit_Toolbox_GatewayAbstract + * @access private + */ + private $_pageGateway; + + /** + * Class constructor + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Gateway + * + * @access public + */ + public function __construct(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $this->_pageGateway = $gateway; + } + + /** + * Description for findAndReplace() + * + * @param string $haystack Haystack + * + * @return string + * @access public + */ + public function findAndReplace($haystack) + { + if (strstr($haystack, '{') !== false) { + $pattern = '/\{([A-Z0-9\&\-\,\'\" ]*)\}/i'; + if (preg_match($pattern, $haystack, $needle) != 0) { + $page = $this->_pageGateway->findByKeyword($needle[1]); + if ($page == false) { + return $haystack; + } else { + $seoUrl = Toolkit_Template_Page::getSeoUrl( + $this->_pageGateway, + $page['id'] + ); + $anchor = ''.$page['navigation_name'].''; + $haystack = str_replace($needle[0], $anchor, $haystack); + } + } else { + return $haystack; + } + + if (strstr($haystack, '{') !== false) { + return $this->findAndReplace($haystack); + } + } + + return $haystack; + } +} +?> diff --git a/Toolkit/Template/Navigation/AllInOneSideNav.php b/Toolkit/Template/Navigation/AllInOneSideNav.php new file mode 100755 index 0000000..2f2df53 --- /dev/null +++ b/Toolkit/Template/Navigation/AllInOneSideNav.php @@ -0,0 +1,128 @@ + + * @copyright 2013 Gaslight Media + * @license Gaslight Media + * @version SVN: (0.1) + * @link <> + */ + +/** + * Toolkit_Package_AllInOneSideNav + * + * Description of AllInOneSideNav + * + * @category Toolkit + * @package Package + * @author Steve Sutton + * @copyright 2013 Gaslight Media + * @license Gaslight Media + * @release Release: (0.1) + * @link <> + */ +class Toolkit_Template_Navigation_AllInOneSideNav +{ + private $_parents = array(); + private $_navArray = array(); + private $_gateway; + private $_pageId; + + public function __construct( + Toolkit_Toolbox_GatewayAbstract $gateway + ) { + $this->_gateway = $gateway; + $id = filter_var($_REQUEST['catid'], FILTER_VALIDATE_INT); + $this->_pageId = $id; + if (!$id) { + $id = HOME_ID; + } + $this->_parents = $this->_getParentIds($id); + } + + public function getNavigation() + { + return $this->setNavArray(0); + } + + public function setNavArray($id) + { + try { + $navArray = array(); + $dbh = Toolkit_Database::getInstance(); + $pages = (defined('ALL_IN_ONE_INCLUDED') + && ALL_IN_ONE_INCLUDED) + ? unserialize(ALL_IN_ONE_INCLUDED) + : null; + $includedPages = (!empty($pages)) + ? "AND (parent != 0 OR id IN (".implode(',', $pages)."))" + : ''; + $memberPages = (defined('MEMBERS_DB') && MEMBERS_DB) + ? "AND id NOT IN (".MEMBERS_CATEGORY.")" + : ''; + $sql = " + SELECT id,parent,navigation_name + FROM pages + WHERE parent = :id + AND active = true + $includedPages + $memberPages + ORDER BY parent,pos"; // AND id != ".MEMBERS_CATEGORY." + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + if ($row['id'] == $this->_pageId) { + $class = 'current'; + } else if (in_array($row['id'], $this->_parents)) { + $class = 'parent'; + } else { + $class = ''; + } + $navArray[] = array( + 'id' => $row['id'], + 'parent' => $row['parent'], + 'label' => $row['navigation_name'], + 'uri' => Toolkit_Template_Page::getSeoUrl( + $this->_gateway, $row['id'] + ), + 'class' => $class, + 'pages' => $this->setNavArray($row['id']) + ); + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + return $navArray; + } + + private function _getParentIds($id) + { + try { + $dbh = Toolkit_Database::getInstance(); + $sql = " + SELECT parent + FROM pages + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $parent = $stmt->fetchColumn(); + $this->_parents[] = $parent; + if ($parent == 0) { + return $this->_parents; + } else { + return $this->_getParentIds($parent); + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } +} + diff --git a/Toolkit/Template/Navigation/Factory.php b/Toolkit/Template/Navigation/Factory.php new file mode 100644 index 0000000..52c76e5 --- /dev/null +++ b/Toolkit/Template/Navigation/Factory.php @@ -0,0 +1,116 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_Factory + * + * Description of Toolkit_Template_Navigation_Factory + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_Factory + extends Toolkit_NavigationFactoryAbstract +{ + /** + * Description for $_gateway + * + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access private + */ + private $_gateway; + + /** + * Sets gateway + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * + * @access public + * @return void + */ + public function setGateway(Toolkit_Toolbox_PageGatewayAbstract $gateway) + { + $this->_gateway = $gateway; + } + + /** + * NOTE: You have different renderers that you can choose for the main + * navigation. + * Toolkit/Template/Navigation/SideNavigation.php + * + * Renderers: all renderers use HTML_Menu which renders ul li + * DirectTreeLastLi = with id in the last li element + * DirectTreeUlId = with id in the main ul element + * DirectTreeLiId = with id on the current li element + * DirectTreeSideNavTitle = adds the page title above sidenav + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * + * @access public + * @return Toolkit_Template_Navigation_SideNavigation + */ + public function createSideNav( + Toolkit_Toolbox_PageGatewayAbstract $gateway = null + ) { + return new Toolkit_Template_Navigation_SideNavigation( + new HTML_Menu(), + new Toolkit_Template_Navigation_Renderer_DirectTreeSideNavTitle($this->_gateway) + ); + } + + /** + * New main nav added can use + * Toolkit_Template_Navigation_MainNavigationAllInOne + * Which will create a side nav that includes all main level pages + * + * NOTE: You have different renderers that you can choose for the main + * navigation. And you can choose from a static or dynamic setup. + * 1) for Dynamic setup use + * Toolkit_Template_Navigation_MainNavigationDynamic + * 2) to edit the static one edit the file + * Toolkit/Template/Navigation/MainNavigationStatic.php + * 3) with either of these navigation objects you can use a different + * renderer. + * + * Renderers: all renderers use HTML_Menu which renders ul li + * DirectTreeLastLi = with id in the last li element + * DirectTreeUlId = with id in the main ul element + * DirectTreeLiId = with id on the current li element + * + * @access public + * @return Toolkit_Template_Navigation_MainNavigationDynamic + */ + public function createMainNav() + { + return new Toolkit_Template_Navigation_MainNavigationDynamic( + new HTML_Menu(), + /** + * new Toolkit_Template_Navigation_Renderer_DirectTreeLiId( + * $this->_gateway, + * 'current' + * ) + */ + new Toolkit_Template_Navigation_Renderer_DirectTreeLastLi( + 'lastli' + ) + ); + } +} +?> diff --git a/Toolkit/Template/Navigation/MainNavigationAbstract.php b/Toolkit/Template/Navigation/MainNavigationAbstract.php new file mode 100644 index 0000000..69accb3 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationAbstract.php @@ -0,0 +1,103 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_MainNavigationAbstract + * + * Description of Toolkit_Template_Navigation_MainNavigationAbstract + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +abstract class Toolkit_Template_Navigation_MainNavigationAbstract + extends Toolkit_NavigationAbstract implements Toolkit_INavigation +{ + // {{{ __construct() + + /** + * Class constructor + * + * @param HTML_Menu $menu + * @param HTML_Menu_Renderer $rEngine + * + * @access public + */ + public function __construct( + HTML_Menu $menu, + HTML_Menu_Renderer $rEngine + ) { + $this->menu = $menu; + $this->rEngine = $rEngine; + } + + // }}} + // {{{ setNavTemplates() + + /** + * Set nav templates + * + * @return void + * @access protected + */ + protected function setNavTemplates() + { + $tpl = '{Title}'; + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_INACTIVE, + sprintf($tpl, '{url}', '', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVE, + sprintf($tpl, '{url}', 'id="current"', '{Title}') + ); + $this->rEngine->setEntryTemplate( + HTML_MENU_ENTRY_ACTIVEPATH, + sprintf($tpl, '{url}', '', '{Title}') + ); + } + + // }}} + // {{{ setCurrentIndex() + + /** + * Set current index + * + * @access protected + * @return void + */ + protected function setCurrentIndex() + { + $this->menu->forceCurrentIndex($_GET['catid']); + } + + // }}} + // {{{ getNavSructure() + + /** + * Create a static array of nav items to use + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure() {} + + // }}} +} +?> diff --git a/Toolkit/Template/Navigation/MainNavigationAllInOne.php b/Toolkit/Template/Navigation/MainNavigationAllInOne.php new file mode 100644 index 0000000..36e45d9 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationAllInOne.php @@ -0,0 +1,123 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_MainNavigationAllInOne + * + * Description of Toolkit_Template_Navigation_MainNavigationDynamic + * + * @category Toolkit + * @package Template/Navigation + * @author Steve Sutton + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_MainNavigationAllInOne + extends Toolkit_Template_Navigation_MainNavigationAbstract +{ + + /** + * Recursive function to create a multi dimensional array for sub nav + * + * create tree (A) at the starting page level, pass the tree up to + * parent page, where tree (B) is created for that level. append + * tree A to tree B as a sub under the correct parent + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway + * @param integer $id id to get subtree for + * @param array $tree subtree created to be + * passed up to the parent + * level + * @param integer $appendTo pageId to append the + * passed up subtree to + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id + ) { + static $currentPage; + if (!$currentPage) { + $currentPage = $gateway->findNavItem($id); + $this->_currentPage = $currentPage['navigation_name']; + $subPages = $gateway->findAllByParent(0); + } else { + $subPages = $gateway->findAllByParent($id); + } + $nav = array(); + foreach ($subPages as $subPage) { + // no home page in sub nav + if (defined('MEMBERS_CATEGORY') && MEMBERS_CATEGORY) { + if ( ($subPage['parent'] != MEMBERS_CATEGORY) + && $subPage['active'] + ) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } else { + if ($subPage['active']) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } + $isSubPage = $this->isSubOfPage($currentPage['id'], $subPage['id']); + if ($isSubPage) { + $nav[$subPage['id']]['sub'] + = $this->getNavStructure($gateway, $subPage['id']); + } + } + return $nav; + } + + /** + * Checks to see if the given $id is a sub page of the $parent + * + * @param type $id id of page to check + * @param type $parent Parent id to check + * + * @return boolean + */ + private function isSubOfPage($id, $parent) + { + if ($id == $parent) { + return true; + } + if ($id == 0 || $parent == 0) { + return false; + } + try { + $dbh = Toolkit_Database::getInstance(); + $sql = " + SELECT parent + FROM pages + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $id = $stmt->fetchColumn(); + return $this->isSubOfPage($id, $parent); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } +} diff --git a/Toolkit/Template/Navigation/MainNavigationDynamic.php b/Toolkit/Template/Navigation/MainNavigationDynamic.php new file mode 100644 index 0000000..8e3c079 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationDynamic.php @@ -0,0 +1,104 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Navigation_MainNavigationDynamic + * + * Description of Toolkit_Template_Navigation_MainNavigationDynamic + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_MainNavigationDynamic + extends Toolkit_Template_Navigation_MainNavigationAbstract +{ + // {{{ getNavSructure() + + /** + * Recursive function to create a multi dimensional array for sub nav + * + * create tree (A) at the starting page level, pass the tree up to + * parent page, where tree (B) is created for that level. append + * tree A to tree B as a sub under the correct parent + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway + * @param integer $id id to get subtree for + * @param array $tree subtree created to be + * passed up to the parent + * level + * @param integer $appendTo pageId to append the + * passed up subtree to + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id, + array $tree = null, + $appendTo = null + ) { + $id = 0; + $currentPage = $gateway->findNavItem($id); + $this->_currentPage = $currentPage['navigation_name']; + + $subPages = $gateway->findAllByParent($id); + + $nav = array(); + foreach ($subPages as $subPage) { + // no home page in sub nav + if (defined('MEMBERS_CATEGORY') && MEMBERS_CATEGORY) { + if ( ($subPage['parent'] != MEMBERS_CATEGORY) + && $subPage['active'] + ) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } else { + if ($subPage['active']) { + $nav[$subPage['id']] = array( + 'Title' => htmlspecialchars($subPage['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $subPage['id']) + ); + } + } + } + + if (is_array($tree) && array_key_exists($appendTo, $nav)) { + $nav[$appendTo]['sub'] = $tree; + } + + if ($currentPage['parent'] != 0) { + return $this->getNavStructure( + $gateway, + $currentPage['parent'], + $nav, + $id + ); + } else { + return $nav; + } + } + + // }}} +} +?> diff --git a/Toolkit/Template/Navigation/MainNavigationStatic.php b/Toolkit/Template/Navigation/MainNavigationStatic.php new file mode 100644 index 0000000..9efce29 --- /dev/null +++ b/Toolkit/Template/Navigation/MainNavigationStatic.php @@ -0,0 +1,71 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_Navigation_MainNavigationStatic + * + * Description of Toolkit_Template_Navigation_MainNavigationStatic + * + * @category Toolkit + * @package Template/Navigation + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Navigation_MainNavigationStatic + extends Toolkit_Template_Navigation_MainNavigationAbstract +{ + // {{{ getNavSructure() + + /** + * Create a static array of nav items to use + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox gateway + * @param integer $id Not used for static nav + * + * @return array navigational array hash + * @access public + */ + public function getNavStructure( + Toolkit_Toolbox_GatewayAbstract $gateway, + $id = null + ) { + $staticPages = array( + HOME_ID, // Home Page + 2, // The GLM Associate + 10, // Contact Gaslight Media + 81, // Services Offered + 86, // About Gaslight Media + ); + + $nav = array(); + + foreach ($staticPages as $pageId) { + // Home Page + $page = $gateway->findNavItem($pageId); + $nav[$pageId] = array( + 'Title' => htmlspecialchars($page['navigation_name']), + 'url' => Toolkit_Template_Page::getSeoUrl($gateway, $pageId) + ); + } + + return $nav; + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/Renderer/DirectTreeLastLi.php b/Toolkit/Template/Navigation/Renderer/DirectTreeLastLi.php new file mode 100644 index 0000000..28f43db --- /dev/null +++ b/Toolkit/Template/Navigation/Renderer/DirectTreeLastLi.php @@ -0,0 +1,97 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DirectTreeRendererLastLi.php,v 1.2 2010/07/27 19:14:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Renderer to create a LI list that has an id on the last element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Navigation_Renderer_DirectTreeLastLi + extends HTML_Menu_DirectTreeRenderer +{ + // {{{ properties + + /** + * Id to be assigned to last LI + * @var string + * @access private + */ + private $_id = null; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * @param string $id id to be assigned to last li + * + * @return void + * @access public + */ + public function __construct($id = null) + { + if (!is_null($id)) { + $this->_id = $id; + } + } + + // }}} + // {{{ finishMenu() + + /** + * Rendering before finishing + * + * if an id must be assigned to the last li element, then extract that + * element from the string and adjust the opening template + * + * @param integer $level Parameter description (if any) ... + * + * @return void + * @access public + */ + function finishMenu($level) + { + parent::finishMenu($level); + if (!is_null($this->_id)) { + $dom = new DOMDocument(); + $htmlUTF8 = mb_convert_encoding($this->_html, 'HTML-ENTITIES', 'UTF-8'); + @$dom->loadHTML($htmlUTF8); + + $uls = $dom->getElementsByTagName('ul'); + $ul = $uls->item(0); + $ul->lastChild->setAttribute('id', $this->_id); + + // Prevent auto tags and doctype from being added to the HTML + $this->_html = substr( + $dom->saveXML($dom->getElementsByTagName('ul')->item(0)), + 0 + ); + } + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/Renderer/DirectTreeLiId.php b/Toolkit/Template/Navigation/Renderer/DirectTreeLiId.php new file mode 100644 index 0000000..1b81bc8 --- /dev/null +++ b/Toolkit/Template/Navigation/Renderer/DirectTreeLiId.php @@ -0,0 +1,121 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DirectTreeRendererLastLi.php,v 1.2 2010/07/27 19:14:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Renderer to create a LI list that has an id on the last element + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Navigation_Renderer_DirectTreeLiId + extends HTML_Menu_DirectTreeRenderer +{ + // {{{ properties + + /** + * Id to be assigned to last LI + * @var string + * @access private + */ + private $_id = null; + + /** + * Database gateway for toolbox + * @var string + * @access private + */ + private $_gateway; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Gateway + * @param string $id id to be assigned to last li + * + * @return void + * @access public + */ + public function __construct( + Toolkit_Toolbox_PageGatewayAbstract $gateway, + $id = null + ) { + $this->_gateway = $gateway; + + if (!is_null($id)) { + $this->_id = $id; + } + } + + // }}} + // {{{ finishMenu() + + /** + * Rendering before finishing + * + * if an id must be assigned to the last li element, then extract that + * element from the string and adjust the opening template + * + * @param integer $level Parameter description (if any) ... + * + * @return void + * @access public + */ + function finishMenu($level) + { + parent::finishMenu($level); + if (!is_null($this->_id)) { + $dom = new DOMDocument(); + $htmlUTF8 = mb_convert_encoding($this->_html, 'HTML-ENTITIES', 'UTF-8'); + @$dom->loadHTML($htmlUTF8); + + $xpath = new DOMXPath($dom); + $element = $xpath->query("//*[@id='{$this->_id}']")->item(0); + + if ($pageId = filter_input(INPUT_GET, 'catid', FILTER_VALIDATE_INT)) { + $topParent = $this->_gateway->findTopParent($pageId); + $page = $this->_gateway->find($topParent); + $nodes = $dom->getElementsByTagName('a'); + foreach ($nodes as $node) { + if ($node->nodeValue == $page['navigation_name']) { + // uncomment to put id on parent node + // $node = $node->parentNode; + $node->setAttribute('id', $this->_id); + } + } + } + + // Prevent auto tags and doctype from being added to the HTML + $this->_html = substr( + $dom->saveXML($dom->getElementsByTagName('ul')->item(0)), + 0 + ); + } + } + + // }}} +} diff --git a/Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php b/Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php new file mode 100644 index 0000000..87e0da6 --- /dev/null +++ b/Toolkit/Template/Navigation/Renderer/DirectTreeSideNavTitle.php @@ -0,0 +1,97 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: DirectTreeRendererSideNavTitle.php,v 1.1 2010/07/22 19:59:02 jamie Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Render the side nav w/ the top parent as a header above the nav + * + * @category Toolkit + * @package Toolkit_Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_Template_Navigation_Renderer_DirectTreeSideNavTitle + extends HTML_Menu_DirectTreeRenderer +{ + // {{{ properties + + /** + * Page gateway to use + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access private + */ + private $_gateway; + private $_useTitleAsLink = false; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param Toolkit_Toolbox_PageGatewayAbstract $gateway Page gateway to use + * + * @return void + * @access public + */ + public function __construct( + Toolkit_Toolbox_PageGatewayAbstract $gateway, + $useTitleAsLink = false + ) { + $this->_gateway = $gateway; + $this->_useTitleAsLink = $useTitleAsLink; + } + + // }}} + + // {{{ finishMenu() + + /** + * Render nav with header before it + * + * Render the entire nav, then prepend the top level parent pages + * navigation name as a head above the nav + * + * @param integer $level Parameter description (if any) ... + * + * @return void + * @access public + */ + public function finishMenu($level) + { + parent::finishMenu($level); + $topParentId = $this->_gateway->findTopParent($_GET['catid']); + $page = $this->_gateway->find($topParentId); + if ($this->_useTitleAsLink) { + $link = Toolkit_Template_Page::getSeoUrl( + $this->_gateway, $topParentId + ); + } + $title + = ($this->_useTitleAsLink) + ? "{$page['navigation_name']}" + : "{$page['navigation_name']}"; + $this->_html = "

    {$title}

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

    Sorry this page is down!

    '; + } +} +?> diff --git a/Toolkit/Template/Page/BodyFactory.php b/Toolkit/Template/Page/BodyFactory.php new file mode 100644 index 0000000..d5f7000 --- /dev/null +++ b/Toolkit/Template/Page/BodyFactory.php @@ -0,0 +1,218 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_BodyFactory + * + * Description of Toolkit_Template_Page_BodyFactory + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_BodyFactory +{ + // {{{ properties + + /** + * description of $_breadCrumbsFactory + * + * @var string + * @access private + */ + private $_breadCrumbsFactory; + + /** + * description of $_pageGateway + * + * @var string + * @access private + */ + private $_pageGateway; + + /** + * description of $_paragraphGateway + * + * @var string + * @access private + */ + private $_paragraphGateway; + + /** + * description of $_cache + * + * @var string + * @access private + */ + private $_cache; + + /** + * description of $_keywordReplacement + * + * @var string + * @access private + */ + private $_keywordReplacement; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory breadCrumbsFactory + * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway pageGateway + * @param Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway paragraphGateway + * @param Toolkit_Template_KeywordReplacement $keywordReplacement keywordReplacement + * @param Cache_Lite $cache cache + * + * @access public + */ + public function __construct( + Toolkit_BreadCrumbsFactory $breadCrumbsFactory, + Toolkit_Toolbox_PageGatewayAbstract $pageGateway, + Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway, + Toolkit_Template_KeywordReplacement $keywordReplacement, + Cache_Lite $cache + ) { + $this->_breadCrumbsFactory = $breadCrumbsFactory; + $this->_pageGateway = $pageGateway; + $this->_paragraphGateway = $paragraphGateway; + $this->_keywordReplacement = $keywordReplacement; + $this->_cache = $cache; + + } + + // }}} + // {{{ getPageBodyBuilder() + + /** + * description of getPageBodyBuilder + * + * @param string $id ID + * + * @return \Toolkit_Members_SiteMapPage|\Toolkit_Template_Page_SiteMap + * |\Toolkit_Template_Page_Bad|\Toolkit_Template_Page_GoogleSearch + * |\Toolkit_Template_Page_Member|\Toolkit_Template_Page_Toolbox + * @access public + */ + public function getPageBodyBuilder($id) + { + $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 + ); + } + } + + // }}} +} diff --git a/Toolkit/Template/Page/FileLink/Abstract.php b/Toolkit/Template/Page/FileLink/Abstract.php new file mode 100644 index 0000000..3c142fc --- /dev/null +++ b/Toolkit/Template/Page/FileLink/Abstract.php @@ -0,0 +1,151 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id:$ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Abstract base class for file links + * + * Long description (if any) ... + * + * @category Toolkit_Template + * @package Template + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +abstract class Toolkit_Template_Page_FileLink_Abstract +{ + // {{{ properties + + + /** + * Database Id + * @var integer + * @access protected + */ + protected $id; + + /** + * Filename + * @var string + * @access protected + */ + protected $filename; + + /** + * Size in bytes of file + * @var integer + * @access protected + */ + protected $bytes; + + /** + * Type of file + * @var string + * @access protected + */ + protected $type; + + /** + * Text to display for link + * @var string + * @access protected + */ + protected $urltext; + + /** + * Paragraph id file belongs to + * @var integer + * @access protected + */ + protected $paragraph; + + /** + * Position of file + * @var integer + * @access protected + */ + protected $pos; + + /** + * File link + * @var string + * @access protected + */ + protected $format = ''; + + /** + * File extension + * @var string + * @access protected + */ + protected $fileExtension; + + // }}} + // {{{ __construct() + + + /** + * Constructor + * + * @param Toolkit_Toolbox_FileExtension $fileExtension file extension helper + * + * @return void + * @access public + */ + public function __construct(Toolkit_Toolbox_FileExtension $fileExtension) + { + $this->fileExtension = $fileExtension; + } + + // }}} + // {{{ readFileArray() + + + /** + * Reads the file array of info and populates the object + * + * @param array $file file data + * + * @return void + * @access public + */ + public function readFileArray (array $file) + { + foreach ($file as $key => $value) { + $this->$key = $value; + } + } + + // }}} + // {{{ getLink() + + /** + * Abstract method to subclass + * + * generates the appropriate link for the type of file + * + * @access public + */ + abstract public function getLink(); + + // }}} +} diff --git a/Toolkit/Template/Page/FileLink/Factory.php b/Toolkit/Template/Page/FileLink/Factory.php new file mode 100644 index 0000000..fca84a0 --- /dev/null +++ b/Toolkit/Template/Page/FileLink/Factory.php @@ -0,0 +1,50 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_FileLink_Factory + * + * Description of Toolkit_Template_Page_FileLink_Factory + * + * @category Toolkit + * @package Template/Page/FileLink + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_FileLink_Factory +{ + /** + * Create Link Renderer + * + * @param array $file File array + * + * @return object Either Image or File object + * @access public + */ + static public function createLinkRenderer(array $file) + { + $fileType = substr($file['filename'], 0, 2); + $fileExt = new Toolkit_Toolbox_FileExtension; + $renderer = ($fileType == 'is') + ? new Toolkit_Template_Page_FileLink_Image($fileExt) + : new Toolkit_Template_Page_FileLink_File($fileExt); + + $renderer->readFileArray($file); + return $renderer; + } +} diff --git a/Toolkit/Template/Page/FileLink/File.php b/Toolkit/Template/Page/FileLink/File.php new file mode 100644 index 0000000..bd67023 --- /dev/null +++ b/Toolkit/Template/Page/FileLink/File.php @@ -0,0 +1,57 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + + +/** + * Toolkit_Template_Page_FileLink_File + * + * Description of Toolkit_Template_Page_FileLink_File + * + * @category Toolkit + * @package Template/Page/FileLink + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_FileLink_File + extends Toolkit_Template_Page_FileLink_Abstract +{ + // {{{ getLink() + + /** + * Gets the link of a file + * + * @return string $link Formatted string + * @access public + */ + public function getLink() + { + $folder = substr($this->filename, 2, 2); + $urltext = urlencode($this->urltext); + $url = UPLOADED_FILES . "_ORIGINAL_/{$this->filename}"; + + $link = sprintf( + $this->format, + $this->fileExtension->getClassForType($this->filename), + $url, + $this->urltext + ); + return $link; + } + + // }}} +} diff --git a/Toolkit/Template/Page/FileLink/Image.php b/Toolkit/Template/Page/FileLink/Image.php new file mode 100644 index 0000000..44649b4 --- /dev/null +++ b/Toolkit/Template/Page/FileLink/Image.php @@ -0,0 +1,58 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_FileLink_Image + * + * Description of Toolkit_Template_Page_FileLink_Image + * + * @category Toolkit + * @package Template/Page/FileLink + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_FileLink_Image + extends Toolkit_Template_Page_FileLink_Abstract +{ + // {{{ getLink() + + /** + * Gets link of an image + * + * @return string $link Formatted string + * @access public + */ + public function getLink() + { + $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/glm.js'; + + $folder = substr($this->filename, 2, 2); + $urltext = urlencode($this->urltext); + $url = ORIGINAL . $this->filename; + + $link = sprintf( + $this->format, + $this->fileExtension->getClassForType($this->filename), + $url, + $this->urltext + ); + return $link; + } + + // }}} +} diff --git a/Toolkit/Template/Page/GLMSearch.php b/Toolkit/Template/Page/GLMSearch.php new file mode 100644 index 0000000..32b7d55 --- /dev/null +++ b/Toolkit/Template/Page/GLMSearch.php @@ -0,0 +1,45 @@ + + * @copyright 2013 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: GLMSearch.php,v 1.5 2010/05/25 14:07:22 cscott Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_GLMSearch + * + * Description of Toolkit_Template_Page_GLMSearch + * + * @category Toolkit + * @package Template/Page + * @author Chuck Scott + * @copyright 2013 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_GLMSearch +{ + /** + * Description for getContent() + * + * @return string + * @access public + */ + public function getContent() + { + require('/var/www/server/CommonApps/GLMSearch/V1/glmSearch.inc'); + $glmSearch = new glmSearch(GLM_SEARCH_SITE, GLM_SEARCH_LOGIN, GLM_SEARCH_KEY); + $page = $glmSearch->doSearch(); + return $page; + } +} +?> diff --git a/Toolkit/Template/Page/GoogleSearch.php b/Toolkit/Template/Page/GoogleSearch.php new file mode 100644 index 0000000..3a608be --- /dev/null +++ b/Toolkit/Template/Page/GoogleSearch.php @@ -0,0 +1,42 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_GoogleSearch + * + * Description of Toolkit_Template_Page_GoogleSearch + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_GoogleSearch +{ + /** + * Description for getContent() + * + * @return string + * @access public + */ + public function getContent() + { + return '
    '; + } +} +?> diff --git a/Toolkit/Template/Page/IBody.php b/Toolkit/Template/Page/IBody.php new file mode 100644 index 0000000..3d70bef --- /dev/null +++ b/Toolkit/Template/Page/IBody.php @@ -0,0 +1,39 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_IBody + * + * Description of Toolkit_Template_Page_IBody + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +interface Toolkit_Template_Page_IBody +{ + /** + * Description of getContent + * + * @access public + * @return unknown + */ + public function getContent(); +} +?> diff --git a/Toolkit/Template/Page/Member.php b/Toolkit/Template/Page/Member.php new file mode 100644 index 0000000..3eff26d --- /dev/null +++ b/Toolkit/Template/Page/Member.php @@ -0,0 +1,404 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_Member + * + * Description of Toolkit_Template_Page_Member + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_Member extends Toolkit_Template_Page_Toolbox +{ + // {{{ properties + + /** + * Description of $_configContainer + * + * @var Config_Container + * @access private + */ + private $_configContainer; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param int $id ID + * @param Toolkit_Template_Image_Factory $imageFactory Image Factory + * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory Breadcrumbs Factory + * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway Page Gateway + * @param Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway Paragraph Gateway + * @param Toolkit_Template_KeywordReplacement $keywordReplacement Keyword Replacement + * @param Cache_Lite $cache Cache + * @param Config_Container $config Config Container + * + * @access public + */ + public function __construct( + $id, + Toolkit_Template_Image_Factory $imageFactory, + Toolkit_BreadCrumbsFactory $breadCrumbsFactory, + Toolkit_Toolbox_PageGatewayAbstract $pageGateway, + Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway, + Toolkit_Template_KeywordReplacement $keywordReplacement, + Cache_Lite $cache, + Config_Container $config + ) { + $this->id = $id; + $this->imageFactory = $imageFactory; + $this->breadCrumbsFactory = $breadCrumbsFactory; + $this->pageGateway = $pageGateway; + $this->paragraphGateway = $paragraphGateway; + $this->keywordReplacement = $keywordReplacement; + $this->cache = $cache; + $this->_configContainer = $config; + } + + // }}} + + // {{{ getBreadCrumbs() + + /** + * Gets breadcrumbs html array + * + * @param int $id ID + * + * @return array + * @access public + */ + protected function getBreadCrumbs($id) + { + $stack = parent::getbreadCrumbsArray($id); + + $lastNode = array_pop($stack); + $anchor = '' . $lastNode . ''; + array_push($stack, $anchor); + + array_push($stack, 'Member Name'); + + return parent::getBreadCrumbsHtml($stack); + } + + // }}} + // {{{ _getMemberSearchResults() + + /** + * Get member search results + * + * @param int $id ID + * + * @return string $html + * @access private + */ + private function _getMemberSearchResults($id) + { + $memberMap = false; + $page = $this->pageGateway->find($id); + $html = ''; + if ($page['include_member_map']) { + $memberMap = true; + $googleMap = new Toolkit_Members_Map(); + $html = $googleMap->toHtml(); + } + + $dbh = Toolkit_Database::getInstance(); + + $searchQuery = new Toolkit_Members_SearchQueryGenerator( + true, + $this->_configContainer + ); + + $sql = $searchQuery->getQuery($dbh); + $searchList = new Toolkit_Members_SearchList( + $dbh, + 50, + null, + null, + true + ); + + $searchList->setConfig($this->_configContainer); + $searchList->setMemberMap($memberMap); + $searchList->setPageGateway($this->pageGateway); + $searchList->setQuery($sql); + // if you add any boolean field to this sort + // you'll need to make sure you have a case if the boolean field is null + // in the SearchGenerator or it will have inconsitant results + $nonMembers = $this->_configContainer->getItem('section', 'conf') + ->getItem('directive', 'nonMembers') + ->getContent(); + if ($nonMembers) { + $defaultSort = array( + 'nonmember' => 'ASC', + 'member_name' => 'ASC' + ); + } else { + $defaultSort = array( + 'member_name' => 'ASC' + ); + } + $searchList->setDefaultSort($defaultSort); + // Rendering Engine to use + $rEngine = new Structures_DataGrid_Renderer_Flexy(); + // Templating Engine to use + $tEngine = new HTML_Template_Flexy( + Toolkit_Members::getFlexyOptions() + ); + $rEngine->setContainer($tEngine); + + $html .= $searchList->toHtml($rEngine); + + return $html; + } + + // }}} + // {{{ _getMemberSearchForm() + + /** + * Gets member search form + * + * @param int $id ID + * + * @return mixed $html or mixed from Common.php + * @access private + */ + private function _getMemberSearchForm($id) + { + $page = $this->pageGateway->find($id); + $html = ''; + if ($page['include_member_map']) { + $googleMap = new Toolkit_Members_Map(); + $html = $googleMap->toHtml(); + } + $pageUrl + = ($_REQUEST['page_id']) + ? MEDIA_BASE_URL . "members-only-area/?page_id={$_REQUEST['page_id']}" + : MEDIA_BASE_URL . "index.php?catid={$_GET['catid']}"; + $form = new Toolkit_Members_UserSearchForm( + 'SearchForm', + 'get', + $pageUrl, + null, + null, + true + ); + + $res = $form->setCatid($_GET['catid']); + if (!PEAR::isError($res)) { + $dbh = Toolkit_Database::getInstance(); + $form->setPageMemberCategories($this->pageGateway); + $form->setPageMemberRegions($this->pageGateway); + $form->configureForm($dbh, $this->_configContainer); + $html .= $form->toHtml( + Toolkit_Members::getFlexyOptions(), + $this->pageGateway + ); + } else { + return Toolkit_Common::handleError($res); + } + + return $html; + } + + // }}} + // {{{ _getMemberProfilePage() + + /** + * Gets member profile page + * + * @param int $id ID + * + * @return mixed + * @access private + */ + private function _getMemberProfilePage($id) + { + try { + $profileCreator = new Toolkit_Members_ProfilePage( + Toolkit_Database::getInstance(), + $this->pageGateway, + $_GET['member_id'] + ); + + $tEngine = new HTML_Template_Flexy( + Toolkit_Members::getFlexyOptions() + ); + + $profileWriter = new Toolkit_Members_ProfileWriter( + new Cache_Lite(Toolkit_Members::getCacheOptions()), + $tEngine + ); + + $profileWriter->setTemplate('memberDetail.tpl'); + $profileWriter->attach( + new Toolkit_Members_Exposure( + $profileCreator->getMemberId(), + 'detail' + ) + ); + + $profileCreator->setCatid($id); + $profileCreator->setConfig($this->_configContainer); + $profileCreator->setImagePath(MEMBER_RESIZED); + + return $profileWriter->toHtml($profileCreator); + } catch (PEAR_Exception $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + /** + * Description for _getPageCoupons + * + * @param int $id ID + * + * @return string|void + * @access private + */ + private function _getPageCoupons($id) + { + $page = $this->pageGateway->find($id); + if (!$page['include_coupons']) { + return; + } + + $widget = new Toolkit_Coupons_PageWidget( + new Toolkit_Coupons_WebCouponFactory(), + new Toolkit_Coupons_Coupons() + ); + + $flexyOpts = Toolkit_Coupons_Controller::getFlexyOptions(); + $tEngine = new HTML_Template_Flexy($flexyOpts); + + $widget->addPageCategories( + Toolkit_Database::getInstance(), + $id + ); + + $searchForm = new Toolkit_Coupons_UserSearch( + 'coupon_search', + 'get', + MEDIA_BASE_URL . 'index.php' + ); + $searchForm->configureForm( + Toolkit_Database::getInstance(), + $id + ); + + $widget->setSearchForm($searchForm); + + $couponForm = new HTML_QuickForm( + 'coupon_form', + 'post', + MEDIA_BASE_URL . 'Toolkit/Coupons/print.php' + ); + $renderer =& $couponForm->defaultRenderer(); + $renderer->clearAllTemplates(); + return $widget->toHtml($couponForm, $tEngine, 'coupons.html'); + } + + private function _isMemberActive($memberId) + { + try { + $dbh = Toolkit_Database::getInstance(); + $sql = " + SELECT active + FROM member + WHERE member_id = :member_id"; + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':member_id', $memberId, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + + } + // {{{ getContent() + + /** + * Description of getContent() + * + * @return string + * @access public + */ + public function getContent() + { + $GLOBALS['bottomScripts'][] + = MEDIA_APP_BASE_URL . 'libjs/member-link.js'; + $breadCrumbsBuilder = $this->breadCrumbsFactory->createBreadCrumbsHelper(); + $page = $this->pageGateway->find($this->id); + + $coupons = null; + if (defined('COUPONS') && COUPONS) { + $coupons = $this->_getPageCoupons($this->id); + } + + if ($memberId = filter_input(INPUT_GET, 'member_id', FILTER_VALIDATE_INT)) { + // check and see if the member is inactive + // if they are then don't show bread crumb and give out 404 header + if (!$this->_isMemberActive($memberId)) { + header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); + $badPage = new Toolkit_Template_Page_Bad(); + return $badPage->getContent(); + } else { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $profile = $this->_getMemberProfilePage($this->id); + return $breadCrumbs . + $profile; + } + } elseif (!$page['search_form']) { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $searchResults = $this->_getMemberSearchResults($this->id); + $secondaryParagraphs = $this->getSecondaryParagraphs($this->id); + $primaryParagraph = $this->getPrimaryParagraph($this->id); + + return $breadCrumbs . + $primaryParagraph . + $searchResults . + $coupons . + $secondaryParagraphs; + } elseif (isset($_GET['search'])) { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $searchResults = $this->_getMemberSearchResults($this->id); + + return $breadCrumbs . + $searchResults; + } else { + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $searchForm = $this->_getMemberSearchForm($this->id); + $secondaryParagraphs = $this->getSecondaryParagraphs($this->id); + $primaryParagraph = $this->getPrimaryParagraph($this->id); + + return $breadCrumbs . + $primaryParagraph . + $searchForm . + $coupons . + $secondaryParagraphs; + } + } + + // }}} +} diff --git a/Toolkit/Template/Page/SiteMap.php b/Toolkit/Template/Page/SiteMap.php new file mode 100644 index 0000000..6cf1a99 --- /dev/null +++ b/Toolkit/Template/Page/SiteMap.php @@ -0,0 +1,237 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_SiteMap + * + * Description of Toolkit_Template_Page_SiteMap + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_SiteMap +{ + // {{{ properties + + /** + * PDO + * + * @var PDO + * @access private + */ + private $_dbh; + + /** + * description of $_pageGateway + * + * @var string + * @access private + */ + private $_pageGateway; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $dbh PDO + * @param string $pageGatweway Page Gateway + * + * @access public + */ + public function __construct(PDO $dbh, $pageGatweway) + { + $this->_dbh = $dbh; + $this->_pageGateway = $pageGatweway; + } + + // }}} + + // {{{ getContent() + + /** + * Description of getContent() + * + * @return HTML_Template_Flexy + * @access public + */ + public function getContent() + { + $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'css/siteMap.css'; + $navArray = $this->getNavArray(0); + $page = new stdClass(); + $tpl = new HTML_Template_Flexy( + $GLOBALS['flexyOptions'] + ); + $page->nav = $navArray; + $tpl->compile('siteMap.html'); + return $tpl->bufferedOutputObject($page); + } + + // }}} + + /** + * Description of getNavArray + * + * @param string $parent Parent + * + * @return array + * @throws Toolkit_Template_Exception + * @access public + */ + public function getNavArray($parent) + { + if ( defined('MEMBERS_CATEGORY') + && defined('MEMBERS_DB') + && MEMBERS_DB + ) { + $sql = " + SELECT id, navigation_name, parent, include_members + FROM pages + WHERE parent = :parent + AND active = true + AND id != " . MEMBERS_CATEGORY . " + ORDER BY parent, pos"; + } else { + $sql = " + SELECT id, navigation_name, parent + FROM pages + WHERE parent = :parent + AND active = true + ORDER BY parent, pos"; + } + + try { + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam( + ':parent', + $parent, + PDO::PARAM_INT + ); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $nav[$row['id']] = array( + 'label' => $row['navigation_name'], + 'url' => Toolkit_Template_Page::getSeoUrl( + $this->_pageGateway, + $row['id'] + ) + ); + $subs = array(); + if ($row['include_members']) { + $subs = $this->_getMembersForPage($row['id']); + } + $subs2 = $this->getNavArray($row['id']); + if ($subs2) { + foreach ($subs2 as $subsub) { + $subs[] = $subsub; + } + } + if ($subs) { + $nav[$row['id']]['subs'] = $subs; + } + } + return $nav; + } catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); + throw new Toolkit_Template_Exception( + 'Unable to fetch pages for sitemap' + ); + } + } + + private function _getMembersForPage($pageId) + { + $members = array(); + $memberCats = array(); + $memberRegs = array(); + try { + // get member categories for the page + $sql = " + SELECT * + FROM toolbox.member_categories2toolbox_pages + WHERE page = :page"; + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(":page", $pageId, PDO::PARAM_INT); + $stmt->execute(); + while ($memberCategory = $stmt->fetch(PDO::FETCH_ASSOC)) { + $memberCats[] = $memberCategory['category']; + } + // get member regions for the page + $sql = " + SELECT * + FROM toolbox.member_regions2toolbox_pages + WHERE page = :page"; + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(":page", $pageId, PDO::PARAM_INT); + $stmt->execute(); + while ($memberRegions = $stmt->fetch(PDO::FETCH_ASSOC)) { + $memberRegs[] = $memberRegions['region']; + } + // if they're both empty then get list of all members + $where = array("active"); + if (!empty($memberCats)) { + $where[] = "member_id IN ( + SELECT member_id + FROM member_category + WHERE category_id IN (" . implode(',', $memberCats) . "))"; + } + if (!empty($memberRegs)) { + $where[] = "( + region IN (" . implode(',', $memberRegs) . ") + OR + region IS NULL)"; + + } + $sql = " + SELECT member_id,member_name + FROM member"; + if (!empty($where)) { + $sql .= " WHERE " . implode(' AND ', $where); + } + $sql .= " ORDER BY member_name"; + $stmt = $this->_dbh->query($sql); + while ($member = $stmt->fetch(PDO::FETCH_ASSOC)) { + $memberName = str_replace(' ', '-', $member['member_name']); + $pattern = '/[\/#&?\'"]|amp;/'; + $name = preg_replace( + $pattern, + '', + strip_tags(strtolower(trim($memberName))) + ); + $url = MEDIA_BASE_URL . "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; + } +} +?> diff --git a/Toolkit/Template/Page/Toolbox.php b/Toolkit/Template/Page/Toolbox.php new file mode 100644 index 0000000..1e50f90 --- /dev/null +++ b/Toolkit/Template/Page/Toolbox.php @@ -0,0 +1,452 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.5 2010/05/25 14:07:22 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Template_Page_Toolbox + * + * Description of Toolkit_Template_Page_Toolbox + * + * @category Toolkit + * @package Template/Page + * @author Jamie Kahgee + * @copyright 2012 Gaslight Media + * @license Gaslight Media + * @release Release: $id$ + * @link <> + */ +class Toolkit_Template_Page_Toolbox implements Toolkit_Template_Page_IBody +{ + // {{{ properties + + + /** + * Description of $id + * + * @var int + * @access protected + */ + protected $id; + + /** + * Description of $imageFactory + * + * @var Toolkit_Template_Image_Factory + * @access protected + */ + protected $imageFactory; + + /** + * Description of $breadCrumbsFactory + * + * @var Toolkit_BreadCrumbsFactory + * @access protected + */ + protected $breadCrumbsFactory; + + /** + * Description of $pageGateway + * + * @var Toolkit_Toolbox_PageGatewayAbstract + * @access protected + */ + protected $pageGateway; + + /** + * Description of $paragraphGateway + * + * @var Toolkit_Toolbox_ParagraphGatewayAbstract + * @access protected + */ + protected $paragraphGateway; + + /** + * Description of $keywordReplacement + * + * @var Toolkit_Template_KeywordReplacement + * @access protected + */ + protected $keywordReplacement; + + /** + * Description of $cache + * + * @var Cache_Lite + * @access protected + */ + protected $cache; + + /** + * Description of $photoGallery + * + * @var Toolkit_Photos_Gallery + * @access protected + */ + protected $photoGallery; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param int $id ID + * @param Toolkit_Template_Image_Factory $imageFactory imageFactory + * @param Toolkit_BreadCrumbsFactory $breadCrumbsFactory breadCrumbsFactory + * @param Toolkit_Toolbox_PageGatewayAbstract $pageGateway Page Gateway + * @param Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway Paragraph Gateway + * @param Toolkit_Template_KeywordReplacement $keywordReplacement Keyword Replacement + * @param Cache_Lite $cache Cache + * @param Toolkit_Photos_Gallery $photoGallery Photo Gallery + * + * @throws RuntimeException + * @access public + */ + public function __construct( + $id, + Toolkit_Template_Image_Factory $imageFactory, + Toolkit_BreadCrumbsFactory $breadCrumbsFactory, + Toolkit_Toolbox_PageGatewayAbstract $pageGateway, + Toolkit_Toolbox_ParagraphGatewayAbstract $paragraphGateway, + Toolkit_Template_KeywordReplacement $keywordReplacement, + Cache_Lite $cache, + Toolkit_Photos_Gallery $photoGallery = null + ) { + if (!filter_var($id, FILTER_VALIDATE_INT)) { + throw new RuntimeException( + "`$id` is not a valid page id - integer required" + ); + } + $this->id = $id; + $this->imageFactory = $imageFactory; + $this->breadCrumbsFactory = $breadCrumbsFactory; + $this->pageGateway = $pageGateway; + $this->paragraphGateway = $paragraphGateway; + $this->keywordReplacement = $keywordReplacement; + $this->cache = $cache; + $this->photoGallery = $photoGallery; + } + + // }}} + + // {{{ getContent() + + /** + * Get content + * + * @return string + * @access public + */ + public function getContent() + { + $breadCrumbsBuilder = $this->breadCrumbsFactory->createBreadCrumbsHelper(); + $breadCrumbs = $breadCrumbsBuilder->toHtml($this->id); + $secondaryParagraphs = $this->getSecondaryParagraphs($this->id); + $primaryParagraph = $this->getPrimaryParagraph($this->id); + $coupons = null; + if (defined('COUPONS') && COUPONS) { + $coupons = $this->_getPageCoupons($this->id); + } + $staticPageContent = $this->getStaticPageContent($this->id); + + $photoGalleryContent = null; + if (defined('PHOTO_GALLERY') && PHOTO_GALLERY) { + $photoGalleryContent = $this->photoGallery->getPageGallery($this->id); + } + + return $breadCrumbs . + $primaryParagraph . + $staticPageContent . + $secondaryParagraphs . + $coupons . + $photoGalleryContent; + } + + // }}} + + // {{{ _getPageCoupons() + + /** + * Description for _getPageCoupons + * + * @param int $id ID + * + * @return string|void + * @access private + */ + private function _getPageCoupons($id) + { + $page = $this->pageGateway->find($id); + if (!$page['include_coupons']) { + return; + } + + $widget = new Toolkit_Coupons_PageWidget( + new Toolkit_Coupons_WebCouponFactory(), + new Toolkit_Coupons_Coupons() + ); + + $flexyOpts = Toolkit_Coupons_Controller::getFlexyOptions(); + $tEngine = new HTML_Template_Flexy($flexyOpts); + + $widget->addPageCategories( + Toolkit_Database::getInstance(), + $id + ); + + $searchForm = new Toolkit_Coupons_UserSearch( + 'coupon_search', + 'get', + MEDIA_BASE_URL . 'index.php' + ); + $searchForm->configureForm( + Toolkit_Database::getInstance(), + $id + ); + + $widget->setSearchForm($searchForm); + + $couponForm = new HTML_QuickForm( + 'coupon_form', + 'post', + MEDIA_BASE_URL . 'Toolkit/Coupons/print.php' + ); + $renderer =& $couponForm->defaultRenderer(); + $renderer->clearAllTemplates(); + return $widget->toHtml($couponForm, $tEngine, 'coupons.html'); + } + + // }}} + // {{{ getParagraphFiles() + + /** + * Description for getParagraphFiles() + * + * @param array $files Files array + * + * @return void|string + * @access protected + */ + protected function getParagraphFiles($files) + { + if (!is_array($files)) { + return; + } + + $filesList = ''; + foreach ($files as $file) { + $linkRenderer = Toolkit_Template_Page_FileLink_Factory::createLinkRenderer($file); + $filesList .= $linkRenderer->getLink(); + } + + return $filesList; + } + + // }}} + // {{{ getParagraphImage() + + /** + * Description for getParagraphImage() + * + * @param array $data Image data + * @param string $side Side image is on + * + * @return string Through Toolkit/Template/Image /Left or /Right or /Null + * @access protected + */ + protected function getParagraphImage(array $data, $side) + { + $imageBuilder = $this->imageFactory->getImageBuilder($data, $side); + return $imageBuilder->getImage(TOOLBOX_RESIZED); + } + + // }}} + // {{{ getParagraphLinks() + + /** + * Description for getParagraphLinks() + * + * @return boolean|string + * @access protected + */ + protected function getParagraphLinks() + { + if (!is_array($this->paragraphLinks)) { + return false; + } + + $links = ''; + + return $links; + } + + // }}} + // {{{ getPrimaryParagraph() + + /** + * Description for getPrimaryParagraph() + * + * @param int $id ID + * + * @return string + * @access protected + */ + protected function getPrimaryParagraph($id) + { + $cache = $this->cache->get("page-$id", 'Toolbox'); + + if ($cache) { + return $cache; + } else { + $page = $this->pageGateway->find($id); + + switch ($page['template']) { + case '2' : + case '4' : + case '5' : + $side = 'left'; + break; + + default : + $side = 'right'; + break; + } + + $html = '
    '; + $html .= "

    {$page['title']}

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

    {$paragraph['title']}

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

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

    +

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

    +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      No paragraph drafts created for this page yet

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

      No paragraphs created for this page yet

      '; // page has no paragraphs + } + + $html = $this->rootNodeStart; + + while (list($parent, $branch) = each($leaf)) { + $html .= sprintf($this->leafStart, $branch['id'], null); + + $html .= '
      '; + $html .= '[Edit] '; + $html .= $this->getActiveBall($branch); + if (count($leaf) > 1) { + $html .= $this->_getPositionSelect($branch); + } + $html .= "{$branch['title']}"; + $html .= '
      '; + + $html .= $this->leafEnd; + } + + $html .= $this->treeEnd; + return $html; + } + + // }}} + + // {{{ fetchContent() + + protected function fetchContent(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $paragraphs = $gateway->findAll($_GET['pageid']); + if (is_array($paragraphs)) { + $threads = array(); + foreach ($paragraphs as $paragraph) { + $threads[] = $paragraph; + } + + $children = array(); + while (list($key, $value) = each ($threads)) { + $children[0][$value['id']] = $value; + } + + $this->tree = $children; + } else { + $this->tree = array(); + } + } + + // }}} + // {{{ toHtml() + + public function toHtml(Toolkit_Toolbox_GatewayAbstract $gateway) + { + $GLOBALS['bottomScripts'][] = MEDIA_BASE_URL . 'Toolkit/Toolbox/libjs/paragraph-tree.js'; + $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js'; + + $this->fetchContent($gateway); + $html = parent::toHtml(); + + return "
      $html
      "; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/SearchController.php b/Toolkit/Toolbox/SearchController.php new file mode 100644 index 0000000..56fbb25 --- /dev/null +++ b/Toolkit/Toolbox/SearchController.php @@ -0,0 +1,50 @@ +configureForm(); + + $html = $searchForm->toHtml(); + + $toolbox = new GLM_TEMPLATE( NULL ); + $sql = " + SELECT id, parent, pos, active, + CASE WHEN keyword IS NOT NULL AND keyword <> '' + THEN category || ' {' || keyword || '}' + ELSE category + END AS category, + CASE WHEN active THEN 'Display' + ELSE 'Don\'t Display' + END AS active_alt + FROM bus_category + WHERE lower(category) LIKE :search"; + + $stmt = $this->registry->dbh->prepare($sql); + $stmt->bindParam(':search', strtolower("%{$_GET['q']}%"), PDO::PARAM_STR); + $stmt->execute(); + + $threads = $stmt->fetchAll(PDO::FETCH_ASSOC); + + $tree = new Toolkit_Toolbox_SearchTree(new GLM_TEMPLATE(null)); + $sortedLeafs = $tree->sortChildren($threads, true); + $html .= $tree->toHtml($sortedLeafs, $sortedLeafs[0]); + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/SearchTree.php b/Toolkit/Toolbox/SearchTree.php new file mode 100644 index 0000000..b5a4b0a --- /dev/null +++ b/Toolkit/Toolbox/SearchTree.php @@ -0,0 +1,35 @@ +%s'; + $img = $branch['active'] ? 'grnball.gif' : 'redball.gif'; + $q = urlencode(stripslashes($_GET['q'])); + return sprintf( + $activeFormat, + MEDIA_BASE_URL . "admin/toolbox.php?id={$branch['id']}&_qf__search_form=&rt=Search&q=$q", + $branch['active_alt'], + MEDIA_BASE_URL . "Toolkit/Toolbox/assets/$img", + $branch['active_alt'] + ); + } + + // }}} + // {{{ sortChildren() + + public function sortChildren(array $threads) + { + $children = array(); + while (list($key, $value) = each ($threads)) { + $children[0][$value['id']] = $value; + } + + return $children; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/TreeAbstract.php b/Toolkit/Toolbox/TreeAbstract.php new file mode 100644 index 0000000..58d2abc --- /dev/null +++ b/Toolkit/Toolbox/TreeAbstract.php @@ -0,0 +1,230 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ + +/** + * Toolkit_Toolbox_TreeAbstract + * + * Description for Toolkit_Toolbox_TreeAbstract + * + * @category Toolkit + * @package Toolbox + * @author Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +abstract class Toolkit_Toolbox_TreeAbstract +{ + // {{{ properties + + + /** + * Description for $rootNodeStart + * @var string + * @access protected + */ + protected $rootNodeStart = "
        \n"; + + /** + * Description for $subTreeStart + * @var string + * @access protected + */ + protected $subTreeStart = "\n
          \n"; + + /** + * Description for $treeEnd + * @var string + * @access protected + */ + protected $treeEnd = "\n
        \n"; + + /** + * Description for $leafStart + * @var string + * @access protected + */ + protected $leafStart = "\n\t
      • \n"; + + /** + * Description for $leafEnd + * @var string + * @access protected + */ + protected $leafEnd = "\n\t
      • \n"; + + /** + * Description for $config + * @var Config_Container + * @access protected + */ + protected $config; + + /** + * Description for $tree + * @var array + * @access protected + */ + protected $tree; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param Config_Container $config Config container + * + * @return void + * @access public + */ + public function __construct(Config_Container $config) + { + $this->config = $config; + } + + // }}} + + // {{{ getActiveBallImage() + + /** + * Description for getActiveBallImage() + * + * @param array $branch Branch array + * + * @return string + * @access protected + */ + protected function getActiveBallImage(array $branch) + { + $imgFormat = '%s'; + + $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 = '%s'; + + $show = sprintf( + $imgFormat, + ($branch['mobile_active']) ? '' : 'style="display: none;"', + MEDIA_BASE_URL . "Toolkit/Toolbox/assets/mobilemgreen.jpg", + 'Active Ball' + ); + + $hide = sprintf( + $imgFormat, + ($branch['mobile_active']) ? 'style="display: none;"' : '', + MEDIA_BASE_URL . "Toolkit/Toolbox/assets/mobilemred.jpg", + "In-active Ball" + ); + + return $show . $hide; + } + + // }}} + // {{{ getActiveBall() + + /** + * Description for getActiveBall() + * + * @param array $branch Branch array + * + * @access protected + * @return void + */ + abstract protected function getActiveBall(array $branch); + + // }}} + + // {{{ createTree() + + /** + * Description for createTree + * + * @param array $tree Description for $tree ... + * @param unknown $leaf Description for $leaf ... + * @param int $level Description for $level ... + * + * @return void + * @access protected + */ + abstract protected function createTree(array $tree, $leaf, $level = 0); + + // }}} + // {{{ fetchContent() + + /** + * Description for fetchContent + * + * @param Toolkit_Toolbox_GatewayAbstract $gateway Toolbox Gateway + * + * @return void + * @access protected + */ + abstract protected function fetchContent( + Toolkit_Toolbox_GatewayAbstract $gateway + ); + + // }}} + + // {{{ toHtml() + + /** + * Description of toHtml() + * + * @return string + * @access public + */ + public function toHtml() + { + $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'admin/main.css'; + $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'Toolkit/Toolbox/styles.css'; + $GLOBALS['topScripts'][] + = MEDIA_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js'; + + if (is_array($this->tree)) { + $html = $this->createTree($this->tree, reset($this->tree)); + } + + return $html; + } + + // }}} +} +?> diff --git a/Toolkit/Toolbox/assets/.keepme b/Toolkit/Toolbox/assets/.keepme new file mode 100644 index 0000000..e69de29 diff --git a/Toolkit/Toolbox/assets/arrow.png b/Toolkit/Toolbox/assets/arrow.png new file mode 100755 index 0000000..ee11ab4 Binary files /dev/null and b/Toolkit/Toolbox/assets/arrow.png differ diff --git a/Toolkit/Toolbox/assets/arrowClosed.png b/Toolkit/Toolbox/assets/arrowClosed.png new file mode 100755 index 0000000..3b34262 Binary files /dev/null and b/Toolkit/Toolbox/assets/arrowClosed.png differ diff --git a/Toolkit/Toolbox/assets/arrowOpen.png b/Toolkit/Toolbox/assets/arrowOpen.png new file mode 100755 index 0000000..6967dea Binary files /dev/null and b/Toolkit/Toolbox/assets/arrowOpen.png differ diff --git a/Toolkit/Toolbox/assets/collapse.png b/Toolkit/Toolbox/assets/collapse.png new file mode 100755 index 0000000..d10e051 Binary files /dev/null and b/Toolkit/Toolbox/assets/collapse.png differ diff --git a/Toolkit/Toolbox/assets/expand.png b/Toolkit/Toolbox/assets/expand.png new file mode 100755 index 0000000..38dcfc0 Binary files /dev/null and b/Toolkit/Toolbox/assets/expand.png differ diff --git a/Toolkit/Toolbox/assets/grnball.gif b/Toolkit/Toolbox/assets/grnball.gif new file mode 100755 index 0000000..5f7740b Binary files /dev/null and b/Toolkit/Toolbox/assets/grnball.gif differ diff --git a/Toolkit/Toolbox/assets/mobilemgreen.jpg b/Toolkit/Toolbox/assets/mobilemgreen.jpg new file mode 100644 index 0000000..a5fc6ce Binary files /dev/null and b/Toolkit/Toolbox/assets/mobilemgreen.jpg differ diff --git a/Toolkit/Toolbox/assets/mobilemred.jpg b/Toolkit/Toolbox/assets/mobilemred.jpg new file mode 100644 index 0000000..217826d Binary files /dev/null and b/Toolkit/Toolbox/assets/mobilemred.jpg differ diff --git a/Toolkit/Toolbox/assets/redball.gif b/Toolkit/Toolbox/assets/redball.gif new file mode 100755 index 0000000..7005133 Binary files /dev/null and b/Toolkit/Toolbox/assets/redball.gif differ diff --git a/Toolkit/Toolbox/assets/template1.gif b/Toolkit/Toolbox/assets/template1.gif new file mode 100755 index 0000000..327d943 Binary files /dev/null and b/Toolkit/Toolbox/assets/template1.gif differ diff --git a/Toolkit/Toolbox/assets/template2.gif b/Toolkit/Toolbox/assets/template2.gif new file mode 100755 index 0000000..edf3d8b Binary files /dev/null and b/Toolkit/Toolbox/assets/template2.gif differ diff --git a/Toolkit/Toolbox/assets/template3.gif b/Toolkit/Toolbox/assets/template3.gif new file mode 100755 index 0000000..16e2107 Binary files /dev/null and b/Toolkit/Toolbox/assets/template3.gif differ diff --git a/Toolkit/Toolbox/assets/template4.gif b/Toolkit/Toolbox/assets/template4.gif new file mode 100755 index 0000000..32174dd Binary files /dev/null and b/Toolkit/Toolbox/assets/template4.gif differ diff --git a/Toolkit/Toolbox/assets/template5.gif b/Toolkit/Toolbox/assets/template5.gif new file mode 100755 index 0000000..6c36b50 Binary files /dev/null and b/Toolkit/Toolbox/assets/template5.gif differ diff --git a/Toolkit/Toolbox/assets/template6.gif b/Toolkit/Toolbox/assets/template6.gif new file mode 100644 index 0000000..28d140e Binary files /dev/null and b/Toolkit/Toolbox/assets/template6.gif differ diff --git a/Toolkit/Toolbox/config.ini b/Toolkit/Toolbox/config.ini new file mode 100644 index 0000000..3d81908 --- /dev/null +++ b/Toolkit/Toolbox/config.ini @@ -0,0 +1,3 @@ +[conf] +applicationName = "Toolbox" +lockMainNavPages = Off diff --git a/Toolkit/Toolbox/fixPageNoContent.php b/Toolkit/Toolbox/fixPageNoContent.php new file mode 100644 index 0000000..8b59bad --- /dev/null +++ b/Toolkit/Toolbox/fixPageNoContent.php @@ -0,0 +1,48 @@ +beginTransaction(); +try { + $checkSql = + "SELECT id + FROM paragraphs + WHERE page = :page + AND pos = 1"; + $checkStmt = $dbh->prepare($checkSql); + $addSql = " + INSERT INTO paragraphs + (active,page,pos) + VALUES + (true,:page,1)"; + $addStmt = $dbh->prepare($addSql); + $sql = " + SELECT id + FROM pages + ORDER BY parent,pos"; + $stmt = $dbh->query($sql); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $checkStmt->bindParam( + ':page', + $row['id'], + PDO::PARAM_INT + ); + $checkStmt->execute(); + if ($checkStmt->rowCount() == 0) { + // nothing set yet need to add one + $addStmt->bindParam( + ':page', + $row['id'], + PDO::PARAM_INT + ); + $addStmt->execute(); + echo '

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

        '; + } else { + echo '

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

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

        fixing page positions

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

        fixing paragraphs positions

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